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: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-pool-stable/contracts/StablePool.sol"; import "@balancer-labs/v2-pool-utils/contracts/rates/PriceRateCache.sol"; import "@balancer-labs/v2-pool-utils/contracts/interfaces/IRateProvider.sol"; import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol"; import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ERC20Helpers.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/BalancerErrors.sol"; import "./StablePhantomPoolUserDataHelpers.sol"; /** * @dev StablePool with preminted BPT and rate providers for each token, allowing for e.g. wrapped tokens with a known * price ratio, such as Compound's cTokens. * * BPT is preminted on Pool initialization and registered as one of the Pool's tokens, allowing for swaps to behave as * single-token joins or exits (by swapping a token for BPT). Regular joins and exits are disabled, since no BPT is * minted or burned after initialization. * * Preminted BPT is sometimes called Phantom BPT, as the preminted BPT (which is deposited in the Vault as balance of * the Pool) doesn't belong to any entity until transferred out of the Pool. The Pool's arithmetic behaves as if it * didn't exist, and the BPT total supply is not a useful value: we rely on the 'virtual supply' (how much BPT is * actually owned by some entity) instead. */ contract StablePhantomPool is StablePool { using FixedPoint for uint256; using PriceRateCache for bytes32; using StablePhantomPoolUserDataHelpers for bytes; uint256 private constant _MIN_TOKENS = 2; uint256 private constant _MAX_TOKEN_BALANCE = 2**(112) - 1; uint256 private immutable _bptIndex; // Since this Pool is not joined or exited via the regular onJoinPool and onExitPool hooks, it lacks a way to // continuously pay due protocol fees. Instead, it keeps track of those internally. // Due protocol fees are expressed in BPT, which leads to reduced gas costs when compared to tracking due fees for // each Pool token. This means that some of the BPT deposited in the Vault for the Pool is part of the 'virtual' // supply, as it belongs to the protocol. uint256 private _dueProtocolFeeBptAmount; // The Vault does not provide the protocol swap fee percentage in swap hooks (as swaps don't typically need this // value), so we need to fetch it ourselves from the Vault's ProtocolFeeCollector. However, this value changes so // rarely that it doesn't make sense to perform the required calls to get the current value in every single swap. // Instead, we keep a local copy that can be permissionlessly updated by anyone with the real value. uint256 private _cachedProtocolSwapFeePercentage; event CachedProtocolSwapFeePercentageUpdated(uint256 protocolSwapFeePercentage); // Token rate caches are used to avoid querying the price rate for a token every time we need to work with it. // Data is stored with the following structure: // // [ expires | duration | price rate value ] // [ uint64 | uint64 | uint128 ] mapping(IERC20 => bytes32) private _tokenRateCaches; IRateProvider internal immutable _rateProvider0; IRateProvider internal immutable _rateProvider1; IRateProvider internal immutable _rateProvider2; IRateProvider internal immutable _rateProvider3; IRateProvider internal immutable _rateProvider4; event TokenRateCacheUpdated(IERC20 indexed token, uint256 rate); event TokenRateProviderSet(IERC20 indexed token, IRateProvider indexed provider, uint256 cacheDuration); event DueProtocolFeeIncreased(uint256 bptAmount); enum JoinKindPhantom { INIT, COLLECT_PROTOCOL_FEES } enum ExitKindPhantom { EXACT_BPT_IN_FOR_TOKENS_OUT } // The constructor arguments are received in a struct to work around stack-too-deep issues struct NewPoolParams { IVault vault; string name; string symbol; IERC20[] tokens; IRateProvider[] rateProviders; uint256[] tokenRateCacheDurations; uint256 amplificationParameter; uint256 swapFeePercentage; uint256 pauseWindowDuration; uint256 bufferPeriodDuration; address owner; } constructor(NewPoolParams memory params) StablePool( params.vault, params.name, params.symbol, _insertSorted(params.tokens, IERC20(this)), params.amplificationParameter, params.swapFeePercentage, params.pauseWindowDuration, params.bufferPeriodDuration, params.owner ) { // BasePool checks that the Pool has at least two tokens, but since one of them is the BPT (this contract), we // need to check ourselves that there are at least creator-supplied tokens (i.e. the minimum number of total // tokens for this contract is actually three, including the BPT). _require(params.tokens.length >= _MIN_TOKENS, Errors.MIN_TOKENS); InputHelpers.ensureInputLengthMatch( params.tokens.length, params.rateProviders.length, params.tokenRateCacheDurations.length ); for (uint256 i = 0; i < params.tokens.length; i++) { if (params.rateProviders[i] != IRateProvider(0)) { _updateTokenRateCache(params.tokens[i], params.rateProviders[i], params.tokenRateCacheDurations[i]); emit TokenRateProviderSet(params.tokens[i], params.rateProviders[i], params.tokenRateCacheDurations[i]); } } // The Vault keeps track of all Pool tokens in a specific order: we need to know what the index of BPT is in // this ordering to be able to identify it when balances arrays are received. Since the tokens array is sorted, // we need to find the correct BPT index in the array returned by `_insertSorted()`. // See `IVault.getPoolTokens()` for more information regarding token ordering. uint256 bptIndex; for (bptIndex = params.tokens.length; bptIndex > 0 && params.tokens[bptIndex - 1] > IERC20(this); bptIndex--) { // solhint-disable-previous-line no-empty-blocks } _bptIndex = bptIndex; // The rate providers are stored as immutable state variables, and for simplicity when accessing those we'll // reference them by token index in the full base tokens plus BPT set (i.e. the tokens the Pool registers). Due // to immutable variables requiring an explicit assignment instead of defaulting to an empty value, it is // simpler to create a new memory array with the values we want to assign to the immutable state variables. IRateProvider[] memory tokensAndBPTRateProviders = new IRateProvider[](params.tokens.length + 1); for (uint256 i = 0; i < tokensAndBPTRateProviders.length; ++i) { if (i < bptIndex) { tokensAndBPTRateProviders[i] = params.rateProviders[i]; } else if (i == bptIndex) { tokensAndBPTRateProviders[i] = IRateProvider(0); } else { tokensAndBPTRateProviders[i] = params.rateProviders[i - 1]; } } // Immutable variables cannot be initialized inside an if statement, so we must do conditional assignments _rateProvider0 = (tokensAndBPTRateProviders.length > 0) ? tokensAndBPTRateProviders[0] : IRateProvider(0); _rateProvider1 = (tokensAndBPTRateProviders.length > 1) ? tokensAndBPTRateProviders[1] : IRateProvider(0); _rateProvider2 = (tokensAndBPTRateProviders.length > 2) ? tokensAndBPTRateProviders[2] : IRateProvider(0); _rateProvider3 = (tokensAndBPTRateProviders.length > 3) ? tokensAndBPTRateProviders[3] : IRateProvider(0); _rateProvider4 = (tokensAndBPTRateProviders.length > 4) ? tokensAndBPTRateProviders[4] : IRateProvider(0); _updateCachedProtocolSwapFeePercentage(params.vault); } function getMinimumBpt() external pure returns (uint256) { return _getMinimumBpt(); } function getBptIndex() external view returns (uint256) { return _bptIndex; } function getDueProtocolFeeBptAmount() external view returns (uint256) { return _dueProtocolFeeBptAmount; } /** * @dev StablePools with two tokens may use the IMinimalSwapInfoPool interface. This should never happen since this * Pool has a minimum of three tokens, but we override and revert unconditionally in this handler anyway. */ function onSwap( SwapRequest memory, uint256, uint256 ) public pure override returns (uint256) { _revert(Errors.UNHANDLED_BY_PHANTOM_POOL); } // StablePool's `_onSwapGivenIn` and `_onSwapGivenOut` handlers are meant to process swaps between Pool tokens. // Since one of the Pool's tokens is the preminted BPT, we neeed to a) handle swaps where that tokens is involved // separately (as they are effectively single-token joins or exits), and b) remove BPT from the balances array when // processing regular swaps before delegating those to StablePool's handler. // // Since StablePools don't accurately track protocol fees in single-token joins and exit, and not only does this // Pool not support multi-token joins or exits, but also they are expected to be much more prevalent, we compute // protocol fees in a different and more straightforward way. Recall that due protocol fees are expressed as BPT // amounts: for any swap involving BPT, we simply add the corresponding protocol swap fee to that amount, and for // swaps without BPT we convert the fee amount to the equivalent BPT amount. Note that swap fees are charged by // BaseGeneralPool. // // The given in and given out handlers are quite similar and could use an intermediate abstraction, but keeping the // duplication seems to lead to more readable code, given the number of variants at play. function _onSwapGivenIn( SwapRequest memory request, uint256[] memory balancesIncludingBpt, uint256 indexIn, uint256 indexOut ) internal virtual override whenNotPaused returns (uint256 amountOut) { _cacheTokenRatesIfNecessary(); uint256 protocolSwapFeePercentage = _cachedProtocolSwapFeePercentage; // Compute virtual BPT supply and token balances (sans BPT). (uint256 virtualSupply, uint256[] memory balances) = _dropBptItem(balancesIncludingBpt); if (request.tokenIn == IERC20(this)) { amountOut = _onSwapTokenGivenBptIn(request.amount, _skipBptIndex(indexOut), virtualSupply, balances); // For given in swaps, request.amount holds the amount in. if (protocolSwapFeePercentage > 0) { _trackDueProtocolFeeByBpt(request.amount, protocolSwapFeePercentage); } } else if (request.tokenOut == IERC20(this)) { amountOut = _onSwapBptGivenTokenIn(request.amount, _skipBptIndex(indexIn), virtualSupply, balances); if (protocolSwapFeePercentage > 0) { _trackDueProtocolFeeByBpt(amountOut, protocolSwapFeePercentage); } } else { // To compute accrued protocol fees in BPT, we measure the invariant before and after the swap, then compute // the equivalent BPT amount that accounts for that growth and finally extract the percentage that // corresponds to protocol fees. // Since the original StablePool._onSwapGivenIn implementation already computes the invariant, we fully // replace it and reimplement it here to take advantage of that. (uint256 currentAmp, ) = _getAmplificationParameter(); uint256 invariant = StableMath._calculateInvariant(currentAmp, balances, true); amountOut = StableMath._calcOutGivenIn( currentAmp, balances, _skipBptIndex(indexIn), _skipBptIndex(indexOut), request.amount, invariant ); if (protocolSwapFeePercentage > 0) { // We could've stored these indices in stack variables, but that causes stack-too-deep issues. uint256 newIndexIn = _skipBptIndex(indexIn); uint256 newIndexOut = _skipBptIndex(indexOut); uint256 amountInWithFee = _addSwapFeeAmount(request.amount); balances[newIndexIn] = balances[newIndexIn].add(amountInWithFee); balances[newIndexOut] = balances[newIndexOut].sub(amountOut); _trackDueProtocolFeeByInvariantIncrement( invariant, currentAmp, balances, virtualSupply, protocolSwapFeePercentage ); } } } function _onSwapGivenOut( SwapRequest memory request, uint256[] memory balancesIncludingBpt, uint256 indexIn, uint256 indexOut ) internal virtual override whenNotPaused returns (uint256 amountIn) { _cacheTokenRatesIfNecessary(); uint256 protocolSwapFeePercentage = _cachedProtocolSwapFeePercentage; // Compute virtual BPT supply and token balances (sans BPT). (uint256 virtualSupply, uint256[] memory balances) = _dropBptItem(balancesIncludingBpt); if (request.tokenIn == IERC20(this)) { amountIn = _onSwapBptGivenTokenOut(request.amount, _skipBptIndex(indexOut), virtualSupply, balances); if (protocolSwapFeePercentage > 0) { _trackDueProtocolFeeByBpt(amountIn, protocolSwapFeePercentage); } } else if (request.tokenOut == IERC20(this)) { amountIn = _onSwapTokenGivenBptOut(request.amount, _skipBptIndex(indexIn), virtualSupply, balances); // For given out swaps, request.amount holds the amount out. if (protocolSwapFeePercentage > 0) { _trackDueProtocolFeeByBpt(request.amount, protocolSwapFeePercentage); } } else { // To compute accrued protocol fees in BPT, we measure the invariant before and after the swap, then compute // the equivalent BPT amount that accounts for that growth and finally extract the percentage that // corresponds to protocol fees. // Since the original StablePool._onSwapGivenOut implementation already computes the invariant, we fully // replace it and reimplement it here to take advtange of that. (uint256 currentAmp, ) = _getAmplificationParameter(); uint256 invariant = StableMath._calculateInvariant(currentAmp, balances, true); amountIn = StableMath._calcInGivenOut( currentAmp, balances, _skipBptIndex(indexIn), _skipBptIndex(indexOut), request.amount, invariant ); if (protocolSwapFeePercentage > 0) { // We could've stored these indices in stack variables, but that causes stack-too-deep issues. uint256 newIndexIn = _skipBptIndex(indexIn); uint256 newIndexOut = _skipBptIndex(indexOut); uint256 amountInWithFee = _addSwapFeeAmount(amountIn); balances[newIndexIn] = balances[newIndexIn].add(amountInWithFee); balances[newIndexOut] = balances[newIndexOut].sub(request.amount); _trackDueProtocolFeeByInvariantIncrement( invariant, currentAmp, balances, virtualSupply, protocolSwapFeePercentage ); } } } /** * @dev Calculate token out for exact BPT in (exit) */ function _onSwapTokenGivenBptIn( uint256 bptIn, uint256 tokenIndex, uint256 virtualSupply, uint256[] memory balances ) internal view returns (uint256 amountOut) { // Use virtual total supply and zero swap fees for joins. (uint256 amp, ) = _getAmplificationParameter(); amountOut = StableMath._calcTokenOutGivenExactBptIn(amp, balances, tokenIndex, bptIn, virtualSupply, 0); } /** * @dev Calculate token in for exact BPT out (join) */ function _onSwapTokenGivenBptOut( uint256 bptOut, uint256 tokenIndex, uint256 virtualSupply, uint256[] memory balances ) internal view returns (uint256 amountIn) { // Use virtual total supply and zero swap fees for joins (uint256 amp, ) = _getAmplificationParameter(); amountIn = StableMath._calcTokenInGivenExactBptOut(amp, balances, tokenIndex, bptOut, virtualSupply, 0); } /** * @dev Calculate BPT in for exact token out (exit) */ function _onSwapBptGivenTokenOut( uint256 amountOut, uint256 tokenIndex, uint256 virtualSupply, uint256[] memory balances ) internal view returns (uint256 bptIn) { // Avoid BPT balance for stable pool math. Use virtual total supply and zero swap fees for exits. (uint256 amp, ) = _getAmplificationParameter(); uint256[] memory amountsOut = new uint256[](_getTotalTokens() - 1); amountsOut[tokenIndex] = amountOut; bptIn = StableMath._calcBptInGivenExactTokensOut(amp, balances, amountsOut, virtualSupply, 0); } /** * @dev Calculate BPT out for exact token in (join) */ function _onSwapBptGivenTokenIn( uint256 amountIn, uint256 tokenIndex, uint256 virtualSupply, uint256[] memory balances ) internal view returns (uint256 bptOut) { uint256[] memory amountsIn = new uint256[](_getTotalTokens() - 1); amountsIn[tokenIndex] = amountIn; (uint256 amp, ) = _getAmplificationParameter(); bptOut = StableMath._calcBptOutGivenExactTokensIn(amp, balances, amountsIn, virtualSupply, 0); } /** * @dev Tracks newly charged protocol fees after a swap where BPT was not involved (i.e. a regular swap). */ function _trackDueProtocolFeeByInvariantIncrement( uint256 previousInvariant, uint256 amp, uint256[] memory postSwapBalances, uint256 virtualSupply, uint256 protocolSwapFeePercentage ) private { // To convert the protocol swap fees to a BPT amount, we compute the invariant growth (which is due exclusively // to swap fees), extract the portion that corresponds to protocol swap fees, and then compute the equivalent // amount of BPT that would cause such an increase. // // Invariant growth is related to new BPT and supply by: // invariant ratio = (bpt amount + supply) / supply // With some manipulation, this becomes: // (invariant ratio - 1) * supply = bpt amount // // However, a part of the invariant growth was due to non protocol swap fees (i.e. value accrued by the // LPs), so we only mint a percentage of this BPT amount: that which corresponds to protocol fees. // We round down, favoring LP fees. uint256 postSwapInvariant = StableMath._calculateInvariant(amp, postSwapBalances, false); uint256 invariantRatio = postSwapInvariant.divDown(previousInvariant); if (invariantRatio > FixedPoint.ONE) { // This condition should always be met outside of rounding errors (for non-zero swap fees). uint256 protocolFeeAmount = protocolSwapFeePercentage.mulDown( invariantRatio.sub(FixedPoint.ONE).mulDown(virtualSupply) ); _dueProtocolFeeBptAmount = _dueProtocolFeeBptAmount.add(protocolFeeAmount); emit DueProtocolFeeIncreased(protocolFeeAmount); } } /** * @dev Tracks newly charged protocol fees after a swap where `bptAmount` was either sent or received (i.e. a * single-token join or exit). */ function _trackDueProtocolFeeByBpt(uint256 bptAmount, uint256 protocolSwapFeePercentage) private { uint256 feeAmount = _addSwapFeeAmount(bptAmount).sub(bptAmount); uint256 protocolFeeAmount = feeAmount.mulDown(protocolSwapFeePercentage); _dueProtocolFeeBptAmount = _dueProtocolFeeBptAmount.add(protocolFeeAmount); emit DueProtocolFeeIncreased(protocolFeeAmount); } /** * Since this Pool has preminted BPT which is stored in the Vault, it cannot simply be minted at construction. * * We take advantage of the fact that StablePools have an initialization step where BPT is minted to the first * account joining them, and perform both actions at once. By minting the entire BPT supply for the initial joiner * and then pulling all tokens except those due the joiner, we arrive at the desired state of the Pool holding all * BPT except the joiner's. */ function _onInitializePool( bytes32, address sender, address, uint256[] memory scalingFactors, bytes memory userData ) internal override whenNotPaused returns (uint256, uint256[] memory) { StablePhantomPool.JoinKindPhantom kind = userData.joinKind(); _require(kind == StablePhantomPool.JoinKindPhantom.INIT, Errors.UNINITIALIZED); uint256[] memory amountsInIncludingBpt = userData.initialAmountsIn(); InputHelpers.ensureInputLengthMatch(amountsInIncludingBpt.length, _getTotalTokens()); _upscaleArray(amountsInIncludingBpt, scalingFactors); (uint256 amp, ) = _getAmplificationParameter(); (, uint256[] memory amountsIn) = _dropBptItem(amountsInIncludingBpt); // The true argument in the _calculateInvariant call instructs it to round up uint256 invariantAfterJoin = StableMath._calculateInvariant(amp, amountsIn, true); // Set the initial BPT to the value of the invariant uint256 bptAmountOut = invariantAfterJoin; // BasePool will mint bptAmountOut for the sender: we then also mint the remaining BPT to make up for the total // supply, and have the Vault pull those tokens from the sender as part of the join. // Note that the sender need not approve BPT for the Vault as the Vault already has infinite BPT allowance for // all accounts. uint256 initialBpt = _MAX_TOKEN_BALANCE.sub(bptAmountOut); _mintPoolTokens(sender, initialBpt); amountsInIncludingBpt[_bptIndex] = initialBpt; return (bptAmountOut, amountsInIncludingBpt); } /** * @dev Revert on all joins, except for the special join kind that simply pays due protocol fees to the Vault. */ function _onJoinPool( bytes32, address, address, uint256[] memory, uint256, uint256, uint256[] memory, bytes memory userData ) internal override returns ( uint256, uint256[] memory, uint256[] memory ) { JoinKindPhantom kind = userData.joinKind(); if (kind == JoinKindPhantom.COLLECT_PROTOCOL_FEES) { return _collectProtocolFees(); } _revert(Errors.UNHANDLED_BY_PHANTOM_POOL); } /** * @dev Collects due protocol fees */ function _collectProtocolFees() private returns ( uint256 bptOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts ) { uint256 totalTokens = _getTotalTokens(); // This join neither grants BPT nor takes any tokens from the sender. bptOut = 0; amountsIn = new uint256[](totalTokens); // Due protocol fees are all zero except for the BPT amount, which is then zeroed out. dueProtocolFeeAmounts = new uint256[](totalTokens); dueProtocolFeeAmounts[_bptIndex] = _dueProtocolFeeBptAmount; _dueProtocolFeeBptAmount = 0; } /** * @dev Revert on all exits. */ function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256, uint256, uint256[] memory, bytes memory userData ) internal view override returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { ExitKindPhantom kind = userData.exitKind(); // Exits typically revert, except for the proportional exit when the emergency pause mechanism has been // triggered. This allows for a simple and safe way to exit the Pool. if (kind == ExitKindPhantom.EXACT_BPT_IN_FOR_TOKENS_OUT) { _ensurePaused(); // Note that this will cause the user's BPT to be burned, which is not something that happens during // regular operation of this Pool, and may lead to accounting errors. Because of this, it is highly // advisable to stop using a Pool after it is paused and the pause window expires. (bptAmountIn, amountsOut) = _proportionalExit(balances, userData); // For simplicity, due protocol fees are set to zero. dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } else { _revert(Errors.UNHANDLED_BY_PHANTOM_POOL); } } function _proportionalExit(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { // This proportional exit function is only enabled if the contract is paused, to provide users a way to // retrieve their tokens in case of an emergency. // // This particular exit function is the only one available because it is the simplest, and therefore least // likely to be incorrect, or revert and lock funds. (, uint256[] memory balancesWithoutBpt) = _dropBptItem(balances); uint256 bptAmountIn = userData.exactBptInForTokensOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. uint256[] memory amountsOut = StableMath._calcTokensOutGivenExactBptIn( balancesWithoutBpt, bptAmountIn, // This process burns BPT, rendering the approximation returned by `_dropBPTItem` inaccurate, // so we use the real method here _getVirtualSupply(balances[_bptIndex]) ); return (bptAmountIn, _addBptItem(amountsOut, 0)); } // Scaling factors function getScalingFactor(IERC20 token) external view returns (uint256) { return _scalingFactor(token); } /** * @dev Overrides scaling factor getter to introduce the tokens' rates. */ function _scalingFactors() internal view virtual override returns (uint256[] memory scalingFactors) { // There is no need to check the arrays length since both are based on `_getTotalTokens` uint256 totalTokens = _getTotalTokens(); scalingFactors = super._scalingFactors(); // Given there is no generic direction for this rounding, it follows the same strategy as the BasePool. // prettier-ignore { if (totalTokens > 0) { scalingFactors[0] = scalingFactors[0].mulDown(getTokenRate(_token0)); } if (totalTokens > 1) { scalingFactors[1] = scalingFactors[1].mulDown(getTokenRate(_token1)); } if (totalTokens > 2) { scalingFactors[2] = scalingFactors[2].mulDown(getTokenRate(_token2)); } if (totalTokens > 3) { scalingFactors[3] = scalingFactors[3].mulDown(getTokenRate(_token3)); } if (totalTokens > 4) { scalingFactors[4] = scalingFactors[4].mulDown(getTokenRate(_token4)); } } } /** * @dev Overrides scaling factor getter to introduce the token's rate. */ function _scalingFactor(IERC20 token) internal view virtual override returns (uint256) { // Given there is no generic direction for this rounding, it follows the same strategy as the BasePool. uint256 baseScalingFactor = super._scalingFactor(token); return baseScalingFactor.mulDown(getTokenRate(token)); } // Token rates /** * @dev Returns the rate providers configured for each token (in the same order as registered). */ function getRateProviders() external view returns (IRateProvider[] memory providers) { uint256 totalTokens = _getTotalTokens(); providers = new IRateProvider[](totalTokens); // prettier-ignore { if (totalTokens > 0) { providers[0] = _rateProvider0; } else { return providers; } if (totalTokens > 1) { providers[1] = _rateProvider1; } else { return providers; } if (totalTokens > 2) { providers[2] = _rateProvider2; } else { return providers; } if (totalTokens > 3) { providers[3] = _rateProvider3; } else { return providers; } if (totalTokens > 4) { providers[4] = _rateProvider4; } else { return providers; } } } function _getRateProvider(IERC20 token) internal view returns (IRateProvider) { // prettier-ignore if (token == _token0) { return _rateProvider0; } else if (token == _token1) { return _rateProvider1; } else if (token == _token2) { return _rateProvider2; } else if (token == _token3) { return _rateProvider3; } else if (token == _token4) { return _rateProvider4; } else { _revert(Errors.INVALID_TOKEN); } } /** * @dev Returns the token rate for token. All token rates are fixed-point values with 18 decimals. * In case there is no rate provider for the provided token it returns 1e18. */ function getTokenRate(IERC20 token) public view virtual returns (uint256) { // We optimize for the scenario where all tokens have rate providers, except the BPT (which never has a rate // provider). Therefore, we return early if token is BPT, and otherwise optimistically read the cache expecting // that it will not be empty (instead of e.g. fetching the provider to avoid a cache read, since we don't need // the provider at all). if (token == this) { return FixedPoint.ONE; } bytes32 tokenRateCache = _tokenRateCaches[token]; return tokenRateCache == bytes32(0) ? FixedPoint.ONE : tokenRateCache.getRate(); } /** * @dev Returns the cached value for token's rate. * Note it could return an empty value if the requested token does not have one or if the token does not belong * to the pool. */ function getTokenRateCache(IERC20 token) external view returns ( uint256 rate, uint256 duration, uint256 expires ) { _require(_getRateProvider(token) != IRateProvider(0), Errors.TOKEN_DOES_NOT_HAVE_RATE_PROVIDER); rate = _tokenRateCaches[token].getRate(); (duration, expires) = _tokenRateCaches[token].getTimestamps(); } /** * @dev Sets a new duration for a token rate cache. It reverts if there was no rate provider set initially. * Note this function also updates the current cached value. * @param duration Number of seconds until the current token rate is fetched again. */ function setTokenRateCacheDuration(IERC20 token, uint256 duration) external authenticate { IRateProvider provider = _getRateProvider(token); _require(address(provider) != address(0), Errors.TOKEN_DOES_NOT_HAVE_RATE_PROVIDER); _updateTokenRateCache(token, provider, duration); emit TokenRateProviderSet(token, provider, duration); } /** * @dev Forces a rate cache hit for a token. * It will revert if the requested token does not have an associated rate provider. */ function updateTokenRateCache(IERC20 token) external { IRateProvider provider = _getRateProvider(token); _require(address(provider) != address(0), Errors.TOKEN_DOES_NOT_HAVE_RATE_PROVIDER); uint256 duration = _tokenRateCaches[token].getDuration(); _updateTokenRateCache(token, provider, duration); } /** * @dev Internal function to update a token rate cache for a known provider and duration. * It trusts the given values, and does not perform any checks. */ function _updateTokenRateCache( IERC20 token, IRateProvider provider, uint256 duration ) private { uint256 rate = provider.getRate(); bytes32 cache = PriceRateCache.encode(rate, duration); _tokenRateCaches[token] = cache; emit TokenRateCacheUpdated(token, rate); } /** * @dev Caches the rates of all tokens if necessary */ function _cacheTokenRatesIfNecessary() internal { uint256 totalTokens = _getTotalTokens(); // prettier-ignore { if (totalTokens > 0) { _cacheTokenRateIfNecessary(_token0); } else { return; } if (totalTokens > 1) { _cacheTokenRateIfNecessary(_token1); } else { return; } if (totalTokens > 2) { _cacheTokenRateIfNecessary(_token2); } else { return; } if (totalTokens > 3) { _cacheTokenRateIfNecessary(_token3); } else { return; } if (totalTokens > 4) { _cacheTokenRateIfNecessary(_token4); } else { return; } } } /** * @dev Caches the rate for a token if necessary. It ignores the call if there is no provider set. */ function _cacheTokenRateIfNecessary(IERC20 token) internal { // We optimize for the scenario where all tokens have rate providers, except the BPT (which never has a rate // provider). Therefore, we return early if token is BPT, and otherwise optimistically read the cache expecting // that it will not be empty (instead of e.g. fetching the provider to avoid a cache read in situations where // we might not need the provider if the cache is still valid). if (token == this) return; bytes32 cache = _tokenRateCaches[token]; if (cache != bytes32(0)) { (uint256 duration, uint256 expires) = _tokenRateCaches[token].getTimestamps(); if (block.timestamp > expires) { // solhint-disable-previous-line not-rely-on-time _updateTokenRateCache(token, _getRateProvider(token), duration); } } } function getCachedProtocolSwapFeePercentage() public view returns (uint256) { return _cachedProtocolSwapFeePercentage; } function updateCachedProtocolSwapFeePercentage() external { _updateCachedProtocolSwapFeePercentage(getVault()); } function _updateCachedProtocolSwapFeePercentage(IVault vault) private { uint256 newPercentage = vault.getProtocolFeesCollector().getSwapFeePercentage(); _cachedProtocolSwapFeePercentage = newPercentage; emit CachedProtocolSwapFeePercentageUpdated(newPercentage); } /** * @dev Overrides only owner action to allow setting the cache duration for the token rates */ function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) { return (actionId == getActionId(this.setTokenRateCacheDuration.selector)) || super._isOwnerOnlyAction(actionId); } function _skipBptIndex(uint256 index) internal view returns (uint256) { return index < _bptIndex ? index : index.sub(1); } function _dropBptItem(uint256[] memory amounts) internal view returns (uint256 virtualSupply, uint256[] memory amountsWithoutBpt) { // The initial amount of BPT pre-minted is _MAX_TOKEN_BALANCE and it goes entirely to the pool balance in the // vault. So the virtualSupply (the actual supply in circulation) is defined as: // virtualSupply = totalSupply() - (_balances[_bptIndex] - _dueProtocolFeeBptAmount) // // However, since this Pool never mints or burns BPT outside of the initial supply (except in the event of an // emergency pause), we can simply use `_MAX_TOKEN_BALANCE` instead of `totalSupply()` and save // gas. virtualSupply = _MAX_TOKEN_BALANCE - amounts[_bptIndex] + _dueProtocolFeeBptAmount; amountsWithoutBpt = new uint256[](amounts.length - 1); for (uint256 i = 0; i < amountsWithoutBpt.length; i++) { amountsWithoutBpt[i] = amounts[i < _bptIndex ? i : i + 1]; } } function _addBptItem(uint256[] memory amounts, uint256 bptAmount) internal view returns (uint256[] memory amountsWithBpt) { amountsWithBpt = new uint256[](amounts.length + 1); for (uint256 i = 0; i < amountsWithBpt.length; i++) { amountsWithBpt[i] = i == _bptIndex ? bptAmount : amounts[i < _bptIndex ? i : i - 1]; } } /** * @dev Returns the number of tokens in circulation. * * In other pools, this would be the same as `totalSupply`, but since this pool pre-mints all BPT, `totalSupply` * remains constant, whereas `getVirtualSupply` increases as users join the pool and decreases as they exit it. */ function getVirtualSupply() external view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); // Note that unlike all other balances, the Vault's BPT balance does not need scaling as its scaling factor is // one. return _getVirtualSupply(balances[_bptIndex]); } function _getVirtualSupply(uint256 bptBalance) internal view returns (uint256) { return totalSupply().sub(bptBalance).add(_dueProtocolFeeBptAmount); } /** * @dev This function returns the appreciation of one BPT relative to the * underlying tokens. This starts at 1 when the pool is created and grows over time. * Because of preminted BPT, it uses `getVirtualSupply` instead of `totalSupply`. */ function getRate() public view override returns (uint256) { (, uint256[] memory balancesIncludingBpt, ) = getVault().getPoolTokens(getPoolId()); _upscaleArray(balancesIncludingBpt, _scalingFactors()); (uint256 virtualSupply, uint256[] memory balances) = _dropBptItem(balancesIncludingBpt); (uint256 currentAmp, ) = _getAmplificationParameter(); return StableMath._getRate(balances, currentAmp, virtualSupply); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol"; import "@balancer-labs/v2-pool-utils/contracts/BaseGeneralPool.sol"; import "@balancer-labs/v2-pool-utils/contracts/BaseMinimalSwapInfoPool.sol"; import "@balancer-labs/v2-pool-utils/contracts/interfaces/IRateProvider.sol"; import "./StableMath.sol"; import "./StablePoolUserData.sol"; contract StablePool is BaseGeneralPool, BaseMinimalSwapInfoPool, IRateProvider { using WordCodec for bytes32; using FixedPoint for uint256; using StablePoolUserData for bytes; // This contract uses timestamps to slowly update its Amplification parameter over time. These changes must occur // over a minimum time period much larger than the blocktime, making timestamp manipulation a non-issue. // solhint-disable not-rely-on-time // Amplification factor changes must happen over a minimum period of one day, and can at most divide or multiply the // current value by 2 every day. // WARNING: this only limits *a single* amplification change to have a maximum rate of change of twice the original // value daily. It is possible to perform multiple amplification changes in sequence to increase this value more // rapidly: for example, by doubling the value every day it can increase by a factor of 8 over three days (2^3). uint256 private constant _MIN_UPDATE_TIME = 1 days; uint256 private constant _MAX_AMP_UPDATE_DAILY_RATE = 2; bytes32 private _packedAmplificationData; event AmpUpdateStarted(uint256 startValue, uint256 endValue, uint256 startTime, uint256 endTime); event AmpUpdateStopped(uint256 currentValue); uint256 private immutable _totalTokens; IERC20 internal immutable _token0; IERC20 internal immutable _token1; IERC20 internal immutable _token2; IERC20 internal immutable _token3; IERC20 internal immutable _token4; // All token balances are normalized to behave as if the token had 18 decimals. We assume a token's decimals will // not change throughout its lifetime, and store the corresponding scaling factor for each at construction time. // These factors are always greater than or equal to one: tokens with more than 18 decimals are not supported. uint256 internal immutable _scalingFactor0; uint256 internal immutable _scalingFactor1; uint256 internal immutable _scalingFactor2; uint256 internal immutable _scalingFactor3; uint256 internal immutable _scalingFactor4; // To track how many tokens are owed to the Vault as protocol fees, we measure and store the value of the invariant // after every join and exit. All invariant growth that happens between join and exit events is due to swap fees. uint256 internal _lastInvariant; // Because the invariant depends on the amplification parameter, and this value may change over time, we should only // compare invariants that were computed using the same value. We therefore store it whenever we store // _lastInvariant. uint256 internal _lastInvariantAmp; constructor( IVault vault, string memory name, string memory symbol, IERC20[] memory tokens, uint256 amplificationParameter, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) BasePool( vault, // Because we're inheriting from both BaseGeneralPool and BaseMinimalSwapInfoPool we can choose any // specialization setting. Since this Pool never registers or deregisters any tokens after construction, // picking Two Token when the Pool only has two tokens is free gas savings. tokens.length == 2 ? IVault.PoolSpecialization.TWO_TOKEN : IVault.PoolSpecialization.GENERAL, name, symbol, tokens, new address[](tokens.length), swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { _require(amplificationParameter >= StableMath._MIN_AMP, Errors.MIN_AMP); _require(amplificationParameter <= StableMath._MAX_AMP, Errors.MAX_AMP); uint256 totalTokens = tokens.length; _totalTokens = totalTokens; // Immutable variables cannot be initialized inside an if statement, so we must do conditional assignments _token0 = tokens[0]; _token1 = tokens[1]; _token2 = totalTokens > 2 ? tokens[2] : IERC20(0); _token3 = totalTokens > 3 ? tokens[3] : IERC20(0); _token4 = totalTokens > 4 ? tokens[4] : IERC20(0); _scalingFactor0 = _computeScalingFactor(tokens[0]); _scalingFactor1 = _computeScalingFactor(tokens[1]); _scalingFactor2 = totalTokens > 2 ? _computeScalingFactor(tokens[2]) : 0; _scalingFactor3 = totalTokens > 3 ? _computeScalingFactor(tokens[3]) : 0; _scalingFactor4 = totalTokens > 4 ? _computeScalingFactor(tokens[4]) : 0; uint256 initialAmp = Math.mul(amplificationParameter, StableMath._AMP_PRECISION); _setAmplificationData(initialAmp); } function getLastInvariant() external view returns (uint256 lastInvariant, uint256 lastInvariantAmp) { lastInvariant = _lastInvariant; lastInvariantAmp = _lastInvariantAmp; } // Base Pool handlers // Swap - General Pool specialization (from BaseGeneralPool) function _onSwapGivenIn( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) internal virtual override whenNotPaused returns (uint256) { (uint256 currentAmp, ) = _getAmplificationParameter(); uint256 invariant = StableMath._calculateInvariant(currentAmp, balances, true); uint256 amountOut = StableMath._calcOutGivenIn( currentAmp, balances, indexIn, indexOut, swapRequest.amount, invariant ); return amountOut; } function _onSwapGivenOut( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) internal virtual override whenNotPaused returns (uint256) { (uint256 currentAmp, ) = _getAmplificationParameter(); uint256 invariant = StableMath._calculateInvariant(currentAmp, balances, true); uint256 amountIn = StableMath._calcInGivenOut( currentAmp, balances, indexIn, indexOut, swapRequest.amount, invariant ); return amountIn; } // Swap - Two Token Pool specialization (from BaseMinimalSwapInfoPool) function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) internal virtual override returns (uint256) { _require(_getTotalTokens() == 2, Errors.NOT_TWO_TOKENS); (uint256[] memory balances, uint256 indexIn, uint256 indexOut) = _getSwapBalanceArrays( swapRequest, balanceTokenIn, balanceTokenOut ); return _onSwapGivenIn(swapRequest, balances, indexIn, indexOut); } function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) internal virtual override returns (uint256) { _require(_getTotalTokens() == 2, Errors.NOT_TWO_TOKENS); (uint256[] memory balances, uint256 indexIn, uint256 indexOut) = _getSwapBalanceArrays( swapRequest, balanceTokenIn, balanceTokenOut ); return _onSwapGivenOut(swapRequest, balances, indexIn, indexOut); } function _getSwapBalanceArrays( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) private view returns ( uint256[] memory balances, uint256 indexIn, uint256 indexOut ) { balances = new uint256[](2); if (_isToken0(swapRequest.tokenIn)) { indexIn = 0; indexOut = 1; balances[0] = balanceTokenIn; balances[1] = balanceTokenOut; } else { // _token0 == swapRequest.tokenOut indexOut = 0; indexIn = 1; balances[0] = balanceTokenOut; balances[1] = balanceTokenIn; } } // Initialize function _onInitializePool( bytes32, address, address, uint256[] memory scalingFactors, bytes memory userData ) internal virtual override whenNotPaused returns (uint256, uint256[] memory) { // It would be strange for the Pool to be paused before it is initialized, but for consistency we prevent // initialization in this case. StablePoolUserData.JoinKind kind = userData.joinKind(); _require(kind == StablePoolUserData.JoinKind.INIT, Errors.UNINITIALIZED); uint256[] memory amountsIn = userData.initialAmountsIn(); InputHelpers.ensureInputLengthMatch(amountsIn.length, _getTotalTokens()); _upscaleArray(amountsIn, scalingFactors); (uint256 currentAmp, ) = _getAmplificationParameter(); uint256 invariantAfterJoin = StableMath._calculateInvariant(currentAmp, amountsIn, true); // Set the initial BPT to the value of the invariant. uint256 bptAmountOut = invariantAfterJoin; _updateLastInvariant(invariantAfterJoin, currentAmp); return (bptAmountOut, amountsIn); } // Join function _onJoinPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, uint256[] memory scalingFactors, bytes memory userData ) internal virtual override whenNotPaused returns ( uint256, uint256[] memory, uint256[] memory ) { // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous join // or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids spending gas to // calculate the fee amounts during each individual swap. uint256[] memory dueProtocolFeeAmounts = _getDueProtocolFeeAmounts(balances, protocolSwapFeePercentage); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); (uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin(balances, scalingFactors, userData); // Update the invariant with the balances the Pool will have after the join, in order to compute the // protocol swap fee amounts due in future joins and exits. _updateInvariantAfterJoin(balances, amountsIn); return (bptAmountOut, amountsIn, dueProtocolFeeAmounts); } function _doJoin( uint256[] memory balances, uint256[] memory scalingFactors, bytes memory userData ) private view returns (uint256, uint256[] memory) { StablePoolUserData.JoinKind kind = userData.joinKind(); if (kind == StablePoolUserData.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) { return _joinExactTokensInForBPTOut(balances, scalingFactors, userData); } else if (kind == StablePoolUserData.JoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT) { return _joinTokenInForExactBPTOut(balances, userData); } else { _revert(Errors.UNHANDLED_JOIN_KIND); } } function _joinExactTokensInForBPTOut( uint256[] memory balances, uint256[] memory scalingFactors, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256[] memory amountsIn, uint256 minBPTAmountOut) = userData.exactTokensInForBptOut(); InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length); _upscaleArray(amountsIn, scalingFactors); (uint256 currentAmp, ) = _getAmplificationParameter(); uint256 bptAmountOut = StableMath._calcBptOutGivenExactTokensIn( currentAmp, balances, amountsIn, totalSupply(), getSwapFeePercentage() ); _require(bptAmountOut >= minBPTAmountOut, Errors.BPT_OUT_MIN_AMOUNT); return (bptAmountOut, amountsIn); } function _joinTokenInForExactBPTOut(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { (uint256 bptAmountOut, uint256 tokenIndex) = userData.tokenInForExactBptOut(); // Note that there is no maximum amountIn parameter: this is handled by `IVault.joinPool`. _require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS); uint256[] memory amountsIn = new uint256[](_getTotalTokens()); (uint256 currentAmp, ) = _getAmplificationParameter(); amountsIn[tokenIndex] = StableMath._calcTokenInGivenExactBptOut( currentAmp, balances, tokenIndex, bptAmountOut, totalSupply(), getSwapFeePercentage() ); return (bptAmountOut, amountsIn); } // Exit function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, uint256[] memory scalingFactors, bytes memory userData ) internal virtual override returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { // Exits are not completely disabled while the contract is paused: proportional exits (exact BPT in for tokens // out) remain functional. if (_isNotPaused()) { // Due protocol swap fee amounts are computed by measuring the growth of the invariant between the previous // join or exit event and now - the invariant's growth is due exclusively to swap fees. This avoids // spending gas calculating fee amounts during each individual swap dueProtocolFeeAmounts = _getDueProtocolFeeAmounts(balances, protocolSwapFeePercentage); // Update current balances by subtracting the protocol fee amounts _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); } else { // If the contract is paused, swap protocol fee amounts are not charged to avoid extra calculations and // reduce the potential for errors. dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } (bptAmountIn, amountsOut) = _doExit(balances, scalingFactors, userData); // Update the invariant with the balances the Pool will have after the exit, in order to compute the // protocol swap fee amounts due in future joins and exits. _updateInvariantAfterExit(balances, amountsOut); return (bptAmountIn, amountsOut, dueProtocolFeeAmounts); } function _doExit( uint256[] memory balances, uint256[] memory scalingFactors, bytes memory userData ) private view returns (uint256, uint256[] memory) { StablePoolUserData.ExitKind kind = userData.exitKind(); if (kind == StablePoolUserData.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) { return _exitExactBPTInForTokenOut(balances, userData); } else if (kind == StablePoolUserData.ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT) { return _exitExactBPTInForTokensOut(balances, userData); } else if (kind == StablePoolUserData.ExitKind.BPT_IN_FOR_EXACT_TOKENS_OUT) { return _exitBPTInForExactTokensOut(balances, scalingFactors, userData); } else { _revert(Errors.UNHANDLED_EXIT_KIND); } } function _exitExactBPTInForTokenOut(uint256[] memory balances, bytes memory userData) private view whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256 bptAmountIn, uint256 tokenIndex) = userData.exactBptInForTokenOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. _require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS); // We exit in a single token, so initialize amountsOut with zeros uint256[] memory amountsOut = new uint256[](_getTotalTokens()); // And then assign the result to the selected token (uint256 currentAmp, ) = _getAmplificationParameter(); amountsOut[tokenIndex] = StableMath._calcTokenOutGivenExactBptIn( currentAmp, balances, tokenIndex, bptAmountIn, totalSupply(), getSwapFeePercentage() ); return (bptAmountIn, amountsOut); } function _exitExactBPTInForTokensOut(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { // This exit function is the only one that is not disabled if the contract is paused: it remains unrestricted // in an attempt to provide users with a mechanism to retrieve their tokens in case of an emergency. // This particular exit function is the only one that remains available because it is the simplest one, and // therefore the one with the lowest likelihood of errors. uint256 bptAmountIn = userData.exactBptInForTokensOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. uint256[] memory amountsOut = StableMath._calcTokensOutGivenExactBptIn(balances, bptAmountIn, totalSupply()); return (bptAmountIn, amountsOut); } function _exitBPTInForExactTokensOut( uint256[] memory balances, uint256[] memory scalingFactors, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { // This exit function is disabled if the contract is paused. (uint256[] memory amountsOut, uint256 maxBPTAmountIn) = userData.bptInForExactTokensOut(); InputHelpers.ensureInputLengthMatch(amountsOut.length, _getTotalTokens()); _upscaleArray(amountsOut, scalingFactors); (uint256 currentAmp, ) = _getAmplificationParameter(); uint256 bptAmountIn = StableMath._calcBptInGivenExactTokensOut( currentAmp, balances, amountsOut, totalSupply(), getSwapFeePercentage() ); _require(bptAmountIn <= maxBPTAmountIn, Errors.BPT_IN_MAX_AMOUNT); return (bptAmountIn, amountsOut); } // Helpers /** * @dev Stores the last measured invariant, and the amplification parameter used to compute it. */ function _updateLastInvariant(uint256 invariant, uint256 amplificationParameter) internal { _lastInvariant = invariant; _lastInvariantAmp = amplificationParameter; } /** * @dev Returns the amount of protocol fees to pay, given the value of the last stored invariant and the current * balances. */ function _getDueProtocolFeeAmounts(uint256[] memory balances, uint256 protocolSwapFeePercentage) private view returns (uint256[] memory) { // Initialize with zeros uint256[] memory dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); // Early return if the protocol swap fee percentage is zero, saving gas. if (protocolSwapFeePercentage == 0) { return dueProtocolFeeAmounts; } // Instead of paying the protocol swap fee in all tokens proportionally, we will pay it in a single one. This // will reduce gas costs for single asset joins and exits, as at most only two Pool balances will change (the // token joined/exited, and the token in which fees will be paid). // The protocol fee is charged using the token with the highest balance in the pool. uint256 chosenTokenIndex = 0; uint256 maxBalance = balances[0]; for (uint256 i = 1; i < _getTotalTokens(); ++i) { uint256 currentBalance = balances[i]; if (currentBalance > maxBalance) { chosenTokenIndex = i; maxBalance = currentBalance; } } // Set the fee amount to pay in the selected token dueProtocolFeeAmounts[chosenTokenIndex] = StableMath._calcDueTokenProtocolSwapFeeAmount( _lastInvariantAmp, balances, _lastInvariant, chosenTokenIndex, protocolSwapFeePercentage ); return dueProtocolFeeAmounts; } /** * @dev Computes and stores the value of the invariant after a join, which is required to compute due protocol fees * in the future. */ function _updateInvariantAfterJoin(uint256[] memory balances, uint256[] memory amountsIn) private { _mutateAmounts(balances, amountsIn, FixedPoint.add); (uint256 currentAmp, ) = _getAmplificationParameter(); // This invariant is used only to compute the final balance when calculating the protocol fees. These are // rounded down, so we round the invariant up. _updateLastInvariant(StableMath._calculateInvariant(currentAmp, balances, true), currentAmp); } /** * @dev Computes and stores the value of the invariant after an exit, which is required to compute due protocol fees * in the future. */ function _updateInvariantAfterExit(uint256[] memory balances, uint256[] memory amountsOut) private { _mutateAmounts(balances, amountsOut, FixedPoint.sub); (uint256 currentAmp, ) = _getAmplificationParameter(); // This invariant is used only to compute the final balance when calculating the protocol fees. These are // rounded down, so we round the invariant up. _updateLastInvariant(StableMath._calculateInvariant(currentAmp, balances, true), currentAmp); } /** * @dev Mutates `amounts` by applying `mutation` with each entry in `arguments`. * * Equivalent to `amounts = amounts.map(mutation)`. */ function _mutateAmounts( uint256[] memory toMutate, uint256[] memory arguments, function(uint256, uint256) pure returns (uint256) mutation ) private view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { toMutate[i] = mutation(toMutate[i], arguments[i]); } } /** * @dev This function returns the appreciation of one BPT relative to the * underlying tokens. This starts at 1 when the pool is created and grows over time */ function getRate() public view virtual override returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); _upscaleArray(balances, _scalingFactors()); (uint256 currentAmp, ) = _getAmplificationParameter(); return StableMath._getRate(balances, currentAmp, totalSupply()); } // Amplification /** * @dev Begins changing the amplification parameter to `rawEndValue` over time. The value will change linearly until * `endTime` is reached, when it will be `rawEndValue`. * * NOTE: Internally, the amplification parameter is represented using higher precision. The values returned by * `getAmplificationParameter` have to be corrected to account for this when comparing to `rawEndValue`. */ function startAmplificationParameterUpdate(uint256 rawEndValue, uint256 endTime) external authenticate { _require(rawEndValue >= StableMath._MIN_AMP, Errors.MIN_AMP); _require(rawEndValue <= StableMath._MAX_AMP, Errors.MAX_AMP); uint256 duration = Math.sub(endTime, block.timestamp); _require(duration >= _MIN_UPDATE_TIME, Errors.AMP_END_TIME_TOO_CLOSE); (uint256 currentValue, bool isUpdating) = _getAmplificationParameter(); _require(!isUpdating, Errors.AMP_ONGOING_UPDATE); uint256 endValue = Math.mul(rawEndValue, StableMath._AMP_PRECISION); // daily rate = (endValue / currentValue) / duration * 1 day // We perform all multiplications first to not reduce precision, and round the division up as we want to avoid // large rates. Note that these are regular integer multiplications and divisions, not fixed point. uint256 dailyRate = endValue > currentValue ? Math.divUp(Math.mul(1 days, endValue), Math.mul(currentValue, duration)) : Math.divUp(Math.mul(1 days, currentValue), Math.mul(endValue, duration)); _require(dailyRate <= _MAX_AMP_UPDATE_DAILY_RATE, Errors.AMP_RATE_TOO_HIGH); _setAmplificationData(currentValue, endValue, block.timestamp, endTime); } /** * @dev Stops the amplification parameter change process, keeping the current value. */ function stopAmplificationParameterUpdate() external authenticate { (uint256 currentValue, bool isUpdating) = _getAmplificationParameter(); _require(isUpdating, Errors.AMP_NO_ONGOING_UPDATE); _setAmplificationData(currentValue); } function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) { return (actionId == getActionId(StablePool.startAmplificationParameterUpdate.selector)) || (actionId == getActionId(StablePool.stopAmplificationParameterUpdate.selector)) || super._isOwnerOnlyAction(actionId); } function getAmplificationParameter() external view returns ( uint256 value, bool isUpdating, uint256 precision ) { (value, isUpdating) = _getAmplificationParameter(); precision = StableMath._AMP_PRECISION; } function _getAmplificationParameter() internal view returns (uint256 value, bool isUpdating) { (uint256 startValue, uint256 endValue, uint256 startTime, uint256 endTime) = _getAmplificationData(); // Note that block.timestamp >= startTime, since startTime is set to the current time when an update starts if (block.timestamp < endTime) { isUpdating = true; // We can skip checked arithmetic as: // - block.timestamp is always larger or equal to startTime // - endTime is always larger than startTime // - the value delta is bounded by the largest amplification parameter, which never causes the // multiplication to overflow. // This also means that the following computation will never revert nor yield invalid results. if (endValue > startValue) { value = startValue + ((endValue - startValue) * (block.timestamp - startTime)) / (endTime - startTime); } else { value = startValue - ((startValue - endValue) * (block.timestamp - startTime)) / (endTime - startTime); } } else { isUpdating = false; value = endValue; } } function _getMaxTokens() internal pure override returns (uint256) { return StableMath._MAX_STABLE_TOKENS; } function _getTotalTokens() internal view virtual override returns (uint256) { return _totalTokens; } function _scalingFactor(IERC20 token) internal view virtual override returns (uint256) { // prettier-ignore if (_isToken0(token)) { return _getScalingFactor0(); } else if (_isToken1(token)) { return _getScalingFactor1(); } else if (token == _token2) { return _getScalingFactor2(); } else if (token == _token3) { return _getScalingFactor3(); } else if (token == _token4) { return _getScalingFactor4(); } else { _revert(Errors.INVALID_TOKEN); } } function _scalingFactors() internal view virtual override returns (uint256[] memory) { uint256 totalTokens = _getTotalTokens(); uint256[] memory scalingFactors = new uint256[](totalTokens); // prettier-ignore { scalingFactors[0] = _getScalingFactor0(); scalingFactors[1] = _getScalingFactor1(); if (totalTokens > 2) { scalingFactors[2] = _getScalingFactor2(); } else { return scalingFactors; } if (totalTokens > 3) { scalingFactors[3] = _getScalingFactor3(); } else { return scalingFactors; } if (totalTokens > 4) { scalingFactors[4] = _getScalingFactor4(); } else { return scalingFactors; } } return scalingFactors; } function _setAmplificationData(uint256 value) private { _storeAmplificationData(value, value, block.timestamp, block.timestamp); emit AmpUpdateStopped(value); } function _setAmplificationData( uint256 startValue, uint256 endValue, uint256 startTime, uint256 endTime ) private { _storeAmplificationData(startValue, endValue, startTime, endTime); emit AmpUpdateStarted(startValue, endValue, startTime, endTime); } function _storeAmplificationData( uint256 startValue, uint256 endValue, uint256 startTime, uint256 endTime ) private { _packedAmplificationData = WordCodec.encodeUint(uint64(startValue), 0) | WordCodec.encodeUint(uint64(endValue), 64) | WordCodec.encodeUint(uint64(startTime), 64 * 2) | WordCodec.encodeUint(uint64(endTime), 64 * 3); } function _getAmplificationData() private view returns ( uint256 startValue, uint256 endValue, uint256 startTime, uint256 endTime ) { startValue = _packedAmplificationData.decodeUint64(0); endValue = _packedAmplificationData.decodeUint64(64); startTime = _packedAmplificationData.decodeUint64(64 * 2); endTime = _packedAmplificationData.decodeUint64(64 * 3); } function _isToken0(IERC20 token) internal view returns (bool) { return token == _token0; } function _isToken1(IERC20 token) internal view returns (bool) { return token == _token1; } function _getScalingFactor0() internal view returns (uint256) { return _scalingFactor0; } function _getScalingFactor1() internal view returns (uint256) { return _scalingFactor1; } function _getScalingFactor2() internal view returns (uint256) { return _scalingFactor2; } function _getScalingFactor3() internal view returns (uint256) { return _scalingFactor3; } function _getScalingFactor4() internal view returns (uint256) { return _scalingFactor4; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/BalancerErrors.sol"; /** * Price rate caches are used to avoid querying the price rate for a token every time we need to work with it. It is * useful for slow changing rates, such as those that arise from interest-bearing tokens (e.g. waDAI into DAI). * * The cache data is packed into a single bytes32 value with the following structure: * [ expires | duration | price rate value ] * [ uint64 | uint64 | uint128 ] * [ MSB LSB ] * * * 'rate' is an 18 decimal fixed point number, supporting rates of up to ~3e20. 'expires' is a Unix timestamp, and * 'duration' is expressed in seconds. */ library PriceRateCache { using WordCodec for bytes32; uint256 private constant _PRICE_RATE_CACHE_VALUE_OFFSET = 0; uint256 private constant _PRICE_RATE_CACHE_DURATION_OFFSET = 128; uint256 private constant _PRICE_RATE_CACHE_EXPIRES_OFFSET = 128 + 64; /** * @dev Returns the rate of a price rate cache. */ function getRate(bytes32 cache) internal pure returns (uint256) { return cache.decodeUint128(_PRICE_RATE_CACHE_VALUE_OFFSET); } /** * @dev Returns the duration of a price rate cache. */ function getDuration(bytes32 cache) internal pure returns (uint256) { return cache.decodeUint64(_PRICE_RATE_CACHE_DURATION_OFFSET); } /** * @dev Returns the duration and expiration time of a price rate cache. */ function getTimestamps(bytes32 cache) internal pure returns (uint256 duration, uint256 expires) { duration = getDuration(cache); expires = cache.decodeUint64(_PRICE_RATE_CACHE_EXPIRES_OFFSET); } /** * @dev Encodes rate and duration into a price rate cache. The expiration time is computed automatically, counting * from the current time. */ function encode(uint256 rate, uint256 duration) internal view returns (bytes32) { _require(rate < 2**128, Errors.PRICE_RATE_OVERFLOW); // solhint-disable not-rely-on-time return WordCodec.encodeUint(uint128(rate), _PRICE_RATE_CACHE_VALUE_OFFSET) | WordCodec.encodeUint(uint64(duration), _PRICE_RATE_CACHE_DURATION_OFFSET) | WordCodec.encodeUint(uint64(block.timestamp + duration), _PRICE_RATE_CACHE_EXPIRES_OFFSET); } /** * @dev Returns rate, duration and expiration time of a price rate cache. */ function decode(bytes32 cache) internal pure returns ( uint256 rate, uint256 duration, uint256 expires ) { rate = getRate(cache); (duration, expires) = getTimestamps(cache); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IRateProvider { /** * @dev Returns an 18 decimal fixed point number that is the exchange rate of the token to some other underlying * token. The meaning of this rate depends on the context. */ function getRate() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow checks. * Adapted from OpenZeppelin's SafeMath library. */ library Math { /** * @dev Returns the absolute value of a signed integer. */ function abs(int256 a) internal pure returns (uint256) { return a > 0 ? uint256(a) : uint256(-a); } /** * @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the addition of two signed integers, reverting 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), Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting 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), Errors.SUB_OVERFLOW); return c; } /** * @dev Returns the largest of two numbers of 256 bits. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers of 256 bits. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; _require(a == 0 || c / a == b, Errors.MUL_OVERFLOW); return c; } function div( uint256 a, uint256 b, bool roundUp ) internal pure returns (uint256) { return roundUp ? divUp(a, b) : divDown(a, b); } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); return a / b; } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { return 1 + (a - 1) / b; } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./LogExpMath.sol"; import "../helpers/BalancerErrors.sol"; /* solhint-disable private-vars-leading-underscore */ library FixedPoint { uint256 internal constant ONE = 1e18; // 18 decimal places uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14) // Minimum base for the power function when the exponent is 'free' (larger than ONE). uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18; function add(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } function mulDown(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); return product / ONE; } function mulUp(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); if (product == 0) { return 0; } else { // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((product - 1) / ONE) + 1; } } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow return aInflated / b; } } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((aInflated - 1) / b) + 1; } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above * the true value (that is, the error function expected - actual is always positive). */ function powDown(uint256 x, uint256 y) internal pure returns (uint256) { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); if (raw < maxError) { return 0; } else { return sub(raw, maxError); } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below * the true value (that is, the error function expected - actual is always negative). */ function powUp(uint256 x, uint256 y) internal pure returns (uint256) { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); return add(raw, maxError); } /** * @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1. * * Useful when computing the complement for values with some level of relative error, as it strips this error and * prevents intermediate negative values. */ function complement(uint256 x) internal pure returns (uint256) { return (x < ONE) ? (ONE - x) : 0; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-vault/contracts/interfaces/IAsset.sol"; import "../openzeppelin/IERC20.sol"; // solhint-disable function _asIAsset(IERC20[] memory tokens) pure returns (IAsset[] memory assets) { // solhint-disable-next-line no-inline-assembly assembly { assets := tokens } } function _sortTokens( IERC20 tokenA, IERC20 tokenB, IERC20 tokenC ) pure returns (IERC20[] memory tokens) { (uint256 indexTokenA, uint256 indexTokenB, uint256 indexTokenC) = _getSortedTokenIndexes(tokenA, tokenB, tokenC); tokens = new IERC20[](3); tokens[indexTokenA] = tokenA; tokens[indexTokenB] = tokenB; tokens[indexTokenC] = tokenC; } function _insertSorted(IERC20[] memory tokens, IERC20 token) pure returns (IERC20[] memory sorted) { sorted = new IERC20[](tokens.length + 1); if (tokens.length == 0) { sorted[0] = token; return sorted; } uint256 i; for (i = tokens.length; i > 0 && tokens[i - 1] > token; i--) sorted[i] = tokens[i - 1]; for (uint256 j = 0; j < i; j++) sorted[j] = tokens[j]; sorted[i] = token; } function _getSortedTokenIndexes( IERC20 tokenA, IERC20 tokenB, IERC20 tokenC ) pure returns ( uint256 indexTokenA, uint256 indexTokenB, uint256 indexTokenC ) { if (tokenA < tokenB) { if (tokenB < tokenC) { // (tokenA, tokenB, tokenC) return (0, 1, 2); } else if (tokenA < tokenC) { // (tokenA, tokenC, tokenB) return (0, 2, 1); } else { // (tokenC, tokenA, tokenB) return (1, 2, 0); } } else { // tokenB < tokenA if (tokenC < tokenB) { // (tokenC, tokenB, tokenA) return (2, 1, 0); } else if (tokenC < tokenA) { // (tokenB, tokenC, tokenA) return (2, 0, 1); } else { // (tokenB, tokenA, tokenC) return (1, 0, 2); } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // solhint-disable /** * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAL#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAL#" part is a known constant // (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Math uint256 internal constant ADD_OVERFLOW = 0; uint256 internal constant SUB_OVERFLOW = 1; uint256 internal constant SUB_UNDERFLOW = 2; uint256 internal constant MUL_OVERFLOW = 3; uint256 internal constant ZERO_DIVISION = 4; uint256 internal constant DIV_INTERNAL = 5; uint256 internal constant X_OUT_OF_BOUNDS = 6; uint256 internal constant Y_OUT_OF_BOUNDS = 7; uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8; uint256 internal constant INVALID_EXPONENT = 9; // Input uint256 internal constant OUT_OF_BOUNDS = 100; uint256 internal constant UNSORTED_ARRAY = 101; uint256 internal constant UNSORTED_TOKENS = 102; uint256 internal constant INPUT_LENGTH_MISMATCH = 103; uint256 internal constant ZERO_TOKEN = 104; // Shared pools uint256 internal constant MIN_TOKENS = 200; uint256 internal constant MAX_TOKENS = 201; uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202; uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203; uint256 internal constant MINIMUM_BPT = 204; uint256 internal constant CALLER_NOT_VAULT = 205; uint256 internal constant UNINITIALIZED = 206; uint256 internal constant BPT_IN_MAX_AMOUNT = 207; uint256 internal constant BPT_OUT_MIN_AMOUNT = 208; uint256 internal constant EXPIRED_PERMIT = 209; uint256 internal constant NOT_TWO_TOKENS = 210; // Pools uint256 internal constant MIN_AMP = 300; uint256 internal constant MAX_AMP = 301; uint256 internal constant MIN_WEIGHT = 302; uint256 internal constant MAX_STABLE_TOKENS = 303; uint256 internal constant MAX_IN_RATIO = 304; uint256 internal constant MAX_OUT_RATIO = 305; uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306; uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307; uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308; uint256 internal constant INVALID_TOKEN = 309; uint256 internal constant UNHANDLED_JOIN_KIND = 310; uint256 internal constant ZERO_INVARIANT = 311; uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312; uint256 internal constant ORACLE_NOT_INITIALIZED = 313; uint256 internal constant ORACLE_QUERY_TOO_OLD = 314; uint256 internal constant ORACLE_INVALID_INDEX = 315; uint256 internal constant ORACLE_BAD_SECS = 316; uint256 internal constant AMP_END_TIME_TOO_CLOSE = 317; uint256 internal constant AMP_ONGOING_UPDATE = 318; uint256 internal constant AMP_RATE_TOO_HIGH = 319; uint256 internal constant AMP_NO_ONGOING_UPDATE = 320; uint256 internal constant STABLE_INVARIANT_DIDNT_CONVERGE = 321; uint256 internal constant STABLE_GET_BALANCE_DIDNT_CONVERGE = 322; uint256 internal constant RELAYER_NOT_CONTRACT = 323; uint256 internal constant BASE_POOL_RELAYER_NOT_CALLED = 324; uint256 internal constant REBALANCING_RELAYER_REENTERED = 325; uint256 internal constant GRADUAL_UPDATE_TIME_TRAVEL = 326; uint256 internal constant SWAPS_DISABLED = 327; uint256 internal constant CALLER_IS_NOT_LBP_OWNER = 328; uint256 internal constant PRICE_RATE_OVERFLOW = 329; uint256 internal constant INVALID_JOIN_EXIT_KIND_WHILE_SWAPS_DISABLED = 330; uint256 internal constant WEIGHT_CHANGE_TOO_FAST = 331; uint256 internal constant LOWER_GREATER_THAN_UPPER_TARGET = 332; uint256 internal constant UPPER_TARGET_TOO_HIGH = 333; uint256 internal constant UNHANDLED_BY_LINEAR_POOL = 334; uint256 internal constant OUT_OF_TARGET_RANGE = 335; uint256 internal constant UNHANDLED_EXIT_KIND = 336; uint256 internal constant UNAUTHORIZED_EXIT = 337; uint256 internal constant MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE = 338; uint256 internal constant UNHANDLED_BY_MANAGED_POOL = 339; uint256 internal constant UNHANDLED_BY_PHANTOM_POOL = 340; uint256 internal constant TOKEN_DOES_NOT_HAVE_RATE_PROVIDER = 341; uint256 internal constant INVALID_INITIALIZATION = 342; uint256 internal constant OUT_OF_NEW_TARGET_RANGE = 343; uint256 internal constant UNAUTHORIZED_OPERATION = 344; uint256 internal constant UNINITIALIZED_POOL_CONTROLLER = 345; // Lib uint256 internal constant REENTRANCY = 400; uint256 internal constant SENDER_NOT_ALLOWED = 401; uint256 internal constant PAUSED = 402; uint256 internal constant PAUSE_WINDOW_EXPIRED = 403; uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404; uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405; uint256 internal constant INSUFFICIENT_BALANCE = 406; uint256 internal constant INSUFFICIENT_ALLOWANCE = 407; uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408; uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409; uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410; uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411; uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412; uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413; uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414; uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415; uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416; uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417; uint256 internal constant SAFE_ERC20_CALL_FAILED = 418; uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419; uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420; uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421; uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422; uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423; uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424; uint256 internal constant BUFFER_PERIOD_EXPIRED = 425; uint256 internal constant CALLER_IS_NOT_OWNER = 426; uint256 internal constant NEW_OWNER_IS_ZERO = 427; uint256 internal constant CODE_DEPLOYMENT_FAILED = 428; uint256 internal constant CALL_TO_NON_CONTRACT = 429; uint256 internal constant LOW_LEVEL_CALL_FAILED = 430; uint256 internal constant NOT_PAUSED = 431; uint256 internal constant ADDRESS_ALREADY_ALLOWLISTED = 432; uint256 internal constant ADDRESS_NOT_ALLOWLISTED = 433; // Vault uint256 internal constant INVALID_POOL_ID = 500; uint256 internal constant CALLER_NOT_POOL = 501; uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502; uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503; uint256 internal constant INVALID_SIGNATURE = 504; uint256 internal constant EXIT_BELOW_MIN = 505; uint256 internal constant JOIN_ABOVE_MAX = 506; uint256 internal constant SWAP_LIMIT = 507; uint256 internal constant SWAP_DEADLINE = 508; uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509; uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510; uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511; uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512; uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513; uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514; uint256 internal constant INVALID_POST_LOAN_BALANCE = 515; uint256 internal constant INSUFFICIENT_ETH = 516; uint256 internal constant UNALLOCATED_ETH = 517; uint256 internal constant ETH_TRANSFER = 518; uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519; uint256 internal constant TOKENS_MISMATCH = 520; uint256 internal constant TOKEN_NOT_REGISTERED = 521; uint256 internal constant TOKEN_ALREADY_REGISTERED = 522; uint256 internal constant TOKENS_ALREADY_SET = 523; uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524; uint256 internal constant NONZERO_TOKEN_BALANCE = 525; uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526; uint256 internal constant POOL_NO_TOKENS = 527; uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528; // Fees uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600; uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601; uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./StablePhantomPool.sol"; library StablePhantomPoolUserDataHelpers { function joinKind(bytes memory self) internal pure returns (StablePhantomPool.JoinKindPhantom) { return abi.decode(self, (StablePhantomPool.JoinKindPhantom)); } function exitKind(bytes memory self) internal pure returns (StablePhantomPool.ExitKindPhantom) { return abi.decode(self, (StablePhantomPool.ExitKindPhantom)); } // Joins function initialAmountsIn(bytes memory self) internal pure returns (uint256[] memory amountsIn) { (, amountsIn) = abi.decode(self, (StablePhantomPool.JoinKindPhantom, uint256[])); } // Exits function exactBptInForTokensOut(bytes memory self) internal pure returns (uint256 bptAmountIn) { (, bptAmountIn) = abi.decode(self, (StablePhantomPool.ExitKindPhantom, uint256)); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../openzeppelin/IERC20.sol"; import "./BalancerErrors.sol"; library InputHelpers { function ensureInputLengthMatch(uint256 a, uint256 b) internal pure { _require(a == b, Errors.INPUT_LENGTH_MISMATCH); } function ensureInputLengthMatch( uint256 a, uint256 b, uint256 c ) internal pure { _require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH); } function ensureArrayIsSorted(IERC20[] memory array) internal pure { address[] memory addressArray; // solhint-disable-next-line no-inline-assembly assembly { addressArray := array } ensureArrayIsSorted(addressArray); } function ensureArrayIsSorted(address[] memory array) internal pure { if (array.length < 2) { return; } address previous = array[0]; for (uint256 i = 1; i < array.length; ++i) { address current = array[i]; _require(previous < current, Errors.UNSORTED_ARRAY); previous = current; } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Library for encoding and decoding values stored inside a 256 bit word. Typically used to pack multiple values in * a single storage slot, saving gas by performing less storage accesses. * * Each value is defined by its size and the least significant bit in the word, also known as offset. For example, two * 128 bit values may be encoded in a word by assigning one an offset of 0, and the other an offset of 128. * * We could use Solidity structs to pack values together in a single storage slot instead of relying on a custom and * error-prone library, but unfortunately Solidity only allows for structs to live in either storage, calldata or * memory. Because a memory struct uses not just memory but also a slot in the stack (to store its memory location), * using memory for word-sized values (i.e. of 256 bits or less) is strictly less gas performant, and doesn't even * prevent stack-too-deep issues. This is compounded by the fact that Balancer contracts typically are memory-intensive, * and the cost of accesing memory increases quadratically with the number of allocated words. Manual packing and * unpacking is therefore the preferred approach. */ library WordCodec { // Masks are values with the least significant N bits set. They can be used to extract an encoded value from a word, // or to insert a new one replacing the old. uint256 private constant _MASK_1 = 2**(1) - 1; uint256 private constant _MASK_5 = 2**(5) - 1; uint256 private constant _MASK_7 = 2**(7) - 1; uint256 private constant _MASK_10 = 2**(10) - 1; uint256 private constant _MASK_16 = 2**(16) - 1; uint256 private constant _MASK_22 = 2**(22) - 1; uint256 private constant _MASK_31 = 2**(31) - 1; uint256 private constant _MASK_32 = 2**(32) - 1; uint256 private constant _MASK_53 = 2**(53) - 1; uint256 private constant _MASK_64 = 2**(64) - 1; uint256 private constant _MASK_96 = 2**(96) - 1; uint256 private constant _MASK_128 = 2**(128) - 1; uint256 private constant _MASK_192 = 2**(192) - 1; // Largest positive values that can be represented as N bits signed integers. int256 private constant _MAX_INT_22 = 2**(21) - 1; int256 private constant _MAX_INT_53 = 2**(52) - 1; // In-place insertion /** * @dev Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the new * word. */ function insertBool( bytes32 word, bool value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_1 << offset)); return clearedWord | bytes32(uint256(value ? 1 : 0) << offset); } // Unsigned /** * @dev Inserts a 5 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` only uses its least significant 5 bits, otherwise it may overwrite sibling bytes. */ function insertUint5( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_5 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 7 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` only uses its least significant 7 bits, otherwise it may overwrite sibling bytes. */ function insertUint7( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_7 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 10 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` only uses its least significant 10 bits, otherwise it may overwrite sibling bytes. */ function insertUint10( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_10 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 16 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. * Returns the new word. * * Assumes `value` only uses its least significant 16 bits, otherwise it may overwrite sibling bytes. */ function insertUint16( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_16 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 31 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 31 bits. */ function insertUint31( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_31 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 32 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` only uses its least significant 32 bits, otherwise it may overwrite sibling bytes. */ function insertUint32( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_32 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 64 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` only uses its least significant 64 bits, otherwise it may overwrite sibling bytes. */ function insertUint64( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_64 << offset)); return clearedWord | bytes32(value << offset); } // Signed /** * @dev Inserts a 22 bits signed integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 22 bits. */ function insertInt22( bytes32 word, int256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_22 << offset)); // Integer values need masking to remove the upper bits of negative values. return clearedWord | bytes32((uint256(value) & _MASK_22) << offset); } // Bytes /** * @dev Inserts 192 bit shifted by an offset into a 256 bit word, replacing the old value. Returns the new word. * * Assumes `value` can be represented using 192 bits. */ function insertBits192( bytes32 word, bytes32 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_192 << offset)); return clearedWord | bytes32((uint256(value) & _MASK_192) << offset); } // Encoding // Unsigned /** * @dev Encodes an unsigned integer shifted by an offset. This performs no size checks: it is up to the caller to * ensure that the values are bounded. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeUint(uint256 value, uint256 offset) internal pure returns (bytes32) { return bytes32(value << offset); } // Signed /** * @dev Encodes a 22 bits signed integer shifted by an offset. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeInt22(int256 value, uint256 offset) internal pure returns (bytes32) { // Integer values need masking to remove the upper bits of negative values. return bytes32((uint256(value) & _MASK_22) << offset); } /** * @dev Encodes a 53 bits signed integer shifted by an offset. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeInt53(int256 value, uint256 offset) internal pure returns (bytes32) { // Integer values need masking to remove the upper bits of negative values. return bytes32((uint256(value) & _MASK_53) << offset); } // Decoding /** * @dev Decodes and returns a boolean shifted by an offset from a 256 bit word. */ function decodeBool(bytes32 word, uint256 offset) internal pure returns (bool) { return (uint256(word >> offset) & _MASK_1) == 1; } // Unsigned /** * @dev Decodes and returns a 5 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint5(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_5; } /** * @dev Decodes and returns a 7 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint7(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_7; } /** * @dev Decodes and returns a 10 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint10(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_10; } /** * @dev Decodes and returns a 16 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint16(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_16; } /** * @dev Decodes and returns a 31 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint31(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_31; } /** * @dev Decodes and returns a 32 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint32(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_32; } /** * @dev Decodes and returns a 64 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint64(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_64; } /** * @dev Decodes and returns a 96 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint96(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_96; } /** * @dev Decodes and returns a 128 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint128(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_128; } // Signed /** * @dev Decodes and returns a 22 bits signed integer shifted by an offset from a 256 bit word. */ function decodeInt22(bytes32 word, uint256 offset) internal pure returns (int256) { int256 value = int256(uint256(word >> offset) & _MASK_22); // In case the decoded value is greater than the max positive integer that can be represented with 22 bits, // we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit // representation. return value > _MAX_INT_22 ? (value | int256(~_MASK_22)) : value; } /** * @dev Decodes and returns a 53 bits signed integer shifted by an offset from a 256 bit word. */ function decodeInt53(bytes32 word, uint256 offset) internal pure returns (int256) { int256 value = int256(uint256(word >> offset) & _MASK_53); // In case the decoded value is greater than the max positive integer that can be represented with 53 bits, // we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit // representation. return value > _MAX_INT_53 ? (value | int256(~_MASK_53)) : value; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./BasePool.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IGeneralPool.sol"; /** * @dev Extension of `BasePool`, adding a handler for `IGeneralPool.onSwap`. * * Derived contracts must call `BasePool`'s constructor, and implement `_onSwapGivenIn` and `_onSwapGivenOut` along with * `BasePool`'s virtual functions. Inheriting from this contract lets derived contracts choose the General * specialization setting. */ abstract contract BaseGeneralPool is IGeneralPool, BasePool { // Swap Hooks function onSwap( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) public virtual override onlyVault(swapRequest.poolId) returns (uint256) { _validateIndexes(indexIn, indexOut, _getTotalTokens()); uint256[] memory scalingFactors = _scalingFactors(); return swapRequest.kind == IVault.SwapKind.GIVEN_IN ? _swapGivenIn(swapRequest, balances, indexIn, indexOut, scalingFactors) : _swapGivenOut(swapRequest, balances, indexIn, indexOut, scalingFactors); } function _swapGivenIn( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut, uint256[] memory scalingFactors ) internal returns (uint256) { // Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis. swapRequest.amount = _subtractSwapFeeAmount(swapRequest.amount); _upscaleArray(balances, scalingFactors); swapRequest.amount = _upscale(swapRequest.amount, scalingFactors[indexIn]); uint256 amountOut = _onSwapGivenIn(swapRequest, balances, indexIn, indexOut); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactors[indexOut]); } function _swapGivenOut( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut, uint256[] memory scalingFactors ) internal returns (uint256) { _upscaleArray(balances, scalingFactors); swapRequest.amount = _upscale(swapRequest.amount, scalingFactors[indexOut]); uint256 amountIn = _onSwapGivenOut(swapRequest, balances, indexIn, indexOut); // amountIn tokens are entering the Pool, so we round up. amountIn = _downscaleUp(amountIn, scalingFactors[indexIn]); // Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis. return _addSwapFeeAmount(amountIn); } /* * @dev Called when a swap with the Pool occurs, where the amount of tokens entering the Pool is known. * * Returns the amount of tokens that will be taken from the Pool in return. * * All amounts inside `swapRequest` and `balances` are upscaled. The swap fee has already been deducted from * `swapRequest.amount`. * * The return value is also considered upscaled, and will be downscaled (rounding down) before returning it to the * Vault. */ function _onSwapGivenIn( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) internal virtual returns (uint256); /* * @dev Called when a swap with the Pool occurs, where the amount of tokens exiting the Pool is known. * * Returns the amount of tokens that will be granted to the Pool in return. * * All amounts inside `swapRequest` and `balances` are upscaled. * * The return value is also considered upscaled, and will be downscaled (rounding up) before applying the swap fee * and returning it to the Vault. */ function _onSwapGivenOut( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) internal virtual returns (uint256); function _validateIndexes( uint256 indexIn, uint256 indexOut, uint256 limit ) private pure { _require(indexIn < limit && indexOut < limit, Errors.OUT_OF_BOUNDS); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./BasePool.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IMinimalSwapInfoPool.sol"; /** * @dev Extension of `BasePool`, adding a handler for `IMinimalSwapInfoPool.onSwap`. * * Derived contracts must call `BasePool`'s constructor, and implement `_onSwapGivenIn` and `_onSwapGivenOut` along with * `BasePool`'s virtual functions. Inheriting from this contract lets derived contracts choose the Two Token or Minimal * Swap Info specialization settings. */ abstract contract BaseMinimalSwapInfoPool is IMinimalSwapInfoPool, BasePool { // Swap Hooks function onSwap( SwapRequest memory request, uint256 balanceTokenIn, uint256 balanceTokenOut ) public virtual override onlyVault(request.poolId) returns (uint256) { uint256 scalingFactorTokenIn = _scalingFactor(request.tokenIn); uint256 scalingFactorTokenOut = _scalingFactor(request.tokenOut); if (request.kind == IVault.SwapKind.GIVEN_IN) { // Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis. uint256 amountInMinusSwapFees = _subtractSwapFeeAmount(request.amount); // Process the (upscaled!) swap fee. uint256 swapFee = request.amount - amountInMinusSwapFees; _processSwapFeeAmount(request.tokenIn, _upscale(swapFee, scalingFactorTokenIn)); request.amount = amountInMinusSwapFees; // All token amounts are upscaled. balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); request.amount = _upscale(request.amount, scalingFactorTokenIn); uint256 amountOut = _onSwapGivenIn(request, balanceTokenIn, balanceTokenOut); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactorTokenOut); } else { // All token amounts are upscaled. balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); request.amount = _upscale(request.amount, scalingFactorTokenOut); uint256 amountIn = _onSwapGivenOut(request, balanceTokenIn, balanceTokenOut); // amountIn tokens are entering the Pool, so we round up. amountIn = _downscaleUp(amountIn, scalingFactorTokenIn); // Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis. uint256 amountInPlusSwapFees = _addSwapFeeAmount(amountIn); // Process the (upscaled!) swap fee. uint256 swapFee = amountInPlusSwapFees - amountIn; _processSwapFeeAmount(request.tokenIn, _upscale(swapFee, scalingFactorTokenIn)); return amountInPlusSwapFees; } } /* * @dev Called when a swap with the Pool occurs, where the amount of tokens entering the Pool is known. * * Returns the amount of tokens that will be taken from the Pool in return. * * All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled. The swap fee has already * been deducted from `swapRequest.amount`. * * The return value is also considered upscaled, and will be downscaled (rounding down) before returning it to the * Vault. */ function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) internal virtual returns (uint256); /* * @dev Called when a swap with the Pool occurs, where the amount of tokens exiting the Pool is known. * * Returns the amount of tokens that will be granted to the Pool in return. * * All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled. * * The return value is also considered upscaled, and will be downscaled (rounding up) before applying the swap fee * and returning it to the Vault. */ function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut ) internal virtual returns (uint256); /** * @dev Called whenever a swap fee is charged. Implementations should call their parents via super, to ensure all * implementations in the inheritance tree are called. * * Callers must call one of the three `_processSwapFeeAmount` functions when swap fees are computed, * and upscale `amount`. */ function _processSwapFeeAmount( uint256, /*index*/ uint256 /*amount*/ ) internal virtual { // solhint-disable-previous-line no-empty-blocks } function _processSwapFeeAmount(IERC20 token, uint256 amount) internal { _processSwapFeeAmount(_tokenAddressToIndex(token), amount); } function _processSwapFeeAmounts(uint256[] memory amounts) internal { InputHelpers.ensureInputLengthMatch(amounts.length, _getTotalTokens()); for (uint256 i = 0; i < _getTotalTokens(); ++i) { _processSwapFeeAmount(i, amounts[i]); } } /** * @dev Returns the index of `token` in the Pool's token array (i.e. the one `vault.getPoolTokens()` would return). * * A trivial (and incorrect!) implementation is already provided for Pools that don't override * `_processSwapFeeAmount` and skip the entire feature. However, Pools that do override `_processSwapFeeAmount` * *must* override this function with a meaningful implementation. */ function _tokenAddressToIndex( IERC20 /*token*/ ) internal view virtual returns (uint256) { return 0; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol"; import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol"; // These functions start with an underscore, as if they were part of a contract and not a library. At some point this // should be fixed. Additionally, some variables have non mixed case names (e.g. P_D) that relate to the mathematical // derivations. // solhint-disable private-vars-leading-underscore, var-name-mixedcase library StableMath { using FixedPoint for uint256; uint256 internal constant _MIN_AMP = 1; uint256 internal constant _MAX_AMP = 5000; uint256 internal constant _AMP_PRECISION = 1e3; uint256 internal constant _MAX_STABLE_TOKENS = 5; // Note on unchecked arithmetic: // This contract performs a large number of additions, subtractions, multiplications and divisions, often inside // loops. Since many of these operations are gas-sensitive (as they happen e.g. during a swap), it is important to // not make any unnecessary checks. We rely on a set of invariants to avoid having to use checked arithmetic (the // Math library), including: // - the number of tokens is bounded by _MAX_STABLE_TOKENS // - the amplification parameter is bounded by _MAX_AMP * _AMP_PRECISION, which fits in 23 bits // - the token balances are bounded by 2^112 (guaranteed by the Vault) times 1e18 (the maximum scaling factor), // which fits in 172 bits // // This means e.g. we can safely multiply a balance by the amplification parameter without worrying about overflow. // About swap fees on joins and exits: // Any join or exit that is not perfectly balanced (e.g. all single token joins or exits) is mathematically // equivalent to a perfectly balanced join or exit followed by a series of swaps. Since these swaps would charge // swap fees, it follows that (some) joins and exits should as well. // On these operations, we split the token amounts in 'taxable' and 'non-taxable' portions, where the 'taxable' part // is the one to which swap fees are applied. // Computes the invariant given the current balances, using the Newton-Raphson approximation. // The amplification parameter equals: A n^(n-1) function _calculateInvariant( uint256 amplificationParameter, uint256[] memory balances, bool roundUp ) internal pure returns (uint256) { /********************************************************************************************** // invariant // // D = invariant D^(n+1) // // A = amplification coefficient A n^n S + D = A D n^n + ----------- // // S = sum of balances n^n P // // P = product of balances // // n = number of tokens // **********************************************************************************************/ // We support rounding up or down. uint256 sum = 0; uint256 numTokens = balances.length; for (uint256 i = 0; i < numTokens; i++) { sum = sum.add(balances[i]); } if (sum == 0) { return 0; } uint256 prevInvariant = 0; uint256 invariant = sum; uint256 ampTimesTotal = amplificationParameter * numTokens; for (uint256 i = 0; i < 255; i++) { uint256 P_D = balances[0] * numTokens; for (uint256 j = 1; j < numTokens; j++) { P_D = Math.div(Math.mul(Math.mul(P_D, balances[j]), numTokens), invariant, roundUp); } prevInvariant = invariant; invariant = Math.div( Math.mul(Math.mul(numTokens, invariant), invariant).add( Math.div(Math.mul(Math.mul(ampTimesTotal, sum), P_D), _AMP_PRECISION, roundUp) ), Math.mul(numTokens + 1, invariant).add( // No need to use checked arithmetic for the amp precision, the amp is guaranteed to be at least 1 Math.div(Math.mul(ampTimesTotal - _AMP_PRECISION, P_D), _AMP_PRECISION, !roundUp) ), roundUp ); if (invariant > prevInvariant) { if (invariant - prevInvariant <= 1) { return invariant; } } else if (prevInvariant - invariant <= 1) { return invariant; } } _revert(Errors.STABLE_INVARIANT_DIDNT_CONVERGE); } // Computes how many tokens can be taken out of a pool if `tokenAmountIn` are sent, given the current balances. // The amplification parameter equals: A n^(n-1) // The invariant should be rounded up. function _calcOutGivenIn( uint256 amplificationParameter, uint256[] memory balances, uint256 tokenIndexIn, uint256 tokenIndexOut, uint256 tokenAmountIn, uint256 invariant ) internal pure returns (uint256) { /************************************************************************************************************** // outGivenIn token x for y - polynomial equation to solve // // ay = amount out to calculate // // by = balance token out // // y = by - ay (finalBalanceOut) // // D = invariant D D^(n+1) // // A = amplification coefficient y^2 + ( S - ---------- - D) * y - ------------- = 0 // // n = number of tokens (A * n^n) A * n^2n * P // // S = sum of final balances but y // // P = product of final balances but y // **************************************************************************************************************/ // Amount out, so we round down overall. balances[tokenIndexIn] = balances[tokenIndexIn].add(tokenAmountIn); uint256 finalBalanceOut = _getTokenBalanceGivenInvariantAndAllOtherBalances( amplificationParameter, balances, invariant, tokenIndexOut ); // No need to use checked arithmetic since `tokenAmountIn` was actually added to the same balance right before // calling `_getTokenBalanceGivenInvariantAndAllOtherBalances` which doesn't alter the balances array. balances[tokenIndexIn] = balances[tokenIndexIn] - tokenAmountIn; return balances[tokenIndexOut].sub(finalBalanceOut).sub(1); } // Computes how many tokens must be sent to a pool if `tokenAmountOut` are sent given the // current balances, using the Newton-Raphson approximation. // The amplification parameter equals: A n^(n-1) // The invariant should be rounded up. function _calcInGivenOut( uint256 amplificationParameter, uint256[] memory balances, uint256 tokenIndexIn, uint256 tokenIndexOut, uint256 tokenAmountOut, uint256 invariant ) internal pure returns (uint256) { /************************************************************************************************************** // inGivenOut token x for y - polynomial equation to solve // // ax = amount in to calculate // // bx = balance token in // // x = bx + ax (finalBalanceIn) // // D = invariant D D^(n+1) // // A = amplification coefficient x^2 + ( S - ---------- - D) * x - ------------- = 0 // // n = number of tokens (A * n^n) A * n^2n * P // // S = sum of final balances but x // // P = product of final balances but x // **************************************************************************************************************/ // Amount in, so we round up overall. balances[tokenIndexOut] = balances[tokenIndexOut].sub(tokenAmountOut); uint256 finalBalanceIn = _getTokenBalanceGivenInvariantAndAllOtherBalances( amplificationParameter, balances, invariant, tokenIndexIn ); // No need to use checked arithmetic since `tokenAmountOut` was actually subtracted from the same balance right // before calling `_getTokenBalanceGivenInvariantAndAllOtherBalances` which doesn't alter the balances array. balances[tokenIndexOut] = balances[tokenIndexOut] + tokenAmountOut; return finalBalanceIn.sub(balances[tokenIndexIn]).add(1); } function _calcBptOutGivenExactTokensIn( uint256 amp, uint256[] memory balances, uint256[] memory amountsIn, uint256 bptTotalSupply, uint256 swapFeePercentage ) internal pure returns (uint256) { // BPT out, so we round down overall. // First loop calculates the sum of all token balances, which will be used to calculate // the current weights of each token, relative to this sum uint256 sumBalances = 0; for (uint256 i = 0; i < balances.length; i++) { sumBalances = sumBalances.add(balances[i]); } // Calculate the weighted balance ratio without considering fees uint256[] memory balanceRatiosWithFee = new uint256[](amountsIn.length); // The weighted sum of token balance ratios with fee uint256 invariantRatioWithFees = 0; for (uint256 i = 0; i < balances.length; i++) { uint256 currentWeight = balances[i].divDown(sumBalances); balanceRatiosWithFee[i] = balances[i].add(amountsIn[i]).divDown(balances[i]); invariantRatioWithFees = invariantRatioWithFees.add(balanceRatiosWithFee[i].mulDown(currentWeight)); } // Second loop calculates new amounts in, taking into account the fee on the percentage excess uint256[] memory newBalances = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { uint256 amountInWithoutFee; // Check if the balance ratio is greater than the ideal ratio to charge fees or not if (balanceRatiosWithFee[i] > invariantRatioWithFees) { uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithFees.sub(FixedPoint.ONE)); uint256 taxableAmount = amountsIn[i].sub(nonTaxableAmount); // No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50% amountInWithoutFee = nonTaxableAmount.add(taxableAmount.mulDown(FixedPoint.ONE - swapFeePercentage)); } else { amountInWithoutFee = amountsIn[i]; } newBalances[i] = balances[i].add(amountInWithoutFee); } // Get current and new invariants, taking swap fees into account uint256 currentInvariant = _calculateInvariant(amp, balances, true); uint256 newInvariant = _calculateInvariant(amp, newBalances, false); uint256 invariantRatio = newInvariant.divDown(currentInvariant); // If the invariant didn't increase for any reason, we simply don't mint BPT if (invariantRatio > FixedPoint.ONE) { return bptTotalSupply.mulDown(invariantRatio - FixedPoint.ONE); } else { return 0; } } function _calcTokenInGivenExactBptOut( uint256 amp, uint256[] memory balances, uint256 tokenIndex, uint256 bptAmountOut, uint256 bptTotalSupply, uint256 swapFeePercentage ) internal pure returns (uint256) { // Token in, so we round up overall. // Get the current invariant uint256 currentInvariant = _calculateInvariant(amp, balances, true); // Calculate new invariant uint256 newInvariant = bptTotalSupply.add(bptAmountOut).divUp(bptTotalSupply).mulUp(currentInvariant); // Calculate amount in without fee. uint256 newBalanceTokenIndex = _getTokenBalanceGivenInvariantAndAllOtherBalances( amp, balances, newInvariant, tokenIndex ); uint256 amountInWithoutFee = newBalanceTokenIndex.sub(balances[tokenIndex]); // First calculate the sum of all token balances, which will be used to calculate // the current weight of each token uint256 sumBalances = 0; for (uint256 i = 0; i < balances.length; i++) { sumBalances = sumBalances.add(balances[i]); } // We can now compute how much extra balance is being deposited and used in virtual swaps, and charge swap fees // accordingly. uint256 currentWeight = balances[tokenIndex].divDown(sumBalances); uint256 taxablePercentage = currentWeight.complement(); uint256 taxableAmount = amountInWithoutFee.mulUp(taxablePercentage); uint256 nonTaxableAmount = amountInWithoutFee.sub(taxableAmount); // No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50% return nonTaxableAmount.add(taxableAmount.divUp(FixedPoint.ONE - swapFeePercentage)); } /* Flow of calculations: amountsTokenOut -> amountsOutProportional -> amountOutPercentageExcess -> amountOutBeforeFee -> newInvariant -> amountBPTIn */ function _calcBptInGivenExactTokensOut( uint256 amp, uint256[] memory balances, uint256[] memory amountsOut, uint256 bptTotalSupply, uint256 swapFeePercentage ) internal pure returns (uint256) { // BPT in, so we round up overall. // First loop calculates the sum of all token balances, which will be used to calculate // the current weights of each token relative to this sum uint256 sumBalances = 0; for (uint256 i = 0; i < balances.length; i++) { sumBalances = sumBalances.add(balances[i]); } // Calculate the weighted balance ratio without considering fees uint256[] memory balanceRatiosWithoutFee = new uint256[](amountsOut.length); uint256 invariantRatioWithoutFees = 0; for (uint256 i = 0; i < balances.length; i++) { uint256 currentWeight = balances[i].divUp(sumBalances); balanceRatiosWithoutFee[i] = balances[i].sub(amountsOut[i]).divUp(balances[i]); invariantRatioWithoutFees = invariantRatioWithoutFees.add(balanceRatiosWithoutFee[i].mulUp(currentWeight)); } // Second loop calculates new amounts in, taking into account the fee on the percentage excess uint256[] memory newBalances = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { // Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it to // 'token out'. This results in slightly larger price impact. uint256 amountOutWithFee; if (invariantRatioWithoutFees > balanceRatiosWithoutFee[i]) { uint256 nonTaxableAmount = balances[i].mulDown(invariantRatioWithoutFees.complement()); uint256 taxableAmount = amountsOut[i].sub(nonTaxableAmount); // No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50% amountOutWithFee = nonTaxableAmount.add(taxableAmount.divUp(FixedPoint.ONE - swapFeePercentage)); } else { amountOutWithFee = amountsOut[i]; } newBalances[i] = balances[i].sub(amountOutWithFee); } // Get current and new invariants, taking into account swap fees uint256 currentInvariant = _calculateInvariant(amp, balances, true); uint256 newInvariant = _calculateInvariant(amp, newBalances, false); uint256 invariantRatio = newInvariant.divDown(currentInvariant); // return amountBPTIn return bptTotalSupply.mulUp(invariantRatio.complement()); } function _calcTokenOutGivenExactBptIn( uint256 amp, uint256[] memory balances, uint256 tokenIndex, uint256 bptAmountIn, uint256 bptTotalSupply, uint256 swapFeePercentage ) internal pure returns (uint256) { // Token out, so we round down overall. // Get the current and new invariants. Since we need a bigger new invariant, we round the current one up. uint256 currentInvariant = _calculateInvariant(amp, balances, true); uint256 newInvariant = bptTotalSupply.sub(bptAmountIn).divUp(bptTotalSupply).mulUp(currentInvariant); // Calculate amount out without fee uint256 newBalanceTokenIndex = _getTokenBalanceGivenInvariantAndAllOtherBalances( amp, balances, newInvariant, tokenIndex ); uint256 amountOutWithoutFee = balances[tokenIndex].sub(newBalanceTokenIndex); // First calculate the sum of all token balances, which will be used to calculate // the current weight of each token uint256 sumBalances = 0; for (uint256 i = 0; i < balances.length; i++) { sumBalances = sumBalances.add(balances[i]); } // We can now compute how much excess balance is being withdrawn as a result of the virtual swaps, which result // in swap fees. uint256 currentWeight = balances[tokenIndex].divDown(sumBalances); uint256 taxablePercentage = currentWeight.complement(); // Swap fees are typically charged on 'token in', but there is no 'token in' here, so we apply it // to 'token out'. This results in slightly larger price impact. Fees are rounded up. uint256 taxableAmount = amountOutWithoutFee.mulUp(taxablePercentage); uint256 nonTaxableAmount = amountOutWithoutFee.sub(taxableAmount); // No need to use checked arithmetic for the swap fee, it is guaranteed to be lower than 50% return nonTaxableAmount.add(taxableAmount.mulDown(FixedPoint.ONE - swapFeePercentage)); } function _calcTokensOutGivenExactBptIn( uint256[] memory balances, uint256 bptAmountIn, uint256 bptTotalSupply ) internal pure returns (uint256[] memory) { /********************************************************************************************** // exactBPTInForTokensOut // // (per token) // // aO = tokenAmountOut / bptIn \ // // b = tokenBalance a0 = b * | --------------------- | // // bptIn = bptAmountIn \ bptTotalSupply / // // bpt = bptTotalSupply // **********************************************************************************************/ // Since we're computing an amount out, we round down overall. This means rounding down on both the // multiplication and division. uint256 bptRatio = bptAmountIn.divDown(bptTotalSupply); uint256[] memory amountsOut = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amountsOut[i] = balances[i].mulDown(bptRatio); } return amountsOut; } // The amplification parameter equals: A n^(n-1) function _calcDueTokenProtocolSwapFeeAmount( uint256 amplificationParameter, uint256[] memory balances, uint256 lastInvariant, uint256 tokenIndex, uint256 protocolSwapFeePercentage ) internal pure returns (uint256) { /************************************************************************************************************** // oneTokenSwapFee - polynomial equation to solve // // af = fee amount to calculate in one token // // bf = balance of fee token // // f = bf - af (finalBalanceFeeToken) // // D = old invariant D D^(n+1) // // A = amplification coefficient f^2 + ( S - ---------- - D) * f - ------------- = 0 // // n = number of tokens (A * n^n) A * n^2n * P // // S = sum of final balances but f // // P = product of final balances but f // **************************************************************************************************************/ // Protocol swap fee amount, so we round down overall. uint256 finalBalanceFeeToken = _getTokenBalanceGivenInvariantAndAllOtherBalances( amplificationParameter, balances, lastInvariant, tokenIndex ); if (balances[tokenIndex] <= finalBalanceFeeToken) { // This shouldn't happen outside of rounding errors, but have this safeguard nonetheless to prevent the Pool // from entering a locked state in which joins and exits revert while computing accumulated swap fees. return 0; } // Result is rounded down uint256 accumulatedTokenSwapFees = balances[tokenIndex] - finalBalanceFeeToken; return accumulatedTokenSwapFees.mulDown(protocolSwapFeePercentage); } // This function calculates the balance of a given token (tokenIndex) // given all the other balances and the invariant function _getTokenBalanceGivenInvariantAndAllOtherBalances( uint256 amplificationParameter, uint256[] memory balances, uint256 invariant, uint256 tokenIndex ) internal pure returns (uint256) { // Rounds result up overall uint256 ampTimesTotal = amplificationParameter * balances.length; uint256 sum = balances[0]; uint256 P_D = balances[0] * balances.length; for (uint256 j = 1; j < balances.length; j++) { P_D = Math.divDown(Math.mul(Math.mul(P_D, balances[j]), balances.length), invariant); sum = sum.add(balances[j]); } // No need to use safe math, based on the loop above `sum` is greater than or equal to `balances[tokenIndex]` sum = sum - balances[tokenIndex]; uint256 inv2 = Math.mul(invariant, invariant); // We remove the balance from c by multiplying it uint256 c = Math.mul( Math.mul(Math.divUp(inv2, Math.mul(ampTimesTotal, P_D)), _AMP_PRECISION), balances[tokenIndex] ); uint256 b = sum.add(Math.mul(Math.divDown(invariant, ampTimesTotal), _AMP_PRECISION)); // We iterate to find the balance uint256 prevTokenBalance = 0; // We multiply the first iteration outside the loop with the invariant to set the value of the // initial approximation. uint256 tokenBalance = Math.divUp(inv2.add(c), invariant.add(b)); for (uint256 i = 0; i < 255; i++) { prevTokenBalance = tokenBalance; tokenBalance = Math.divUp( Math.mul(tokenBalance, tokenBalance).add(c), Math.mul(tokenBalance, 2).add(b).sub(invariant) ); if (tokenBalance > prevTokenBalance) { if (tokenBalance - prevTokenBalance <= 1) { return tokenBalance; } } else if (prevTokenBalance - tokenBalance <= 1) { return tokenBalance; } } _revert(Errors.STABLE_GET_BALANCE_DIDNT_CONVERGE); } function _getRate( uint256[] memory balances, uint256 amp, uint256 supply ) internal pure returns (uint256) { // When calculating the current BPT rate, we may not have paid the protocol fees, therefore // the invariant should be smaller than its current value. Then, we round down overall. uint256 invariant = _calculateInvariant(amp, balances, false); return invariant.divDown(supply); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; library StablePoolUserData { // In order to preserve backwards compatibility, make sure new join and exit kinds are added at the end of the enum. enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT } enum ExitKind { EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT } function joinKind(bytes memory self) internal pure returns (JoinKind) { return abi.decode(self, (JoinKind)); } function exitKind(bytes memory self) internal pure returns (ExitKind) { return abi.decode(self, (ExitKind)); } // Joins function initialAmountsIn(bytes memory self) internal pure returns (uint256[] memory amountsIn) { (, amountsIn) = abi.decode(self, (JoinKind, uint256[])); } function exactTokensInForBptOut(bytes memory self) internal pure returns (uint256[] memory amountsIn, uint256 minBPTAmountOut) { (, amountsIn, minBPTAmountOut) = abi.decode(self, (JoinKind, uint256[], uint256)); } function tokenInForExactBptOut(bytes memory self) internal pure returns (uint256 bptAmountOut, uint256 tokenIndex) { (, bptAmountOut, tokenIndex) = abi.decode(self, (JoinKind, uint256, uint256)); } // Exits function exactBptInForTokenOut(bytes memory self) internal pure returns (uint256 bptAmountIn, uint256 tokenIndex) { (, bptAmountIn, tokenIndex) = abi.decode(self, (ExitKind, uint256, uint256)); } function exactBptInForTokensOut(bytes memory self) internal pure returns (uint256 bptAmountIn) { (, bptAmountIn) = abi.decode(self, (ExitKind, uint256)); } function bptInForExactTokensOut(bytes memory self) internal pure returns (uint256[] memory amountsOut, uint256 maxBPTAmountIn) { (, amountsOut, maxBPTAmountIn) = abi.decode(self, (ExitKind, uint256[], uint256)); } } // SPDX-License-Identifier: MIT // 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.7.0; import "../helpers/BalancerErrors.sol"; /* solhint-disable */ /** * @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument). * * Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural * exponentiation and logarithm (where the base is Euler's number). * * @author Fernando Martinelli - @fernandomartinelli * @author Sergio Yuhjtman - @sergioyuhjtman * @author Daniel Fernandez - @dmf7z */ library LogExpMath { // All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying // two numbers, and multiply by ONE when dividing them. // All arguments and return values are 18 decimal fixed point numbers. int256 constant ONE_18 = 1e18; // Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the // case of ln36, 36 decimals. int256 constant ONE_20 = 1e20; int256 constant ONE_36 = 1e36; // The domain of natural exponentiation is bound by the word size and number of decimals used. // // Because internally the result will be stored using 20 decimals, the largest possible result is // (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221. // The smallest possible result is 10^(-18), which makes largest negative argument // ln(10^(-18)) = -41.446531673892822312. // We use 130.0 and -41.0 to have some safety margin. int256 constant MAX_NATURAL_EXPONENT = 130e18; int256 constant MIN_NATURAL_EXPONENT = -41e18; // Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point // 256 bit integer. int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17; int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17; uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20); // 18 decimal constants int256 constant x0 = 128000000000000000000; // 2ˆ7 int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals) int256 constant x1 = 64000000000000000000; // 2ˆ6 int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals) // 20 decimal constants int256 constant x2 = 3200000000000000000000; // 2ˆ5 int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2) int256 constant x3 = 1600000000000000000000; // 2ˆ4 int256 constant a3 = 888611052050787263676000000; // eˆ(x3) int256 constant x4 = 800000000000000000000; // 2ˆ3 int256 constant a4 = 298095798704172827474000; // eˆ(x4) int256 constant x5 = 400000000000000000000; // 2ˆ2 int256 constant a5 = 5459815003314423907810; // eˆ(x5) int256 constant x6 = 200000000000000000000; // 2ˆ1 int256 constant a6 = 738905609893065022723; // eˆ(x6) int256 constant x7 = 100000000000000000000; // 2ˆ0 int256 constant a7 = 271828182845904523536; // eˆ(x7) int256 constant x8 = 50000000000000000000; // 2ˆ-1 int256 constant a8 = 164872127070012814685; // eˆ(x8) int256 constant x9 = 25000000000000000000; // 2ˆ-2 int256 constant a9 = 128402541668774148407; // eˆ(x9) int256 constant x10 = 12500000000000000000; // 2ˆ-3 int256 constant a10 = 113314845306682631683; // eˆ(x10) int256 constant x11 = 6250000000000000000; // 2ˆ-4 int256 constant a11 = 106449445891785942956; // eˆ(x11) /** * @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent. * * Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`. */ function pow(uint256 x, uint256 y) internal pure returns (uint256) { if (y == 0) { // We solve the 0^0 indetermination by making it equal one. return uint256(ONE_18); } if (x == 0) { return 0; } // Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to // arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means // x^y = exp(y * ln(x)). // The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range. _require(x < 2**255, Errors.X_OUT_OF_BOUNDS); int256 x_int256 = int256(x); // We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In // both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end. // This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range. _require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS); int256 y_int256 = int256(y); int256 logx_times_y; if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) { int256 ln_36_x = _ln_36(x_int256); // ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just // bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal // multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the // (downscaled) last 18 decimals. logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18); } else { logx_times_y = _ln(x_int256) * y_int256; } logx_times_y /= ONE_18; // Finally, we compute exp(y * ln(x)) to arrive at x^y _require( MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT, Errors.PRODUCT_OUT_OF_BOUNDS ); return uint256(exp(logx_times_y)); } /** * @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent. * * Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`. */ function exp(int256 x) internal pure returns (int256) { _require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT); if (x < 0) { // We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it // fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT). // Fixed point division requires multiplying by ONE_18. return ((ONE_18 * ONE_18) / exp(-x)); } // First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n, // where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7 // because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the // decomposition. // At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this // decomposition, which will be lower than the smallest x_n. // exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1. // We mutate x by subtracting x_n, making it the remainder of the decomposition. // The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause // intermediate overflows. Instead we store them as plain integers, with 0 decimals. // Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the // decomposition. // For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct // it and compute the accumulated product. int256 firstAN; if (x >= x0) { x -= x0; firstAN = a0; } else if (x >= x1) { x -= x1; firstAN = a1; } else { firstAN = 1; // One with no decimal places } // We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the // smaller terms. x *= 100; // `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point // one. Recall that fixed point multiplication requires dividing by ONE_20. int256 product = ONE_20; if (x >= x2) { x -= x2; product = (product * a2) / ONE_20; } if (x >= x3) { x -= x3; product = (product * a3) / ONE_20; } if (x >= x4) { x -= x4; product = (product * a4) / ONE_20; } if (x >= x5) { x -= x5; product = (product * a5) / ONE_20; } if (x >= x6) { x -= x6; product = (product * a6) / ONE_20; } if (x >= x7) { x -= x7; product = (product * a7) / ONE_20; } if (x >= x8) { x -= x8; product = (product * a8) / ONE_20; } if (x >= x9) { x -= x9; product = (product * a9) / ONE_20; } // x10 and x11 are unnecessary here since we have high enough precision already. // Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series // expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!). int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places. int256 term; // Each term in the sum, where the nth term is (x^n / n!). // The first term is simply x. term = x; seriesSum += term; // Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number, // multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not. term = ((term * x) / ONE_20) / 2; seriesSum += term; term = ((term * x) / ONE_20) / 3; seriesSum += term; term = ((term * x) / ONE_20) / 4; seriesSum += term; term = ((term * x) / ONE_20) / 5; seriesSum += term; term = ((term * x) / ONE_20) / 6; seriesSum += term; term = ((term * x) / ONE_20) / 7; seriesSum += term; term = ((term * x) / ONE_20) / 8; seriesSum += term; term = ((term * x) / ONE_20) / 9; seriesSum += term; term = ((term * x) / ONE_20) / 10; seriesSum += term; term = ((term * x) / ONE_20) / 11; seriesSum += term; term = ((term * x) / ONE_20) / 12; seriesSum += term; // 12 Taylor terms are sufficient for 18 decimal precision. // We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor // approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply // all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication), // and then drop two digits to return an 18 decimal value. return (((product * seriesSum) / ONE_20) * firstAN) / 100; } /** * @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument. */ function log(int256 arg, int256 base) internal pure returns (int256) { // This performs a simple base change: log(arg, base) = ln(arg) / ln(base). // Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by // upscaling. int256 logBase; if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) { logBase = _ln_36(base); } else { logBase = _ln(base) * ONE_18; } int256 logArg; if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) { logArg = _ln_36(arg); } else { logArg = _ln(arg) * ONE_18; } // When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places return (logArg * ONE_18) / logBase; } /** * @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function ln(int256 a) internal pure returns (int256) { // The real natural logarithm is not defined for negative numbers or zero. _require(a > 0, Errors.OUT_OF_BOUNDS); if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) { return _ln_36(a) / ONE_18; } else { return _ln(a); } } /** * @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function _ln(int256 a) private pure returns (int256) { if (a < ONE_18) { // Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less // than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call. // Fixed point division requires multiplying by ONE_18. return (-_ln((ONE_18 * ONE_18) / a)); } // First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which // we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is, // ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot // be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a. // At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this // decomposition, which will be lower than the smallest a_n. // ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1. // We mutate a by subtracting a_n, making it the remainder of the decomposition. // For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point // numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by // ONE_18 to convert them to fixed point. // For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide // by it and compute the accumulated sum. int256 sum = 0; if (a >= a0 * ONE_18) { a /= a0; // Integer, not fixed point division sum += x0; } if (a >= a1 * ONE_18) { a /= a1; // Integer, not fixed point division sum += x1; } // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format. sum *= 100; a *= 100; // Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them. if (a >= a2) { a = (a * ONE_20) / a2; sum += x2; } if (a >= a3) { a = (a * ONE_20) / a3; sum += x3; } if (a >= a4) { a = (a * ONE_20) / a4; sum += x4; } if (a >= a5) { a = (a * ONE_20) / a5; sum += x5; } if (a >= a6) { a = (a * ONE_20) / a6; sum += x6; } if (a >= a7) { a = (a * ONE_20) / a7; sum += x7; } if (a >= a8) { a = (a * ONE_20) / a8; sum += x8; } if (a >= a9) { a = (a * ONE_20) / a9; sum += x9; } if (a >= a10) { a = (a * ONE_20) / a10; sum += x10; } if (a >= a11) { a = (a * ONE_20) / a11; sum += x11; } // a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series // that converges rapidly for values of `a` close to one - the same one used in ln_36. // Let z = (a - 1) / (a + 1). // ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires // division by ONE_20. int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20); int256 z_squared = (z * z) / ONE_20; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_20; seriesSum += num / 3; num = (num * z_squared) / ONE_20; seriesSum += num / 5; num = (num * z_squared) / ONE_20; seriesSum += num / 7; num = (num * z_squared) / ONE_20; seriesSum += num / 9; num = (num * z_squared) / ONE_20; seriesSum += num / 11; // 6 Taylor terms are sufficient for 36 decimal precision. // Finally, we multiply by 2 (non fixed point) to compute ln(remainder) seriesSum *= 2; // We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both // with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal // value. return (sum + seriesSum) / 100; } /** * @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument, * for x close to one. * * Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND. */ function _ln_36(int256 x) private pure returns (int256) { // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits // worthwhile. // First, we transform x to a 36 digit fixed point value. x *= ONE_18; // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1). // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires // division by ONE_36. int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36); int256 z_squared = (z * z) / ONE_36; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_36; seriesSum += num / 3; num = (num * z_squared) / ONE_36; seriesSum += num / 5; num = (num * z_squared) / ONE_36; seriesSum += num / 7; num = (num * z_squared) / ONE_36; seriesSum += num / 9; num = (num * z_squared) / ONE_36; seriesSum += num / 11; num = (num * z_squared) / ONE_36; seriesSum += num / 13; num = (num * z_squared) / ONE_36; seriesSum += num / 15; // 8 Taylor terms are sufficient for 36 decimal precision. // All that remains is multiplying by 2 (non fixed point). return seriesSum * 2; } } // 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: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol"; import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/TemporarilyPausable.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol"; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IBasePool.sol"; import "@balancer-labs/v2-asset-manager-utils/contracts/IAssetManager.sol"; import "./BalancerPoolToken.sol"; import "./BasePoolAuthorization.sol"; // solhint-disable max-states-count /** * @dev Reference implementation for the base layer of a Pool contract that manages a single Pool with optional * Asset Managers, an admin-controlled swap fee percentage, and an emergency pause mechanism. * * Note that neither swap fees nor the pause mechanism are used by this contract. They are passed through so that * derived contracts can use them via the `_addSwapFeeAmount` and `_subtractSwapFeeAmount` functions, and the * `whenNotPaused` modifier. * * No admin permissions are checked here: instead, this contract delegates that to the Vault's own Authorizer. * * Because this contract doesn't implement the swap hooks, derived contracts should generally inherit from * BaseGeneralPool or BaseMinimalSwapInfoPool. Otherwise, subclasses must inherit from the corresponding interfaces * and implement the swap callbacks themselves. */ abstract contract BasePool is IBasePool, BasePoolAuthorization, BalancerPoolToken, TemporarilyPausable { using WordCodec for bytes32; using FixedPoint for uint256; uint256 private constant _MIN_TOKENS = 2; uint256 private constant _DEFAULT_MINIMUM_BPT = 1e6; // 1e18 corresponds to 1.0, or a 100% fee uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001% uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10% - this fits in 64 bits // Storage slot that can be used to store unrelated pieces of information. In particular, by default is used // to store only the swap fee percentage of a pool. But it can be extended to store some more pieces of information. // The swap fee percentage is stored in the most-significant 64 bits, therefore the remaining 192 bits can be // used to store any other piece of information. bytes32 private _miscData; uint256 private constant _SWAP_FEE_PERCENTAGE_OFFSET = 192; bytes32 private immutable _poolId; event SwapFeePercentageChanged(uint256 swapFeePercentage); constructor( IVault vault, IVault.PoolSpecialization specialization, string memory name, string memory symbol, IERC20[] memory tokens, address[] memory assetManagers, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) // Base Pools are expected to be deployed using factories. By using the factory address as the action // disambiguator, we make all Pools deployed by the same factory share action identifiers. This allows for // simpler management of permissions (such as being able to manage granting the 'set fee percentage' action in // any Pool created by the same factory), while still making action identifiers unique among different factories // if the selectors match, preventing accidental errors. Authentication(bytes32(uint256(msg.sender))) BalancerPoolToken(name, symbol, vault) BasePoolAuthorization(owner) TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration) { _require(tokens.length >= _MIN_TOKENS, Errors.MIN_TOKENS); _require(tokens.length <= _getMaxTokens(), Errors.MAX_TOKENS); // The Vault only requires the token list to be ordered for the Two Token Pools specialization. However, // to make the developer experience consistent, we are requiring this condition for all the native pools. // Also, since these Pools will register tokens only once, we can ensure the Pool tokens will follow the same // order. We rely on this property to make Pools simpler to write, as it lets us assume that the // order of token-specific parameters (such as token weights) will not change. InputHelpers.ensureArrayIsSorted(tokens); _setSwapFeePercentage(swapFeePercentage); bytes32 poolId = vault.registerPool(specialization); vault.registerTokens(poolId, tokens, assetManagers); // Set immutable state variables - these cannot be read from during construction _poolId = poolId; } // Getters / Setters function getPoolId() public view override returns (bytes32) { return _poolId; } function _getTotalTokens() internal view virtual returns (uint256); function _getMaxTokens() internal pure virtual returns (uint256); /** * @dev Returns the minimum BPT supply. This amount is minted to the zero address during initialization, effectively * locking it. * * This is useful to make sure Pool initialization happens only once, but derived Pools can change this value (even * to zero) by overriding this function. */ function _getMinimumBpt() internal pure virtual returns (uint256) { return _DEFAULT_MINIMUM_BPT; } function getSwapFeePercentage() public view returns (uint256) { return _miscData.decodeUint64(_SWAP_FEE_PERCENTAGE_OFFSET); } function setSwapFeePercentage(uint256 swapFeePercentage) public virtual authenticate whenNotPaused { _setSwapFeePercentage(swapFeePercentage); } function _setSwapFeePercentage(uint256 swapFeePercentage) private { _require(swapFeePercentage >= _MIN_SWAP_FEE_PERCENTAGE, Errors.MIN_SWAP_FEE_PERCENTAGE); _require(swapFeePercentage <= _MAX_SWAP_FEE_PERCENTAGE, Errors.MAX_SWAP_FEE_PERCENTAGE); _miscData = _miscData.insertUint64(swapFeePercentage, _SWAP_FEE_PERCENTAGE_OFFSET); emit SwapFeePercentageChanged(swapFeePercentage); } function setAssetManagerPoolConfig(IERC20 token, bytes memory poolConfig) public virtual authenticate whenNotPaused { _setAssetManagerPoolConfig(token, poolConfig); } function _setAssetManagerPoolConfig(IERC20 token, bytes memory poolConfig) private { bytes32 poolId = getPoolId(); (, , , address assetManager) = getVault().getPoolTokenInfo(poolId, token); IAssetManager(assetManager).setConfig(poolId, poolConfig); } function setPaused(bool paused) external authenticate { _setPaused(paused); } function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) { return (actionId == getActionId(this.setSwapFeePercentage.selector)) || (actionId == getActionId(this.setAssetManagerPoolConfig.selector)); } function _getMiscData() internal view returns (bytes32) { return _miscData; } /** * Inserts data into the least-significant 192 bits of the misc data storage slot. * Note that the remaining 64 bits are used for the swap fee percentage and cannot be overloaded. */ function _setMiscData(bytes32 newData) internal { _miscData = _miscData.insertBits192(newData, 0); } // Join / Exit Hooks modifier onlyVault(bytes32 poolId) { _require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT); _require(poolId == getPoolId(), Errors.INVALID_POOL_ID); _; } function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) public virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { uint256[] memory scalingFactors = _scalingFactors(); if (totalSupply() == 0) { (uint256 bptAmountOut, uint256[] memory amountsIn) = _onInitializePool( poolId, sender, recipient, scalingFactors, userData ); // On initialization, we lock _getMinimumBpt() by minting it for the zero address. This BPT acts as a // minimum as it will never be burned, which reduces potential issues with rounding, and also prevents the // Pool from ever being fully drained. _require(bptAmountOut >= _getMinimumBpt(), Errors.MINIMUM_BPT); _mintPoolTokens(address(0), _getMinimumBpt()); _mintPoolTokens(recipient, bptAmountOut - _getMinimumBpt()); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn, scalingFactors); return (amountsIn, new uint256[](_getTotalTokens())); } else { _upscaleArray(balances, scalingFactors); (uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) = _onJoinPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, scalingFactors, userData ); // Note we no longer use `balances` after calling `_onJoinPool`, which may mutate it. _mintPoolTokens(recipient, bptAmountOut); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn, scalingFactors); // dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(dueProtocolFeeAmounts, scalingFactors); return (amountsIn, dueProtocolFeeAmounts); } } function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) public virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, scalingFactors, userData ); // Note we no longer use `balances` after calling `_onExitPool`, which may mutate it. _burnPoolTokens(sender, bptAmountIn); // Both amountsOut and dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(amountsOut, scalingFactors); _downscaleDownArray(dueProtocolFeeAmounts, scalingFactors); return (amountsOut, dueProtocolFeeAmounts); } // Query functions /** * @dev Returns the amount of BPT that would be granted to `recipient` if the `onJoinPool` hook were called by the * Vault with the same arguments, along with the number of tokens `sender` would have to supply. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryJoin( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptOut, uint256[] memory amountsIn) { InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens()); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onJoinPool, _downscaleUpArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptOut, amountsIn); } /** * @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the * Vault with the same arguments, along with the number of tokens `recipient` would receive. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryExit( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptIn, uint256[] memory amountsOut) { InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens()); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onExitPool, _downscaleDownArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptIn, amountsOut); } // Internal hooks to be overridden by derived contracts - all token amounts (except BPT) in these interfaces are // upscaled. /** * @dev Called when the Pool is joined for the first time; that is, when the BPT total supply is zero. * * Returns the amount of BPT to mint, and the token amounts the Pool will receive in return. * * Minted BPT will be sent to `recipient`, except for _getMinimumBpt(), which will be deducted from this amount and * sent to the zero address instead. This will cause that BPT to remain forever locked there, preventing total BTP * from ever dropping below that value, and ensuring `_onInitializePool` can only be called once in the entire * Pool's lifetime. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. */ function _onInitializePool( bytes32 poolId, address sender, address recipient, uint256[] memory scalingFactors, bytes memory userData ) internal virtual returns (uint256 bptAmountOut, uint256[] memory amountsIn); /** * @dev Called whenever the Pool is joined after the first initialization join (see `_onInitializePool`). * * Returns the amount of BPT to mint, the token amounts that the Pool will receive in return, and the number of * tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * Minted BPT will be sent to `recipient`. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onJoinPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, uint256[] memory scalingFactors, bytes memory userData ) internal virtual returns ( uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts ); /** * @dev Called whenever the Pool is exited. * * Returns the amount of BPT to burn, the token amounts for each Pool token that the Pool will grant in return, and * the number of tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * BPT will be burnt from `sender`. * * The Pool will grant tokens to `recipient`. These amounts are considered upscaled and will be downscaled * (rounding down) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onExitPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, uint256[] memory scalingFactors, bytes memory userData ) internal virtual returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ); // Internal functions /** * @dev Adds swap fee amount to `amount`, returning a higher value. */ function _addSwapFeeAmount(uint256 amount) internal view returns (uint256) { // This returns amount + fee amount, so we round up (favoring a higher fee amount). return amount.divUp(FixedPoint.ONE.sub(getSwapFeePercentage())); } /** * @dev Subtracts swap fee amount from `amount`, returning a lower value. */ function _subtractSwapFeeAmount(uint256 amount) internal view returns (uint256) { // This returns amount - fee amount, so we round up (favoring a higher fee amount). uint256 feeAmount = amount.mulUp(getSwapFeePercentage()); return amount.sub(feeAmount); } // Scaling /** * @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if * it had 18 decimals. */ function _computeScalingFactor(IERC20 token) internal view returns (uint256) { if (address(token) == address(this)) { return FixedPoint.ONE; } // Tokens that don't implement the `decimals` method are not supported. uint256 tokenDecimals = ERC20(address(token)).decimals(); // Tokens with more than 18 decimals are not supported. uint256 decimalsDifference = Math.sub(18, tokenDecimals); return FixedPoint.ONE * 10**decimalsDifference; } /** * @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the * Pool. * * All scaling factors are fixed-point values with 18 decimals, to allow for this function to be overridden by * derived contracts that need to apply further scaling, making these factors potentially non-integer. * * The largest 'base' scaling factor (i.e. in tokens with less than 18 decimals) is 10**18, which in fixed-point is * 10**36. This value can be multiplied with a 112 bit Vault balance with no overflow by a factor of ~1e7, making * even relatively 'large' factors safe to use. * * The 1e7 figure is the result of 2**256 / (1e18 * 1e18 * 2**112). */ function _scalingFactor(IERC20 token) internal view virtual returns (uint256); /** * @dev Same as `_scalingFactor()`, except for all registered tokens (in the same order as registered). The Vault * will always pass balances in this order when calling any of the Pool hooks. */ function _scalingFactors() internal view virtual returns (uint256[] memory); function getScalingFactors() external view returns (uint256[] memory) { return _scalingFactors(); } /** * @dev Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it needed * scaling or not. */ function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { // Upscale rounding wouldn't necessarily always go in the same direction: in a swap for example the balance of // token in should be rounded up, and that of token out rounded down. This is the only place where we round in // the same direction for all amounts, as the impact of this rounding is expected to be minimal (and there's no // rounding error unless `_scalingFactor()` is overriden). return FixedPoint.mulDown(amount, scalingFactor); } /** * @dev Same as `_upscale`, but for an entire array. This function does not return anything, but instead *mutates* * the `amounts` array. */ function _upscaleArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = FixedPoint.mulDown(amounts[i], scalingFactors[i]); } } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded down. */ function _downscaleDown(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return FixedPoint.divDown(amount, scalingFactor); } /** * @dev Same as `_downscaleDown`, but for an entire array. This function does not return anything, but instead * *mutates* the `amounts` array. */ function _downscaleDownArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = FixedPoint.divDown(amounts[i], scalingFactors[i]); } } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded up. */ function _downscaleUp(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return FixedPoint.divUp(amount, scalingFactor); } /** * @dev Same as `_downscaleUp`, but for an entire array. This function does not return anything, but instead * *mutates* the `amounts` array. */ function _downscaleUpArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = FixedPoint.divUp(amounts[i], scalingFactors[i]); } } function _getAuthorizer() internal view override returns (IAuthorizer) { // Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which // accounts can call permissioned functions: for example, to perform emergency pauses. // If the owner is delegated, then *all* permissioned functions, including `setSwapFeePercentage`, will be under // Governance control. return getVault().getAuthorizer(); } function _queryAction( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData, function(bytes32, address, address, uint256[] memory, uint256, uint256, uint256[] memory, bytes memory) internal returns (uint256, uint256[] memory, uint256[] memory) _action, function(uint256[] memory, uint256[] memory) internal view _downscaleArray ) private { // This uses the same technique used by the Vault in queryBatchSwap. Refer to that function for a detailed // explanation. if (msg.sender != address(this)) { // We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of // the preceding if statement will be executed instead. // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(msg.data); // solhint-disable-next-line no-inline-assembly assembly { // This call should always revert to decode the bpt and token amounts from the revert reason switch success case 0 { // Note we are manually writing the memory slot 0. We can safely overwrite whatever is // stored there as we take full control of the execution and then immediately return. // We copy the first 4 bytes to check if it matches with the expected signature, otherwise // there was another revert reason and we should forward it. returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) // If the first 4 bytes don't match with the expected signature, we forward the revert reason. if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } // The returndata contains the signature, followed by the raw memory representation of the // `bptAmount` and `tokenAmounts` (array: length + data). We need to return an ABI-encoded // representation of these. // An ABI-encoded response will include one additional field to indicate the starting offset of // the `tokenAmounts` array. The `bptAmount` will be laid out in the first word of the // returndata. // // In returndata: // [ signature ][ bptAmount ][ tokenAmounts length ][ tokenAmounts values ] // [ 4 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // // We now need to return (ABI-encoded values): // [ bptAmount ][ tokeAmounts offset ][ tokenAmounts length ][ tokenAmounts values ] // [ 32 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // We copy 32 bytes for the `bptAmount` from returndata into memory. // Note that we skip the first 4 bytes for the error signature returndatacopy(0, 0x04, 32) // The offsets are 32-bytes long, so the array of `tokenAmounts` will start after // the initial 64 bytes. mstore(0x20, 64) // We now copy the raw memory array for the `tokenAmounts` from returndata into memory. // Since bpt amount and offset take up 64 bytes, we start copying at address 0x40. We also // skip the first 36 bytes from returndata, which correspond to the signature plus bpt amount. returndatacopy(0x40, 0x24, sub(returndatasize(), 36)) // We finally return the ABI-encoded uint256 and the array, which has a total length equal to // the size of returndata, plus the 32 bytes of the offset but without the 4 bytes of the // error signature. return(0, add(returndatasize(), 28)) } default { // This call should always revert, but we fail nonetheless if that didn't happen invalid() } } } else { uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, scalingFactors, userData ); _downscaleArray(tokenAmounts, scalingFactors); // solhint-disable-next-line no-inline-assembly assembly { // We will return a raw representation of `bptAmount` and `tokenAmounts` in memory, which is composed of // a 32-byte uint256, followed by a 32-byte for the array length, and finally the 32-byte uint256 values // Because revert expects a size in bytes, we multiply the array length (stored at `tokenAmounts`) by 32 let size := mul(mload(tokenAmounts), 32) // We store the `bptAmount` in the previous slot to the `tokenAmounts` array. We can make sure there // will be at least one available slot due to how the memory scratch space works. // We can safely overwrite whatever is stored in this slot as we will revert immediately after that. let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount) // We send one extra value for the error signature "QueryError(uint256,uint256[])" which is 0x43adbafb // We use the previous slot to `bptAmount`. mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb) start := sub(start, 0x04) // When copying from `tokenAmounts` into returndata, we copy the additional 68 bytes to also return // the `bptAmount`, the array 's length, and the error signature. revert(start, add(size, 68)) } } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IBasePool.sol"; /** * @dev IPools with the General specialization setting should implement this interface. * * This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool. * Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will * grant to the pool in a 'given out' swap. * * This can often be implemented by a `view` function, since many pricing algorithms don't need to track state * changes in swaps. However, contracts implementing this in non-view functions should check that the caller is * indeed the Vault. */ interface IGeneralPool is IBasePool { function onSwap( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) external returns (uint256 amount); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./ITemporarilyPausable.sol"; /** * @dev Allows for a contract to be paused during an initial period after deployment, disabling functionality. Can be * used as an emergency switch in case a security vulnerability or threat is identified. * * The contract can only be paused during the Pause Window, a period that starts at deployment. It can also be * unpaused and repaused any number of times during this period. This is intended to serve as a safety measure: it lets * system managers react quickly to potentially dangerous situations, knowing that this action is reversible if careful * analysis later determines there was a false alarm. * * If the contract is paused when the Pause Window finishes, it will remain in the paused state through an additional * Buffer Period, after which it will be automatically unpaused forever. This is to ensure there is always enough time * to react to an emergency, even if the threat is discovered shortly before the Pause Window expires. * * Note that since the contract can only be paused within the Pause Window, unpausing during the Buffer Period is * irreversible. */ abstract contract TemporarilyPausable is ITemporarilyPausable { // The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy. // solhint-disable not-rely-on-time uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days; uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days; uint256 private immutable _pauseWindowEndTime; uint256 private immutable _bufferPeriodEndTime; bool private _paused; constructor(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) { _require(pauseWindowDuration <= _MAX_PAUSE_WINDOW_DURATION, Errors.MAX_PAUSE_WINDOW_DURATION); _require(bufferPeriodDuration <= _MAX_BUFFER_PERIOD_DURATION, Errors.MAX_BUFFER_PERIOD_DURATION); uint256 pauseWindowEndTime = block.timestamp + pauseWindowDuration; _pauseWindowEndTime = pauseWindowEndTime; _bufferPeriodEndTime = pauseWindowEndTime + bufferPeriodDuration; } /** * @dev Reverts if the contract is paused. */ modifier whenNotPaused() { _ensureNotPaused(); _; } /** * @dev Returns the current contract pause status, as well as the end times of the Pause Window and Buffer * Period. */ function getPausedState() external view override returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ) { paused = !_isNotPaused(); pauseWindowEndTime = _getPauseWindowEndTime(); bufferPeriodEndTime = _getBufferPeriodEndTime(); } /** * @dev Sets the pause state to `paused`. The contract can only be paused until the end of the Pause Window, and * unpaused until the end of the Buffer Period. * * Once the Buffer Period expires, this function reverts unconditionally. */ function _setPaused(bool paused) internal { if (paused) { _require(block.timestamp < _getPauseWindowEndTime(), Errors.PAUSE_WINDOW_EXPIRED); } else { _require(block.timestamp < _getBufferPeriodEndTime(), Errors.BUFFER_PERIOD_EXPIRED); } _paused = paused; emit PausedStateChanged(paused); } /** * @dev Reverts if the contract is paused. */ function _ensureNotPaused() internal view { _require(_isNotPaused(), Errors.PAUSED); } /** * @dev Reverts if the contract is not paused. */ function _ensurePaused() internal view { _require(!_isNotPaused(), Errors.NOT_PAUSED); } /** * @dev Returns true if the contract is unpaused. * * Once the Buffer Period expires, the gas cost of calling this function is reduced dramatically, as storage is no * longer accessed. */ function _isNotPaused() internal view returns (bool) { // After the Buffer Period, the (inexpensive) timestamp check short-circuits the storage access. return block.timestamp > _getBufferPeriodEndTime() || !_paused; } // These getters lead to reduced bytecode size by inlining the immutable variables in a single place. function _getPauseWindowEndTime() private view returns (uint256) { return _pauseWindowEndTime; } function _getBufferPeriodEndTime() private view returns (uint256) { return _bufferPeriodEndTime; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; import "./IERC20.sol"; import "./SafeMath.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 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_) { _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(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); _approve( sender, msg.sender, _allowances[sender][msg.sender].sub(amount, Errors.ERC20_TRANSFER_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(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, Errors.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), Errors.ERC20_TRANSFER_FROM_ZERO_ADDRESS); _require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, Errors.ERC20_TRANSFER_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 { _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), Errors.ERC20_BURN_FROM_ZERO_ADDRESS); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, Errors.ERC20_BURN_EXCEEDS_ALLOWANCE); _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 { _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: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ISignaturesValidator.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ITemporarilyPausable.sol"; import "@balancer-labs/v2-solidity-utils/contracts/misc/IWETH.sol"; import "./IAsset.sol"; import "./IAuthorizer.sol"; import "./IFlashLoanRecipient.sol"; import "./IProtocolFeesCollector.sol"; pragma solidity ^0.7.0; /** * @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that * don't override one of these declarations. */ interface IVault is ISignaturesValidator, ITemporarilyPausable { // Generalities about the Vault: // // - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are // transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling // `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by // calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning // a boolean value: in these scenarios, a non-reverting call is assumed to be successful. // // - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g. // while execution control is transferred to a token contract during a swap) will result in a revert. View // functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results. // Contracts calling view functions in the Vault must make sure the Vault has not already been entered. // // - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools. // Authorizer // // Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists // outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller // can perform a given action. /** * @dev Returns the Vault's Authorizer. */ function getAuthorizer() external view returns (IAuthorizer); /** * @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this. * * Emits an `AuthorizerChanged` event. */ function setAuthorizer(IAuthorizer newAuthorizer) external; /** * @dev Emitted when a new authorizer is set by `setAuthorizer`. */ event AuthorizerChanged(IAuthorizer indexed newAuthorizer); // Relayers // // Additionally, it is possible for an account to perform certain actions on behalf of another one, using their // Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions, // and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield // this power, two things must occur: // - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This // means that Balancer governance must approve each individual contract to act as a relayer for the intended // functions. // - Each user must approve the relayer to act on their behalf. // This double protection means users cannot be tricked into approving malicious relayers (because they will not // have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised // Authorizer or governance drain user funds, since they would also need to be approved by each individual user. /** * @dev Returns true if `user` has approved `relayer` to act as a relayer for them. */ function hasApprovedRelayer(address user, address relayer) external view returns (bool); /** * @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise. * * Emits a `RelayerApprovalChanged` event. */ function setRelayerApproval( address sender, address relayer, bool approved ) external; /** * @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`. */ event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved); // Internal Balance // // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users. // // Internal Balance management features batching, which means a single contract call can be used to perform multiple // operations of different kinds, with different senders and recipients, at once. /** * @dev Returns `user`'s Internal Balance for a set of tokens. */ function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory); /** * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer) * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as * it lets integrators reuse a user's Vault allowance. * * For each operation, if the caller is not `sender`, it must be an authorized relayer for them. */ function manageUserBalance(UserBalanceOp[] memory ops) external payable; /** * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received without manual WETH wrapping or unwrapping. */ struct UserBalanceOp { UserBalanceOpKind kind; IAsset asset; uint256 amount; address sender; address payable recipient; } // There are four possible operations in `manageUserBalance`: // // - DEPOSIT_INTERNAL // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`. // // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is // relevant for relayers). // // Emits an `InternalBalanceChanged` event. // // // - WITHDRAW_INTERNAL // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`. // // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send // it to the recipient as ETH. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_INTERNAL // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`. // // Reverts if the ETH sentinel value is passed. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_EXTERNAL // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by // relayers, as it lets them reuse a user's Vault allowance. // // Reverts if the ETH sentinel value is passed. // // Emits an `ExternalBalanceTransfer` event. enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL } /** * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through * interacting with Pools using Internal Balance. * * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH * address. */ event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta); /** * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account. */ event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount); // Pools // // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced // functionality: // // - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads), // which increase with the number of registered tokens. // // - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are // independent of the number of registered tokens. // // - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like // minimal swap info Pools, these are called via IMinimalSwapInfoPool. enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN } /** * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be * changed. * * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`, * depending on the chosen specialization setting. This contract is known as the Pool's contract. * * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words, * multiple Pools may share the same contract. * * Emits a `PoolRegistered` event. */ function registerPool(PoolSpecialization specialization) external returns (bytes32); /** * @dev Emitted when a Pool is registered by calling `registerPool`. */ event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization); /** * @dev Returns a Pool's contract address and specialization setting. */ function getPool(bytes32 poolId) external view returns (address, PoolSpecialization); /** * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens, * exit by receiving registered tokens, and can only swap registered tokens. * * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in * ascending order. * * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`, * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore * expected to be highly secured smart contracts with sound design principles, and the decision to register an * Asset Manager should not be made lightly. * * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a * different Asset Manager. * * Emits a `TokensRegistered` event. */ function registerTokens( bytes32 poolId, IERC20[] memory tokens, address[] memory assetManagers ) external; /** * @dev Emitted when a Pool registers tokens by calling `registerTokens`. */ event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers); /** * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens * must be deregistered in the same `deregisterTokens` call. * * A deregistered token can be re-registered later on, possibly with a different Asset Manager. * * Emits a `TokensDeregistered` event. */ function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external; /** * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`. */ event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens); /** * @dev Returns detailed information for a Pool's registered token. * * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token` * equals the sum of `cash` and `managed`. * * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`, * `managed` or `total` balance to be greater than 2^112 - 1. * * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a * change for this purpose, and will update `lastChangeBlock`. * * `assetManager` is the Pool's token Asset Manager. */ function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager ); /** * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of * the tokens' `balances` changed. * * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order. * * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same * order as passed to `registerTokens`. * * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo` * instead. */ function getPoolTokens(bytes32 poolId) external view returns ( IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ); /** * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized * Pool shares. * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces * these maximums. * * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent * back to the caller (not the sender, which is important for relayers). * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final * `assets` array might not be sorted. Pools with no registered tokens cannot be joined. * * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be * withdrawn from Internal Balance: attempting to do so will trigger a revert. * * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed * directly to the Pool's contract, as is `recipient`. * * Emits a `PoolBalanceChanged` event. */ function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; struct JoinPoolRequest { IAsset[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } /** * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see * `getPoolTokenInfo`). * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault: * it just enforces these minimums. * * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit. * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited. * * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise, * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to * do so will trigger a revert. * * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the * `tokens` array. This array must match the Pool's registered tokens. * * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and * passed directly to the Pool's contract. * * Emits a `PoolBalanceChanged` event. */ function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; struct ExitPoolRequest { IAsset[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } /** * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively. */ event PoolBalanceChanged( bytes32 indexed poolId, address indexed liquidityProvider, IERC20[] tokens, int256[] deltas, uint256[] protocolFeeAmounts ); enum PoolBalanceChangeKind { JOIN, EXIT } // Swaps // // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this, // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote. // // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence. // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'), // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out'). // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together // individual swaps. // // There are two swap kinds: // - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the // `onSwap` hook) the amount of tokens out (to send to the recipient). // - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines // (via the `onSwap` hook) the amount of tokens in (to receive from the sender). // // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at // the final intended token. // // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost // much less gas than they would otherwise. // // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only // updating the Pool's internal accounting). // // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the // minimum amount of tokens to receive (by passing a negative value) is specified. // // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after // this point in time (e.g. if the transaction failed to be included in a block promptly). // // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers). // // Finally, Internal Balance can be used when either sending or receiving tokens. enum SwapKind { GIVEN_IN, GIVEN_OUT } /** * @dev Performs a swap with a single Pool. * * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens * taken from the Pool, which must be greater than or equal to `limit`. * * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens * sent to the Pool, which must be less than or equal to `limit`. * * Internal Balance usage and the recipient are determined by the `funds` struct. * * Emits a `Swap` event. */ function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); /** * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on * the `kind` value. * * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address). * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct SingleSwap { bytes32 poolId; SwapKind kind; IAsset assetIn; IAsset assetOut; uint256 amount; bytes userData; } /** * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either * the amount of tokens sent to or received from the Pool, depending on the `kind` value. * * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at * the same index in the `assets` array. * * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or * `amountOut` depending on the swap kind. * * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`. * * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses, * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to * or unwrapped from WETH by the Vault. * * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies * the minimum or maximum amount of each token the vault is allowed to transfer. * * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the * equivalent `swap` call. * * Emits `Swap` events. */ function batchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, int256[] memory limits, uint256 deadline ) external payable returns (int256[] memory); /** * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the * `assets` array passed to that function, and ETH assets are converted to WETH. * * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out * from the previous swap, depending on the swap kind. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct BatchSwapStep { bytes32 poolId; uint256 assetInIndex; uint256 assetOutIndex; uint256 amount; bytes userData; } /** * @dev Emitted for each individual swap performed by `swap` or `batchSwap`. */ event Swap( bytes32 indexed poolId, IERC20 indexed tokenIn, IERC20 indexed tokenOut, uint256 amountIn, uint256 amountOut ); /** * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the * `recipient` account. * * If the caller is not `sender`, it must be an authorized relayer for them. * * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20 * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender` * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of * `joinPool`. * * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of * transferred. This matches the behavior of `exitPool`. * * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a * revert. */ struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } /** * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result. * * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH) * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it * receives are the same that an equivalent `batchSwap` call would receive. * * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct. * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens, * approve them for the Vault, or even know a user's address. * * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute * eth_call instead of eth_sendTransaction. */ function queryBatchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds ) external returns (int256[] memory assetDeltas); // Flash Loans /** * @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it, * and then reverting unless the tokens plus a proportional protocol fee have been returned. * * The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount * for each token contract. `tokens` must be sorted in ascending order. * * The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the * `receiveFlashLoan` call. * * Emits `FlashLoan` events. */ function flashLoan( IFlashLoanRecipient recipient, IERC20[] memory tokens, uint256[] memory amounts, bytes memory userData ) external; /** * @dev Emitted for each individual flash loan performed by `flashLoan`. */ event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount); // Asset Management // // Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's // tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see // `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly // controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the // prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore // not constrained to the tokens they are managing, but extends to the entire Pool's holdings. // // However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit, // for example by lending unused tokens out for interest, or using them to participate in voting protocols. // // This concept is unrelated to the IAsset interface. /** * @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates. * * Pool Balance management features batching, which means a single contract call can be used to perform multiple * operations of different kinds, with different Pools and tokens, at once. * * For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`. */ function managePoolBalance(PoolBalanceOp[] memory ops) external; struct PoolBalanceOp { PoolBalanceOpKind kind; bytes32 poolId; IERC20 token; uint256 amount; } /** * Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged. * * Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged. * * Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total. * The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss). */ enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE } /** * @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`. */ event PoolBalanceManaged( bytes32 indexed poolId, address indexed assetManager, IERC20 indexed token, int256 cashDelta, int256 managedDelta ); // Protocol Fees // // Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by // permissioned accounts. // // There are two kinds of protocol fees: // // - flash loan fees: charged on all flash loans, as a percentage of the amounts lent. // // - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including // swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather, // Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the // Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as // exiting a Pool in debt without first paying their share. /** * @dev Returns the current protocol fee module. */ function getProtocolFeesCollector() external view returns (IProtocolFeesCollector); /** * @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an * error in some part of the system. * * The Vault can only be paused during an initial time period, after which pausing is forever disabled. * * While the contract is paused, the following features are disabled: * - depositing and transferring internal balance * - transferring external balance (using the Vault's allowance) * - swaps * - joining Pools * - Asset Manager interactions * * Internal Balance can still be withdrawn, and Pools exited. */ function setPaused(bool paused) external; /** * @dev Returns the Vault's WETH instance. */ function WETH() external view returns (IWETH); // solhint-disable-previous-line func-name-mixedcase } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IVault.sol"; import "./IPoolSwapStructs.sol"; /** * @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not * the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from * either IGeneralPool or IMinimalSwapInfoPool */ interface IBasePool is IPoolSwapStructs { /** * @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of * each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault. * The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect * the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`. * * Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join. * * `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account * designated to receive any benefits (typically pool shares). `balances` contains the total balances * for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as minting pool shares. */ function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts); /** * @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many * tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes * to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`, * as well as collect the reported amount in protocol fees, which the Pool should calculate based on * `protocolSwapFeePercentage`. * * Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share. * * `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account * to which the Vault will send the proceeds. `balances` contains the total token balances for each token * the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as burning pool shares. */ function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts); function getPoolId() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; interface IAssetManager { /** * @notice Emitted when asset manager is rebalanced */ event Rebalance(bytes32 poolId); /** * @notice Sets the config */ function setConfig(bytes32 poolId, bytes calldata config) external; /** * Note: No function to read the asset manager config is included in IAssetManager * as the signature is expected to vary between asset manager implementations */ /** * @notice Returns the asset manager's token */ function getToken() external view returns (IERC20); /** * @return the current assets under management of this asset manager */ function getAUM(bytes32 poolId) external view returns (uint256); /** * @return poolCash - The up-to-date cash balance of the pool * @return poolManaged - The up-to-date managed balance of the pool */ function getPoolBalances(bytes32 poolId) external view returns (uint256 poolCash, uint256 poolManaged); /** * @return The difference in tokens between the target investment * and the currently invested amount (i.e. the amount that can be invested) */ function maxInvestableBalance(bytes32 poolId) external view returns (int256); /** * @notice Updates the Vault on the value of the pool's investment returns */ function updateBalanceOfPool(bytes32 poolId) external; /** * @notice Determines whether the pool should rebalance given the provided balances */ function shouldRebalance(uint256 cash, uint256 managed) external view returns (bool); /** * @notice Rebalances funds between the pool and the asset manager to maintain target investment percentage. * @param poolId - the poolId of the pool to be rebalanced * @param force - a boolean representing whether a rebalance should be forced even when the pool is near balance */ function rebalance(bytes32 poolId, bool force) external; /** * @notice allows an authorized rebalancer to remove capital to facilitate large withdrawals * @param poolId - the poolId of the pool to withdraw funds back to * @param amount - the amount of tokens to withdraw back to the pool */ function capitalOut(bytes32 poolId, uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20Permit.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; /** * @title Highly opinionated token implementation * @author Balancer Labs * @dev * - Includes functions to increase and decrease allowance as a workaround * for the well-known issue with `approve`: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * - Allows for 'infinite allowance', where an allowance of 0xff..ff is not * decreased by calls to transferFrom * - Lets a token holder use `transferFrom` to send their own tokens, * without first setting allowance * - Emits 'Approval' events whenever allowance is changed by `transferFrom` * - Assigns infinite allowance for all token holders to the Vault */ contract BalancerPoolToken is ERC20Permit { IVault private immutable _vault; constructor( string memory tokenName, string memory tokenSymbol, IVault vault ) ERC20(tokenName, tokenSymbol) ERC20Permit(tokenName) { _vault = vault; } function getVault() public view returns (IVault) { return _vault; } // Overrides /** * @dev Override to grant the Vault infinite allowance, causing for Pool Tokens to not require approval. * * This is sound as the Vault already provides authorization mechanisms when initiation token transfers, which this * contract inherits. */ function allowance(address owner, address spender) public view override returns (uint256) { if (spender == address(getVault())) { return uint256(-1); } else { return super.allowance(owner, spender); } } /** * @dev Override to allow for 'infinite allowance' and let the token owner use `transferFrom` with no self-allowance */ function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { uint256 currentAllowance = allowance(sender, msg.sender); _require(msg.sender == sender || currentAllowance >= amount, Errors.ERC20_TRANSFER_EXCEEDS_ALLOWANCE); _transfer(sender, recipient, amount); if (msg.sender != sender && currentAllowance != uint256(-1)) { // Because of the previous require, we know that if msg.sender != sender then currentAllowance >= amount _approve(sender, msg.sender, currentAllowance - amount); } return true; } /** * @dev Override to allow decreasing allowance by more than the current amount (setting it to zero) */ function decreaseAllowance(address spender, uint256 amount) public override returns (bool) { uint256 currentAllowance = allowance(msg.sender, spender); if (amount >= currentAllowance) { _approve(msg.sender, spender, 0); } else { // No risk of underflow due to if condition _approve(msg.sender, spender, currentAllowance - amount); } return true; } // Internal functions function _mintPoolTokens(address recipient, uint256 amount) internal { _mint(recipient, amount); } function _burnPoolTokens(address sender, uint256 amount) internal { _burn(sender, amount); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/helpers/Authentication.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IAuthorizer.sol"; import "./BasePool.sol"; /** * @dev Base authorization layer implementation for Pools. * * The owner account can call some of the permissioned functions - access control of the rest is delegated to the * Authorizer. Note that this owner is immutable: more sophisticated permission schemes, such as multiple ownership, * granular roles, etc., could be built on top of this by making the owner a smart contract. * * Access control of all other permissioned functions is delegated to an Authorizer. It is also possible to delegate * control of *all* permissioned functions to the Authorizer by setting the owner address to `_DELEGATE_OWNER`. */ abstract contract BasePoolAuthorization is Authentication { address private immutable _owner; address private constant _DELEGATE_OWNER = 0xBA1BA1ba1BA1bA1bA1Ba1BA1ba1BA1bA1ba1ba1B; constructor(address owner) { _owner = owner; } function getOwner() public view returns (address) { return _owner; } function getAuthorizer() external view returns (IAuthorizer) { return _getAuthorizer(); } function _canPerform(bytes32 actionId, address account) internal view override returns (bool) { if ((getOwner() != _DELEGATE_OWNER) && _isOwnerOnlyAction(actionId)) { // Only the owner can perform "owner only" actions, unless the owner is delegated. return msg.sender == getOwner(); } else { // Non-owner actions are always processed via the Authorizer, as "owner only" ones are when delegated. return _getAuthorizer().canPerform(actionId, account, address(this)); } } function _isOwnerOnlyAction(bytes32 actionId) internal view virtual returns (bool); function _getAuthorizer() internal view virtual returns (IAuthorizer); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the TemporarilyPausable helper. */ interface ITemporarilyPausable { /** * @dev Emitted every time the pause state changes by `_setPaused`. */ event PausedStateChanged(bool paused); /** * @dev Returns the current paused state. */ function getPausedState() external view returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.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, Errors.ADD_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, Errors.SUB_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, uint256 errorCode) internal pure returns (uint256) { _require(b <= a, errorCode); uint256 c = a - b; return c; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the SignatureValidator helper, used to support meta-transactions. */ interface ISignaturesValidator { /** * @dev Returns the EIP712 domain separator. */ function getDomainSeparator() external view returns (bytes32); /** * @dev Returns the next nonce used by an address to sign messages. */ function getNextNonce(address user) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../openzeppelin/IERC20.sol"; /** * @dev Interface for WETH9. * See https://github.com/gnosis/canonical-weth/blob/0dd1ea3e295eef916d0c6223ec63141137d22d67/contracts/WETH9.sol */ interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like * types. * * This concept is unrelated to a Pool's Asset Managers. */ interface IAsset { // solhint-disable-previous-line no-empty-blocks } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthorizer { /** * @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`. */ function canPerform( bytes32 actionId, address account, address where ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // Inspired by Aave Protocol's IFlashLoanReceiver. import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; interface IFlashLoanRecipient { /** * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient. * * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the * Vault, or else the entire flash loan will revert. * * `userData` is the same value passed in the `IVault.flashLoan` call. */ function receiveFlashLoan( IERC20[] memory tokens, uint256[] memory amounts, uint256[] memory feeAmounts, bytes memory userData ) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./IVault.sol"; import "./IAuthorizer.sol"; interface IProtocolFeesCollector { event SwapFeePercentageChanged(uint256 newSwapFeePercentage); event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage); function withdrawCollectedFees( IERC20[] calldata tokens, uint256[] calldata amounts, address recipient ) external; function setSwapFeePercentage(uint256 newSwapFeePercentage) external; function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external; function getSwapFeePercentage() external view returns (uint256); function getFlashLoanFeePercentage() external view returns (uint256); function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts); function getAuthorizer() external view returns (IAuthorizer); function vault() external view returns (IVault); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./IVault.sol"; interface IPoolSwapStructs { // This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and // IMinimalSwapInfoPool. // // This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or // 'given out') which indicates whether or not the amount sent by the pool is known. // // The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take // in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`. // // All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in // some Pools. // // `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than // one Pool. // // The meaning of `lastChangeBlock` depends on the Pool specialization: // - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total // balance. // - General: the last block in which *any* of the Pool's registered tokens changed its total balance. // // `from` is the origin address for the funds the Pool receives, and `to` is the destination address // where the Pool sends the outgoing tokens. // // `userData` is extra data provided by the caller - typically a signature from a trusted party. struct SwapRequest { IVault.SwapKind kind; IERC20 tokenIn; IERC20 tokenOut; uint256 amount; // Misc data bytes32 poolId; uint256 lastChangeBlock; address from; address to; bytes userData; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./ERC20.sol"; import "./IERC20Permit.sol"; import "./EIP712.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { mapping(address => uint256) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { // solhint-disable-next-line not-rely-on-time _require(block.timestamp <= deadline, Errors.EXPIRED_PERMIT); uint256 nonce = _nonces[owner]; bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, nonce, deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ecrecover(hash, v, r, s); _require((signer != address(0)) && (signer == owner), Errors.INVALID_SIGNATURE); _nonces[owner] = nonce + 1; _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view override returns (uint256) { return _nonces[owner]; } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { _HASHED_NAME = keccak256(bytes(name)); _HASHED_VERSION = keccak256(bytes(version)); _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view virtual returns (bytes32) { return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { // Silence state mutability warning without generating bytecode. // See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and // https://github.com/ethereum/solidity/issues/2691 this; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./IAuthentication.sol"; /** * @dev Building block for performing access control on external functions. * * This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied * to external functions to only make them callable by authorized accounts. * * Derived contracts must implement the `_canPerform` function, which holds the actual access control logic. */ abstract contract Authentication is IAuthentication { bytes32 private immutable _actionIdDisambiguator; /** * @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in * multi contract systems. * * There are two main uses for it: * - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers * unique. The contract's own address is a good option. * - if the contract belongs to a family that shares action identifiers for the same functions, an identifier * shared by the entire family (and no other contract) should be used instead. */ constructor(bytes32 actionIdDisambiguator) { _actionIdDisambiguator = actionIdDisambiguator; } /** * @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions. */ modifier authenticate() { _authenticateCaller(); _; } /** * @dev Reverts unless the caller is allowed to call the entry point function. */ function _authenticateCaller() internal view { bytes32 actionId = getActionId(msg.sig); _require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED); } function getActionId(bytes4 selector) public view override returns (bytes32) { // Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the // function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of // multiple contracts. return keccak256(abi.encodePacked(_actionIdDisambiguator, selector)); } function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthentication { /** * @dev Returns the action identifier associated with the external function described by `selector`. */ function getActionId(bytes4 selector) external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IBasePool.sol"; /** * @dev Pool contracts with the MinimalSwapInfo or TwoToken specialization settings should implement this interface. * * This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool. * Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will grant * to the pool in a 'given out' swap. * * This can often be implemented by a `view` function, since many pricing algorithms don't need to track state * changes in swaps. However, contracts implementing this in non-view functions should check that the caller is * indeed the Vault. */ interface IMinimalSwapInfoPool is IBasePool { function onSwap( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) external returns (uint256 amount); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "@balancer-labs/v2-pool-utils/contracts/factories/BasePoolFactory.sol"; import "@balancer-labs/v2-pool-utils/contracts/factories/BasePoolSplitCodeFactory.sol"; import "@balancer-labs/v2-pool-utils/contracts/factories/FactoryWidePauseWindow.sol"; import "./StablePhantomPool.sol"; contract StablePhantomPoolFactory is BasePoolSplitCodeFactory, FactoryWidePauseWindow { constructor(IVault vault) BasePoolSplitCodeFactory(vault, type(StablePhantomPool).creationCode) { // solhint-disable-previous-line no-empty-blocks } /** * @dev Deploys a new `StablePhantomPool`. */ function create( string memory name, string memory symbol, IERC20[] memory tokens, uint256 amplificationParameter, IRateProvider[] memory rateProviders, uint256[] memory tokenRateCacheDurations, uint256 swapFeePercentage, address owner ) external returns (StablePhantomPool) { (uint256 pauseWindowDuration, uint256 bufferPeriodDuration) = getPauseConfiguration(); return StablePhantomPool( _create( abi.encode( StablePhantomPool.NewPoolParams({ vault: getVault(), name: name, symbol: symbol, tokens: tokens, rateProviders: rateProviders, tokenRateCacheDurations: tokenRateCacheDurations, amplificationParameter: amplificationParameter, swapFeePercentage: swapFeePercentage, pauseWindowDuration: pauseWindowDuration, bufferPeriodDuration: bufferPeriodDuration, owner: owner }) ) ) ); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; /** * @dev Base contract for Pool factories. * * Pools are deployed from factories to allow third parties to reason about them. Unknown Pools may have arbitrary * logic: being able to assert that a Pool's behavior follows certain rules (those imposed by the contracts created by * the factory) is very powerful. */ abstract contract BasePoolFactory { IVault private immutable _vault; mapping(address => bool) private _isPoolFromFactory; event PoolCreated(address indexed pool); constructor(IVault vault) { _vault = vault; } /** * @dev Returns the Vault's address. */ function getVault() public view returns (IVault) { return _vault; } /** * @dev Returns true if `pool` was created by this factory. */ function isPoolFromFactory(address pool) external view returns (bool) { return _isPoolFromFactory[pool]; } /** * @dev Registers a new created pool. * * Emits a `PoolCreated` event. */ function _register(address pool) internal { _isPoolFromFactory[pool] = true; emit PoolCreated(pool); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/helpers/BaseSplitCodeFactory.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; /** * @dev Same as `BasePoolFactory`, for Pools whose creation code is so large that the factory cannot hold it. */ abstract contract BasePoolSplitCodeFactory is BaseSplitCodeFactory { IVault private immutable _vault; mapping(address => bool) private _isPoolFromFactory; event PoolCreated(address indexed pool); constructor(IVault vault, bytes memory creationCode) BaseSplitCodeFactory(creationCode) { _vault = vault; } /** * @dev Returns the Vault's address. */ function getVault() public view returns (IVault) { return _vault; } /** * @dev Returns true if `pool` was created by this factory. */ function isPoolFromFactory(address pool) external view returns (bool) { return _isPoolFromFactory[pool]; } function _create(bytes memory constructorArgs) internal override returns (address) { address pool = super._create(constructorArgs); _isPoolFromFactory[pool] = true; emit PoolCreated(pool); return pool; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** * @dev Utility to create Pool factories for Pools that use the `TemporarilyPausable` contract. * * By calling `TemporarilyPausable`'s constructor with the result of `getPauseConfiguration`, all Pools created by this * factory will share the same Pause Window end time, after which both old and new Pools will not be pausable. */ contract FactoryWidePauseWindow { // This contract relies on timestamps in a similar way as `TemporarilyPausable` does - the same caveats apply. // solhint-disable not-rely-on-time uint256 private constant _INITIAL_PAUSE_WINDOW_DURATION = 90 days; uint256 private constant _BUFFER_PERIOD_DURATION = 30 days; // Time when the pause window for all created Pools expires, and the pause window duration of new Pools becomes // zero. uint256 private immutable _poolsPauseWindowEndTime; constructor() { _poolsPauseWindowEndTime = block.timestamp + _INITIAL_PAUSE_WINDOW_DURATION; } /** * @dev Returns the current `TemporarilyPausable` configuration that will be applied to Pools created by this * factory. * * `pauseWindowDuration` will decrease over time until it reaches zero, at which point both it and * `bufferPeriodDuration` will be zero forever, meaning deployed Pools will not be pausable. */ function getPauseConfiguration() public view returns (uint256 pauseWindowDuration, uint256 bufferPeriodDuration) { uint256 currentTime = block.timestamp; if (currentTime < _poolsPauseWindowEndTime) { // The buffer period is always the same since its duration is related to how much time is needed to respond // to a potential emergency. The Pause Window duration however decreases as the end time approaches. pauseWindowDuration = _poolsPauseWindowEndTime - currentTime; // No need for checked arithmetic. bufferPeriodDuration = _BUFFER_PERIOD_DURATION; } else { // After the end time, newly created Pools have no Pause Window, nor Buffer Period (since they are not // pausable in the first place). pauseWindowDuration = 0; bufferPeriodDuration = 0; } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./BalancerErrors.sol"; import "./CodeDeployer.sol"; /** * @dev Base factory for contracts whose creation code is so large that the factory cannot hold it. This happens when * the contract's creation code grows close to 24kB. * * Note that this factory cannot help with contracts that have a *runtime* (deployed) bytecode larger than 24kB. */ abstract contract BaseSplitCodeFactory { // The contract's creation code is stored as code in two separate addresses, and retrieved via `extcodecopy`. This // means this factory supports contracts with creation code of up to 48kB. // We rely on inline-assembly to achieve this, both to make the entire operation highly gas efficient, and because // `extcodecopy` is not available in Solidity. // solhint-disable no-inline-assembly address private immutable _creationCodeContractA; uint256 private immutable _creationCodeSizeA; address private immutable _creationCodeContractB; uint256 private immutable _creationCodeSizeB; /** * @dev The creation code of a contract Foo can be obtained inside Solidity with `type(Foo).creationCode`. */ constructor(bytes memory creationCode) { uint256 creationCodeSize = creationCode.length; // We are going to deploy two contracts: one with approximately the first half of `creationCode`'s contents // (A), and another with the remaining half (B). // We store the lengths in both immutable and stack variables, since immutable variables cannot be read during // construction. uint256 creationCodeSizeA = creationCodeSize / 2; _creationCodeSizeA = creationCodeSizeA; uint256 creationCodeSizeB = creationCodeSize - creationCodeSizeA; _creationCodeSizeB = creationCodeSizeB; // To deploy the contracts, we're going to use `CodeDeployer.deploy()`, which expects a memory array with // the code to deploy. Note that we cannot simply create arrays for A and B's code by copying or moving // `creationCode`'s contents as they are expected to be very large (> 24kB), so we must operate in-place. // Memory: [ code length ] [ A.data ] [ B.data ] // Creating A's array is simple: we simply replace `creationCode`'s length with A's length. We'll later restore // the original length. bytes memory creationCodeA; assembly { creationCodeA := creationCode mstore(creationCodeA, creationCodeSizeA) } // Memory: [ A.length ] [ A.data ] [ B.data ] // ^ creationCodeA _creationCodeContractA = CodeDeployer.deploy(creationCodeA); // Creating B's array is a bit more involved: since we cannot move B's contents, we are going to create a 'new' // memory array starting at A's last 32 bytes, which will be replaced with B's length. We'll back-up this last // byte to later restore it. bytes memory creationCodeB; bytes32 lastByteA; assembly { // `creationCode` points to the array's length, not data, so by adding A's length to it we arrive at A's // last 32 bytes. creationCodeB := add(creationCode, creationCodeSizeA) lastByteA := mload(creationCodeB) mstore(creationCodeB, creationCodeSizeB) } // Memory: [ A.length ] [ A.data[ : -1] ] [ B.length ][ B.data ] // ^ creationCodeA ^ creationCodeB _creationCodeContractB = CodeDeployer.deploy(creationCodeB); // We now restore the original contents of `creationCode` by writing back the original length and A's last byte. assembly { mstore(creationCodeA, creationCodeSize) mstore(creationCodeB, lastByteA) } } /** * @dev Returns the two addresses where the creation code of the contract crated by this factory is stored. */ function getCreationCodeContracts() public view returns (address contractA, address contractB) { return (_creationCodeContractA, _creationCodeContractB); } /** * @dev Returns the creation code of the contract this factory creates. */ function getCreationCode() public view returns (bytes memory) { return _getCreationCodeWithArgs(""); } /** * @dev Returns the creation code that will result in a contract being deployed with `constructorArgs`. */ function _getCreationCodeWithArgs(bytes memory constructorArgs) private view returns (bytes memory code) { // This function exists because `abi.encode()` cannot be instructed to place its result at a specific address. // We need for the ABI-encoded constructor arguments to be located immediately after the creation code, but // cannot rely on `abi.encodePacked()` to perform concatenation as that would involve copying the creation code, // which would be prohibitively expensive. // Instead, we compute the creation code in a pre-allocated array that is large enough to hold *both* the // creation code and the constructor arguments, and then copy the ABI-encoded arguments (which should not be // overly long) right after the end of the creation code. // Immutable variables cannot be used in assembly, so we store them in the stack first. address creationCodeContractA = _creationCodeContractA; uint256 creationCodeSizeA = _creationCodeSizeA; address creationCodeContractB = _creationCodeContractB; uint256 creationCodeSizeB = _creationCodeSizeB; uint256 creationCodeSize = creationCodeSizeA + creationCodeSizeB; uint256 constructorArgsSize = constructorArgs.length; uint256 codeSize = creationCodeSize + constructorArgsSize; assembly { // First, we allocate memory for `code` by retrieving the free memory pointer and then moving it ahead of // `code` by the size of the creation code plus constructor arguments, and 32 bytes for the array length. code := mload(0x40) mstore(0x40, add(code, add(codeSize, 32))) // We now store the length of the code plus constructor arguments. mstore(code, codeSize) // Next, we concatenate the creation code stored in A and B. let dataStart := add(code, 32) extcodecopy(creationCodeContractA, dataStart, 0, creationCodeSizeA) extcodecopy(creationCodeContractB, add(dataStart, creationCodeSizeA), 0, creationCodeSizeB) } // Finally, we copy the constructorArgs to the end of the array. Unfortunately there is no way to avoid this // copy, as it is not possible to tell Solidity where to store the result of `abi.encode()`. uint256 constructorArgsDataPtr; uint256 constructorArgsCodeDataPtr; assembly { constructorArgsDataPtr := add(constructorArgs, 32) constructorArgsCodeDataPtr := add(add(code, 32), creationCodeSize) } _memcpy(constructorArgsCodeDataPtr, constructorArgsDataPtr, constructorArgsSize); } /** * @dev Deploys a contract with constructor arguments. To create `constructorArgs`, call `abi.encode()` with the * contract's constructor arguments, in order. */ function _create(bytes memory constructorArgs) internal virtual returns (address) { bytes memory creationCode = _getCreationCodeWithArgs(constructorArgs); address destination; assembly { destination := create(0, add(creationCode, 32), mload(creationCode)) } if (destination == address(0)) { // Bubble up inner revert reason // solhint-disable-next-line no-inline-assembly assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } return destination; } // From // https://github.com/Arachnid/solidity-stringutils/blob/b9a6f6615cf18a87a823cbc461ce9e140a61c305/src/strings.sol function _memcpy( uint256 dest, uint256 src, uint256 len ) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes 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)) } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; /** * @dev Library used to deploy contracts with specific code. This can be used for long-term storage of immutable data as * contract code, which can be retrieved via the `extcodecopy` opcode. */ library CodeDeployer { // During contract construction, the full code supplied exists as code, and can be accessed via `codesize` and // `codecopy`. This is not the contract's final code however: whatever the constructor returns is what will be // stored as its code. // // We use this mechanism to have a simple constructor that stores whatever is appended to it. The following opcode // sequence corresponds to the creation code of the following equivalent Solidity contract, plus padding to make the // full code 32 bytes long: // // contract CodeDeployer { // constructor() payable { // uint256 size; // assembly { // size := sub(codesize(), 32) // size of appended data, as constructor is 32 bytes long // codecopy(0, 32, size) // copy all appended data to memory at position 0 // return(0, size) // return appended data for it to be stored as code // } // } // } // // More specifically, it is composed of the following opcodes (plus padding): // // [1] PUSH1 0x20 // [2] CODESIZE // [3] SUB // [4] DUP1 // [6] PUSH1 0x20 // [8] PUSH1 0x00 // [9] CODECOPY // [11] PUSH1 0x00 // [12] RETURN // // The padding is just the 0xfe sequence (invalid opcode). bytes32 private constant _DEPLOYER_CREATION_CODE = 0x602038038060206000396000f3fefefefefefefefefefefefefefefefefefefe; /** * @dev Deploys a contract with `code` as its code, returning the destination address. * * Reverts if deployment fails. */ function deploy(bytes memory code) internal returns (address destination) { bytes32 deployerCreationCode = _DEPLOYER_CREATION_CODE; // solhint-disable-next-line no-inline-assembly assembly { let codeLength := mload(code) // `code` is composed of length and data. We've already stored its length in `codeLength`, so we simply // replace it with the deployer creation code (which is exactly 32 bytes long). mstore(code, deployerCreationCode) // At this point, `code` now points to the deployer creation code immediately followed by `code`'s data // contents. This is exactly what the deployer expects to receive when created. destination := create(0, code, add(codeLength, 32)) // Finally, we restore the original length in order to not mutate `code`. mstore(code, codeLength) } // The create opcode returns the zero address when contract creation fails, so we revert if this happens. _require(destination != address(0), Errors.CODE_DEPLOYMENT_FAILED); } }
* @dev Library used to deploy contracts with specific code. This can be used for long-term storage of immutable data as contract code, which can be retrieved via the `extcodecopy` opcode./ During contract construction, the full code supplied exists as code, and can be accessed via `codesize` and `codecopy`. This is not the contract's final code however: whatever the constructor returns is what will be stored as its code. We use this mechanism to have a simple constructor that stores whatever is appended to it. The following opcode sequence corresponds to the creation code of the following equivalent Solidity contract, plus padding to make the full code 32 bytes long: contract CodeDeployer { constructor() payable { uint256 size; assembly { size := sub(codesize(), 32) size of appended data, as constructor is 32 bytes long codecopy(0, 32, size) copy all appended data to memory at position 0 return(0, size) return appended data for it to be stored as code } } } More specifically, it is composed of the following opcodes (plus padding): [1] PUSH1 0x20 [2] CODESIZE [3] SUB [4] DUP1 [6] PUSH1 0x20 [8] PUSH1 0x00 [9] CODECOPY [11] PUSH1 0x00 [12] RETURN The padding is just the 0xfe sequence (invalid opcode).
library CodeDeployer { bytes32 private constant _DEPLOYER_CREATION_CODE = 0x602038038060206000396000f3fefefefefefefefefefefefefefefefefefefe; function deploy(bytes memory code) internal returns (address destination) { bytes32 deployerCreationCode = _DEPLOYER_CREATION_CODE; assembly { let codeLength := mload(code) mstore(code, deployerCreationCode) destination := create(0, code, add(codeLength, 32)) mstore(code, codeLength) } } function deploy(bytes memory code) internal returns (address destination) { bytes32 deployerCreationCode = _DEPLOYER_CREATION_CODE; assembly { let codeLength := mload(code) mstore(code, deployerCreationCode) destination := create(0, code, add(codeLength, 32)) mstore(code, codeLength) } } _require(destination != address(0), Errors.CODE_DEPLOYMENT_FAILED); }
278,040
[ 1, 9313, 1399, 358, 7286, 20092, 598, 2923, 981, 18, 1220, 848, 506, 1399, 364, 1525, 17, 6408, 2502, 434, 11732, 501, 487, 6835, 981, 16, 1492, 848, 506, 10295, 3970, 326, 1375, 408, 710, 3530, 68, 11396, 18, 19, 463, 4017, 6835, 16171, 16, 326, 1983, 981, 4580, 1704, 487, 981, 16, 471, 848, 506, 15539, 3970, 1375, 7000, 554, 68, 471, 1375, 710, 3530, 8338, 1220, 353, 486, 326, 6835, 1807, 727, 981, 14025, 30, 15098, 326, 3885, 1135, 353, 4121, 903, 506, 4041, 487, 2097, 981, 18, 1660, 999, 333, 12860, 358, 1240, 279, 4143, 3885, 716, 9064, 15098, 353, 12317, 358, 518, 18, 1021, 3751, 11396, 3102, 13955, 358, 326, 6710, 981, 434, 326, 3751, 7680, 348, 7953, 560, 6835, 16, 8737, 4992, 358, 1221, 326, 1983, 981, 3847, 1731, 1525, 30, 6835, 3356, 10015, 264, 288, 377, 3885, 1435, 8843, 429, 288, 540, 2254, 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, 12083, 3356, 10015, 264, 288, 203, 565, 1731, 1578, 203, 3639, 3238, 5381, 389, 1639, 22971, 654, 67, 5458, 2689, 67, 5572, 273, 374, 92, 26, 3103, 4630, 3672, 23, 3672, 26, 3103, 7677, 3784, 5520, 26, 3784, 74, 23, 3030, 3030, 3030, 3030, 3030, 3030, 3030, 3030, 3030, 3030, 3030, 3030, 3030, 3030, 3030, 3030, 3030, 3030, 3030, 31, 203, 203, 203, 203, 203, 565, 445, 7286, 12, 3890, 3778, 981, 13, 2713, 1135, 261, 2867, 2929, 13, 288, 203, 3639, 1731, 1578, 7286, 264, 9906, 1085, 273, 389, 1639, 22971, 654, 67, 5458, 2689, 67, 5572, 31, 203, 203, 3639, 19931, 288, 203, 5411, 2231, 981, 1782, 519, 312, 945, 12, 710, 13, 203, 203, 5411, 312, 2233, 12, 710, 16, 7286, 264, 9906, 1085, 13, 203, 203, 5411, 2929, 519, 752, 12, 20, 16, 981, 16, 527, 12, 710, 1782, 16, 3847, 3719, 203, 203, 5411, 312, 2233, 12, 710, 16, 981, 1782, 13, 203, 3639, 289, 203, 203, 565, 289, 203, 565, 445, 7286, 12, 3890, 3778, 981, 13, 2713, 1135, 261, 2867, 2929, 13, 288, 203, 3639, 1731, 1578, 7286, 264, 9906, 1085, 273, 389, 1639, 22971, 654, 67, 5458, 2689, 67, 5572, 31, 203, 203, 3639, 19931, 288, 203, 5411, 2231, 981, 1782, 519, 312, 945, 12, 710, 13, 203, 203, 5411, 312, 2233, 12, 710, 16, 7286, 264, 9906, 1085, 13, 203, 203, 5411, 2929, 519, 752, 12, 20, 16, 981, 16, 527, 12, 710, 1782, 16, 3847, 3719, 203, 203, 5411, 312, 2233, 12, 710, 16, 2 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "../interfaces/IERC20Permit.sol"; import "../interfaces/IDeBridgeToken.sol"; import "../interfaces/IDeBridgeTokenDeployer.sol"; import "../interfaces/ISignatureVerifier.sol"; import "../interfaces/IWETH.sol"; import "../interfaces/IDeBridgeGate.sol"; import "../interfaces/ICallProxy.sol"; import "../interfaces/IFlashCallback.sol"; import "../libraries/SignatureUtil.sol"; import "../libraries/Flags.sol"; import "../interfaces/IWethGate.sol"; contract DeBridgeGate is Initializable, AccessControlUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable, IDeBridgeGate { using SafeERC20 for IERC20; using SignatureUtil for bytes; using Flags for uint256; /* ========== STATE VARIABLES ========== */ // Basis points or bps equal to 1/10000 // used to express relative values (fees) uint256 public constant BPS_DENOMINATOR = 10000; bytes32 public constant GOVMONITORING_ROLE = keccak256("GOVMONITORING_ROLE"); // role allowed to stop transfers address public deBridgeTokenDeployer; address public signatureVerifier; // current signatureVerifier address to verify signatures // address public confirmationAggregator; // current aggregator address to verify by oracles confirmations uint8 public excessConfirmations; // minimal required confirmations in case of too many confirmations uint256 public flashFeeBps; // fee in basis points (1/10000) uint256 public nonce; //outgoing submissions count mapping(bytes32 => DebridgeInfo) public getDebridge; // debridgeId (i.e. hash(native chainId, native tokenAddress)) => token mapping(bytes32 => DebridgeFeeInfo) public getDebridgeFeeInfo; mapping(bytes32 => bool) public override isSubmissionUsed; // submissionId (i.e. hash( debridgeId, amount, receiver, nonce)) => whether is claimed mapping(bytes32 => bool) public isBlockedSubmission; // submissionId => is blocked mapping(bytes32 => uint256) public getAmountThreshold; // debridge => amount threshold mapping(uint256 => ChainSupportInfo) public getChainToConfig; // whether the chain for the asset is supported to send mapping(uint256 => ChainSupportInfo) public getChainFromConfig;// whether the chain for the asset is supported to claim mapping(address => DiscountInfo) public feeDiscount; //fee discount for address mapping(address => TokenInfo) public getNativeInfo; //return native token info by wrapped token address address public defiController; // proxy to use the locked assets in Defi protocols address public feeProxy; // proxy to convert the collected fees into Link's address public callProxy; // proxy to execute user's calls IWETH public weth; // wrapped native token contract address public feeContractUpdater; // contract address that can override globalFixedNativeFee uint256 public globalFixedNativeFee; uint16 public globalTransferFeeBps; IWethGate public wethGate; bool public lockedClaim; //locker for claim method /* ========== ERRORS ========== */ error FeeProxyBadRole(); error DefiControllerBadRole(); error FeeContractUpdaterBadRole(); error AdminBadRole(); error GovMonitoringBadRole(); error DebridgeNotFound(); error WrongChainTo(); error WrongChainFrom(); error WrongArgument(); error WrongAutoArgument(); error TransferAmountTooHigh(); error NotSupportedFixedFee(); error TransferAmountNotCoverFees(); error InvalidTokenToSend(); error SubmissionUsed(); error SubmissionNotConfirmed(); error SubmissionAmountNotConfirmed(); error SubmissionBlocked(); error AmountMismatch(); error AssetAlreadyExist(); error AssetNotConfirmed(); error ZeroAddress(); error ProposedFeeTooHigh(); error FeeNotPaid(); error NotEnoughReserves(); error EthTransferFailed(); error Locked(); /* ========== MODIFIERS ========== */ modifier onlyFeeProxy() { if (feeProxy != msg.sender) revert FeeProxyBadRole(); _; } modifier onlyDefiController() { if (defiController != msg.sender) revert DefiControllerBadRole(); _; } modifier onlyFeeContractUpdater() { if (feeContractUpdater != msg.sender) revert FeeContractUpdaterBadRole(); _; } modifier onlyAdmin() { if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) revert AdminBadRole(); _; } modifier onlyGovMonitoring() { if (!hasRole(GOVMONITORING_ROLE, msg.sender)) revert GovMonitoringBadRole(); _; } /// @dev lock for claim method modifier lockClaim() { if (lockedClaim) revert Locked(); lockedClaim = true; _; lockedClaim = false; } /* ========== CONSTRUCTOR ========== */ /// @dev Constructor that initializes the most important configurations. function initialize( uint8 _excessConfirmations, IWETH _weth ) public initializer { excessConfirmations = _excessConfirmations; weth = _weth; _addAsset( getDebridgeId(getChainId(), address(_weth)), address(_weth), abi.encodePacked(address(_weth)), getChainId() ); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); __ReentrancyGuard_init(); } /* ========== send, claim ========== */ /// @dev Locks asset on the chain and enables withdraw on the other chain. /// @param _tokenAddress Asset identifier. /// @param _amount Amount to be transfered (note: the fee can be applyed). /// @param _chainIdTo Chain id of the target chain. /// @param _receiver Receiver address. /// @param _permit deadline + signature for approving the spender by signature. /// @param _useAssetFee use assets fee for pay protocol fix (work only for specials token) /// @param _referralCode Referral code /// @param _autoParams Auto params for external call in target network function send( address _tokenAddress, uint256 _amount, uint256 _chainIdTo, bytes memory _receiver, bytes memory _permit, bool _useAssetFee, uint32 _referralCode, bytes calldata _autoParams ) external payable override nonReentrant whenNotPaused { bytes32 debridgeId; FeeParams memory feeParams; uint256 amountAfterFee; // the amount will be reduced by the protocol fee (amountAfterFee, debridgeId, feeParams) = _send( _permit, _tokenAddress, _amount, _chainIdTo, _useAssetFee ); SubmissionAutoParamsTo memory autoParams = _validateAutoParams(_autoParams, amountAfterFee); amountAfterFee -= autoParams.executionFee; // round down amount in order not to bridge dust amountAfterFee = _normalizeTokenAmount(_tokenAddress, amountAfterFee); bytes32 submissionId = getSubmissionIdTo( debridgeId, _chainIdTo, amountAfterFee, _receiver, autoParams, _autoParams.length > 0 ); emit Sent( submissionId, debridgeId, amountAfterFee, _receiver, nonce, _chainIdTo, _referralCode, feeParams, _autoParams, msg.sender ); nonce++; } /// @dev Unlock the asset on the current chain and transfer to receiver. /// @param _debridgeId Asset identifier. /// @param _amount Amount of the transfered asset (note: the fee can be applyed). /// @param _chainIdFrom Chain where submission was sent /// @param _receiver Receiver address. /// @param _nonce Submission id. /// @param _signatures Validators signatures to confirm /// @param _autoParams Auto params for external call function claim( bytes32 _debridgeId, uint256 _amount, uint256 _chainIdFrom, address _receiver, uint256 _nonce, bytes calldata _signatures, bytes calldata _autoParams ) external override lockClaim whenNotPaused { if (!getChainFromConfig[_chainIdFrom].isSupported) revert WrongChainFrom(); SubmissionAutoParamsFrom memory autoParams; if (_autoParams.length > 0) { autoParams = abi.decode(_autoParams, (SubmissionAutoParamsFrom)); } bytes32 submissionId = getSubmissionIdFrom( _debridgeId, _chainIdFrom, _amount, _receiver, _nonce, autoParams, _autoParams.length > 0 ); // check if submission already claimed if (isSubmissionUsed[submissionId]) revert SubmissionUsed(); isSubmissionUsed[submissionId] = true; _checkConfirmations(submissionId, _debridgeId, _amount, _signatures); bool isNativeToken =_claim( submissionId, _debridgeId, _receiver, _amount, _chainIdFrom, autoParams ); emit Claimed( submissionId, _debridgeId, _amount, _receiver, _nonce, _chainIdFrom, _autoParams, isNativeToken ); } function flash( address _tokenAddress, address _receiver, uint256 _amount, bytes memory _data ) external override nonReentrant whenNotPaused // noDelegateCall { bytes32 debridgeId = getDebridgeId(getChainId(), _tokenAddress); if (!getDebridge[debridgeId].exist) revert DebridgeNotFound(); uint256 currentFlashFee = (_amount * flashFeeBps) / BPS_DENOMINATOR; uint256 balanceBefore = IERC20(_tokenAddress).balanceOf(address(this)); IERC20(_tokenAddress).safeTransfer(_receiver, _amount); IFlashCallback(msg.sender).flashCallback(currentFlashFee, _data); uint256 balanceAfter = IERC20(_tokenAddress).balanceOf(address(this)); if (balanceBefore + currentFlashFee > balanceAfter) revert FeeNotPaid(); uint256 paid = balanceAfter - balanceBefore; getDebridgeFeeInfo[debridgeId].collectedFees += paid; emit Flash(msg.sender, _tokenAddress, _receiver, _amount, paid); } function deployNewAsset( bytes memory _nativeTokenAddress, uint256 _nativeChainId, string memory _name, string memory _symbol, uint8 _decimals, bytes memory _signatures ) external nonReentrant whenNotPaused{ bytes32 debridgeId = getbDebridgeId(_nativeChainId, _nativeTokenAddress); if (getDebridge[debridgeId].exist) revert AssetAlreadyExist(); bytes32 deployId = keccak256(abi.encodePacked(debridgeId, _name, _symbol, _decimals)); // verify signatures ISignatureVerifier(signatureVerifier).submit(deployId, _signatures, excessConfirmations); address deBridgeTokenAddress = IDeBridgeTokenDeployer(deBridgeTokenDeployer) .deployAsset(debridgeId, _name, _symbol, _decimals); _addAsset(debridgeId, deBridgeTokenAddress, _nativeTokenAddress, _nativeChainId); } /// @dev Update native fix fee. called by our fee update contract /// @param _globalFixedNativeFee new value function autoUpdateFixedNativeFee( uint256 _globalFixedNativeFee ) external onlyFeeContractUpdater { globalFixedNativeFee = _globalFixedNativeFee; emit FixedNativeFeeAutoUpdated(_globalFixedNativeFee); } /* ========== ADMIN ========== */ /// @dev Update asset's fees. /// @param _chainIds Chain identifiers. /// @param _chainSupportInfo Chain support info. /// @param _isChainFrom is true for editing getChainFromConfig. function updateChainSupport( uint256[] memory _chainIds, ChainSupportInfo[] memory _chainSupportInfo, bool _isChainFrom ) external onlyAdmin { if (_chainIds.length != _chainSupportInfo.length) revert WrongArgument(); for (uint256 i = 0; i < _chainIds.length; i++) { if(_isChainFrom){ getChainFromConfig[_chainIds[i]] = _chainSupportInfo[i]; } else { getChainToConfig[_chainIds[i]] = _chainSupportInfo[i]; } emit ChainsSupportUpdated(_chainIds[i], _chainSupportInfo[i], _isChainFrom); } } function updateGlobalFee( uint256 _globalFixedNativeFee, uint16 _globalTransferFeeBps ) external onlyAdmin { globalFixedNativeFee = _globalFixedNativeFee; globalTransferFeeBps = _globalTransferFeeBps; emit FixedNativeFeeUpdated(_globalFixedNativeFee, _globalTransferFeeBps); } /// @dev Update asset's fees. /// @param _debridgeId Asset identifier. /// @param _supportedChainIds Chain identifiers. /// @param _assetFeesInfo Chain support info. function updateAssetFixedFees( bytes32 _debridgeId, uint256[] memory _supportedChainIds, uint256[] memory _assetFeesInfo ) external onlyAdmin { if (_supportedChainIds.length != _assetFeesInfo.length) revert WrongArgument(); DebridgeFeeInfo storage debridgeFee = getDebridgeFeeInfo[_debridgeId]; for (uint256 i = 0; i < _supportedChainIds.length; i++) { debridgeFee.getChainFee[_supportedChainIds[i]] = _assetFeesInfo[i]; } } function updateExcessConfirmations(uint8 _excessConfirmations) external onlyAdmin { if (_excessConfirmations == 0) revert WrongArgument(); excessConfirmations = _excessConfirmations; } /// @dev Set support for the chains where the token can be transfered. /// @param _chainId Chain id where tokens are sent. /// @param _isSupported Whether the token is transferable to the other chain. /// @param _isChainFrom is true for editing getChainFromConfig. function setChainSupport(uint256 _chainId, bool _isSupported, bool _isChainFrom) external onlyAdmin { if (_isChainFrom) { getChainFromConfig[_chainId].isSupported = _isSupported; } else { getChainToConfig[_chainId].isSupported = _isSupported; } emit ChainSupportUpdated(_chainId, _isSupported, _isChainFrom); } /// @dev Set proxy address. /// @param _callProxy Address of the proxy that executes external calls. function setCallProxy(address _callProxy) external onlyAdmin { callProxy = _callProxy; emit CallProxyUpdated(_callProxy); } /// @dev Add support for the asset. /// @param _debridgeId Asset identifier. /// @param _maxAmount Maximum amount of current chain token to be wrapped. /// @param _minReservesBps Minimal reserve ration in BPS. function updateAsset( bytes32 _debridgeId, uint256 _maxAmount, uint16 _minReservesBps, uint256 _amountThreshold ) external onlyAdmin { if (_minReservesBps > BPS_DENOMINATOR) revert WrongArgument(); DebridgeInfo storage debridge = getDebridge[_debridgeId]; // don't check existance of debridge - it allows to setup asset before first transfer debridge.maxAmount = _maxAmount; debridge.minReservesBps = _minReservesBps; getAmountThreshold[_debridgeId] = _amountThreshold; } /// @dev Set signature verifier address. /// @param _verifier Signature verifier address. function setSignatureVerifier(address _verifier) external onlyAdmin { signatureVerifier = _verifier; } /// @dev Set asset deployer address. /// @param _deBridgeTokenDeployer Asset deployer address. function setDeBridgeTokenDeployer(address _deBridgeTokenDeployer) external onlyAdmin { deBridgeTokenDeployer = _deBridgeTokenDeployer; } /// @dev Set defi controoler. /// @param _defiController Defi controller address address. function setDefiController(address _defiController) external onlyAdmin { defiController = _defiController; } /// @dev Set fee contract updater, that can update fix native fee /// @param _value new contract address. function setFeeContractUpdater(address _value) external onlyAdmin { feeContractUpdater = _value; } /// @dev Set wethGate contract, that uses for weth withdraws affected by EIP1884 /// @param _wethGate address of new wethGate contract. function setWethGate(IWethGate _wethGate) external onlyAdmin { wethGate = _wethGate; } /// @dev Stop all transfers. function pause() external onlyGovMonitoring { _pause(); } /// @dev Allow transfers. function unpause() external onlyAdmin whenPaused { _unpause(); } /// @dev Withdraw fees. /// @param _debridgeId Asset identifier. function withdrawFee(bytes32 _debridgeId) external override nonReentrant onlyFeeProxy { DebridgeFeeInfo storage debridgeFee = getDebridgeFeeInfo[_debridgeId]; // Amount for transfer to treasury uint256 amount = debridgeFee.collectedFees - debridgeFee.withdrawnFees; if (amount == 0) revert NotEnoughReserves(); debridgeFee.withdrawnFees += amount; if (_debridgeId == getDebridgeId(getChainId(), address(0))) { _safeTransferETH(feeProxy, amount); } else { // don't need this check as we check that amount is not zero // if (!getDebridge[_debridgeId].exist) revert DebridgeNotFound(); IERC20(getDebridge[_debridgeId].tokenAddress).safeTransfer(feeProxy, amount); } emit WithdrawnFee(_debridgeId, amount); } /// @dev Request the assets to be used in defi protocol. /// @param _tokenAddress Asset address. /// @param _amount Amount of tokens to request. function requestReserves(address _tokenAddress, uint256 _amount) external override onlyDefiController nonReentrant { bytes32 debridgeId = getDebridgeId(getChainId(), _tokenAddress); DebridgeInfo storage debridge = getDebridge[debridgeId]; if (!debridge.exist) revert DebridgeNotFound(); uint256 minReserves = (debridge.balance * debridge.minReservesBps) / BPS_DENOMINATOR; if (minReserves + _amount > IERC20(_tokenAddress).balanceOf(address(this))) revert NotEnoughReserves(); debridge.lockedInStrategies += _amount; IERC20(_tokenAddress).safeTransfer(defiController, _amount); } /// @dev Return the assets that were used in defi protocol. /// @param _tokenAddress Asset address. /// @param _amount Amount of tokens to claim. function returnReserves(address _tokenAddress, uint256 _amount) external override onlyDefiController nonReentrant { bytes32 debridgeId = getDebridgeId(getChainId(), _tokenAddress); DebridgeInfo storage debridge = getDebridge[debridgeId]; if (!debridge.exist) revert DebridgeNotFound(); debridge.lockedInStrategies -= _amount; IERC20(debridge.tokenAddress).safeTransferFrom( defiController, address(this), _amount ); } /// @dev Set fee converter proxy. /// @param _feeProxy Fee proxy address. function setFeeProxy(address _feeProxy) external onlyAdmin { feeProxy = _feeProxy; } function blockSubmission(bytes32[] memory _submissionIds, bool isBlocked) external onlyAdmin { for (uint256 i = 0; i < _submissionIds.length; i++) { isBlockedSubmission[_submissionIds[i]] = isBlocked; if (isBlocked) { emit Blocked(_submissionIds[i]); } else { emit Unblocked(_submissionIds[i]); } } } /// @dev Update flash fees. /// @param _flashFeeBps new fee in BPS function updateFlashFee(uint256 _flashFeeBps) external onlyAdmin { if (_flashFeeBps > BPS_DENOMINATOR) revert WrongArgument(); flashFeeBps = _flashFeeBps; } /// @dev Update discount. /// @param _address customer address /// @param _discountFixBps fix discount in BPS /// @param _discountTransferBps transfer % discount in BPS function updateFeeDiscount( address _address, uint16 _discountFixBps, uint16 _discountTransferBps ) external onlyAdmin { if (_address == address(0) || _discountFixBps > BPS_DENOMINATOR || _discountTransferBps > BPS_DENOMINATOR ) revert WrongArgument(); DiscountInfo storage discountInfo = feeDiscount[_address]; discountInfo.discountFixBps = _discountFixBps; discountInfo.discountTransferBps = _discountTransferBps; } // we need to accept ETH sends to unwrap WETH receive() external payable { // assert(msg.sender == address(weth)); // only accept ETH via fallback from the WETH contract } /* ========== INTERNAL ========== */ function _checkConfirmations( bytes32 _submissionId, bytes32 _debridgeId, uint256 _amount, bytes calldata _signatures ) internal { if (isBlockedSubmission[_submissionId]) revert SubmissionBlocked(); // inside check is confirmed ISignatureVerifier(signatureVerifier).submit( _submissionId, _signatures, _amount >= getAmountThreshold[_debridgeId] ? excessConfirmations : 0 ); } /// @dev Add support for the asset. /// @param _debridgeId Asset identifier. /// @param _tokenAddress Address of the asset on the current chain. /// @param _nativeAddress Address of the asset on the native chain. /// @param _nativeChainId Native chain id. function _addAsset( bytes32 _debridgeId, address _tokenAddress, bytes memory _nativeAddress, uint256 _nativeChainId ) internal { DebridgeInfo storage debridge = getDebridge[_debridgeId]; if (debridge.exist) revert AssetAlreadyExist(); if (_tokenAddress == address(0)) revert ZeroAddress(); debridge.exist = true; debridge.tokenAddress = _tokenAddress; debridge.chainId = _nativeChainId; // Don't override if the admin already set maxAmount in updateAsset method before if (debridge.maxAmount == 0) { debridge.maxAmount = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; } // debridge.minReservesBps = BPS; if (getAmountThreshold[_debridgeId] == 0) { getAmountThreshold[ _debridgeId ] = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; } TokenInfo storage tokenInfo = getNativeInfo[_tokenAddress]; tokenInfo.nativeChainId = _nativeChainId; tokenInfo.nativeAddress = _nativeAddress; emit PairAdded( _debridgeId, _tokenAddress, _nativeAddress, _nativeChainId, debridge.maxAmount, debridge.minReservesBps ); } /// @dev Locks asset on the chain and enables minting on the other chain. /// @param _amount Amount to be transfered (note: the fee can be applyed). /// @param _chainIdTo Chain id of the target chain. /// @param _permit deadline + signature for approving the spender by signature. function _send( bytes memory _permit, address _tokenAddress, uint256 _amount, uint256 _chainIdTo, bool _useAssetFee ) internal returns ( // bool isNativeToken, uint256 amountAfterFee, bytes32 debridgeId, FeeParams memory feeParams ) { _validateToken(_tokenAddress); // Run _permit first. Avoid Stack too deep if (_permit.length > 0) { // call permit before transfering token uint256 deadline = _permit.toUint256(0); (bytes32 r, bytes32 s, uint8 v) = _permit.parseSignature(32); IERC20Permit(_tokenAddress).permit( msg.sender, address(this), _amount, deadline, v, r, s); } TokenInfo memory nativeTokenInfo = getNativeInfo[_tokenAddress]; bool isNativeToken = nativeTokenInfo.nativeChainId == 0 ? true // token not in mapping : nativeTokenInfo.nativeChainId == getChainId(); // token native chain id the same if (isNativeToken) { //We use WETH debridgeId for transfer ETH debridgeId = getDebridgeId( getChainId(), _tokenAddress == address(0) ? address(weth) : _tokenAddress ); } else { debridgeId = getbDebridgeId( nativeTokenInfo.nativeChainId, nativeTokenInfo.nativeAddress ); } DebridgeInfo storage debridge = getDebridge[debridgeId]; if (!debridge.exist) { if (isNativeToken) { _addAsset( debridgeId, _tokenAddress == address(0) ? address(weth) : _tokenAddress, abi.encodePacked(_tokenAddress), getChainId() ); } else revert DebridgeNotFound(); } ChainSupportInfo memory chainFees = getChainToConfig[_chainIdTo]; if (!chainFees.isSupported) revert WrongChainTo(); if (_amount > debridge.maxAmount) revert TransferAmountTooHigh(); if (_tokenAddress == address(0)) { if (msg.value < _amount) revert AmountMismatch(); else if (msg.value > _amount) { // refund extra eth payable(msg.sender).transfer(msg.value - _amount); } weth.deposit{value: _amount}(); _useAssetFee = true; } else { IERC20 token = IERC20(_tokenAddress); uint256 balanceBefore = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); // Received real amount _amount = token.balanceOf(address(this)) - balanceBefore; } //_processFeeForTransfer { DiscountInfo memory discountInfo = feeDiscount[msg.sender]; DebridgeFeeInfo storage debridgeFee = getDebridgeFeeInfo[debridgeId]; // calculate fixed fee uint256 assetsFixedFee; if (_useAssetFee) { assetsFixedFee = debridgeFee.getChainFee[_chainIdTo]; if (assetsFixedFee == 0) revert NotSupportedFixedFee(); // Apply discount for a asset fixed fee assetsFixedFee -= assetsFixedFee * discountInfo.discountFixBps / BPS_DENOMINATOR; feeParams.fixFee = assetsFixedFee; } else { // collect native fees // use globalFixedNativeFee if value for chain is not setted uint256 nativeFee = chainFees.fixedNativeFee == 0 ? globalFixedNativeFee : chainFees.fixedNativeFee; // Apply discount for a fixed fee nativeFee -= nativeFee * discountInfo.discountFixBps / BPS_DENOMINATOR; if (msg.value < nativeFee) revert TransferAmountNotCoverFees(); else if (msg.value > nativeFee) { // refund extra fee eth payable(msg.sender).transfer(msg.value - nativeFee); } bytes32 nativeDebridgeId = getDebridgeId(getChainId(), address(0)); getDebridgeFeeInfo[nativeDebridgeId].collectedFees += nativeFee; feeParams.fixFee = nativeFee; } // Calculate transfer fee if (chainFees.transferFeeBps == 0) { // use globalTransferFeeBps if value for chain is not setted chainFees.transferFeeBps = globalTransferFeeBps; } uint256 transferFee = (_amount * chainFees.transferFeeBps) / BPS_DENOMINATOR; // apply discount for a transfer fee transferFee -= transferFee * discountInfo.discountTransferBps / BPS_DENOMINATOR; uint256 totalFee = transferFee + assetsFixedFee; if (_amount < totalFee) revert TransferAmountNotCoverFees(); debridgeFee.collectedFees += totalFee; amountAfterFee = _amount - totalFee; // initialize feeParams // feeParams.fixFee = _useAssetFee ? assetsFixedFee : msg.value; feeParams.transferFee = transferFee; feeParams.useAssetFee = _useAssetFee; feeParams.receivedAmount = _amount; feeParams.isNativeToken = isNativeToken; } // Is native token if (isNativeToken) { debridge.balance += amountAfterFee; } else { debridge.balance -= amountAfterFee; IDeBridgeToken(debridge.tokenAddress).burn(amountAfterFee); } return (amountAfterFee, debridgeId, feeParams); } function _validateToken(address _token) internal { if (_token == address(0)) { // no validation for native tokens return; } // check existance of decimals method (bool success, ) = _token.call(abi.encodeWithSignature("decimals()")); if (!success) revert InvalidTokenToSend(); // check existance of symbol method (success, ) = _token.call(abi.encodeWithSignature("symbol()")); if (!success) revert InvalidTokenToSend(); } function _validateAutoParams( bytes calldata _autoParams, uint256 _amount ) internal pure returns (SubmissionAutoParamsTo memory autoParams) { if (_autoParams.length > 0) { autoParams = abi.decode(_autoParams, (SubmissionAutoParamsTo)); if (autoParams.executionFee > _amount) revert ProposedFeeTooHigh(); if (autoParams.data.length > 0 && autoParams.fallbackAddress.length == 0 ) revert WrongAutoArgument(); } } /// @dev Unlock the asset on the current chain and transfer to receiver. /// @param _debridgeId Asset identifier. /// @param _receiver Receiver address. /// @param _amount Amount of the transfered asset (note: the fee can be applyed). function _claim( bytes32 _submissionId, bytes32 _debridgeId, address _receiver, uint256 _amount, uint256 _chainIdFrom, SubmissionAutoParamsFrom memory _autoParams ) internal returns (bool isNativeToken) { DebridgeInfo storage debridge = getDebridge[_debridgeId]; if (!debridge.exist) revert DebridgeNotFound(); // if (debridge.chainId != getChainId()) revert WrongChain(); isNativeToken = debridge.chainId == getChainId(); if (isNativeToken) { debridge.balance -= _amount + _autoParams.executionFee; } else { debridge.balance += _amount + _autoParams.executionFee; } address _token = debridge.tokenAddress; bool unwrapETH = isNativeToken && _autoParams.flags.getFlag(Flags.UNWRAP_ETH) && _token == address(weth); if (_autoParams.executionFee > 0) { _mintOrTransfer(_token, msg.sender, _autoParams.executionFee, isNativeToken); } if (_autoParams.data.length > 0) { // use local variable to reduce gas usage address _callProxy = callProxy; bool status; if (unwrapETH) { // withdraw weth to callProxy directly _withdrawWeth(_callProxy, _amount); status = ICallProxy(_callProxy).call( _autoParams.fallbackAddress, _receiver, _autoParams.data, _autoParams.flags, _autoParams.nativeSender, _chainIdFrom ); } else { _mintOrTransfer(_token, _callProxy, _amount, isNativeToken); status = ICallProxy(_callProxy).callERC20( _token, _autoParams.fallbackAddress, _receiver, _autoParams.data, _autoParams.flags, _autoParams.nativeSender, _chainIdFrom ); } emit AutoRequestExecuted(_submissionId, status, _callProxy); } else if (unwrapETH) { // transferring WETH with unwrap flag _withdrawWeth(_receiver, _amount); } else { _mintOrTransfer(_token, _receiver, _amount, isNativeToken); } } function _mintOrTransfer( address _token, address _receiver, uint256 _amount, bool isNativeToken ) internal { if (isNativeToken) { IERC20(_token).safeTransfer(_receiver, _amount); } else { IDeBridgeToken(_token).mint(_receiver, _amount); } } /* * @dev transfer ETH to an address, revert if it fails. * @param to recipient of the transfer * @param value the amount to send */ function _safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); if (!success) revert EthTransferFailed(); } function _withdrawWeth(address _receiver, uint _amount) internal { if (address(wethGate) == address(0)) { // dealing with weth withdraw affected by EIP1884 weth.withdraw(_amount); _safeTransferETH(_receiver, _amount); } else { IERC20(address(weth)).safeTransfer(address(wethGate), _amount); wethGate.withdraw(_receiver, _amount); } } /* * @dev round down token amount * @param _token address of token, zero for native tokens * @param __amount amount for rounding */ function _normalizeTokenAmount( address _token, uint256 _amount ) internal view returns (uint256) { uint256 decimals = _token == address(0) ? 18 : IERC20Metadata(_token).decimals(); uint256 maxDecimals = 8; if (decimals > maxDecimals) { uint256 multiplier = 10 ** (decimals - maxDecimals); _amount = _amount / multiplier * multiplier; } return _amount; } /* VIEW */ function getDefiAvaliableReserves(address _tokenAddress) external view override returns (uint256) { DebridgeInfo storage debridge = getDebridge[getDebridgeId(getChainId(), _tokenAddress)]; return (debridge.balance * (BPS_DENOMINATOR - debridge.minReservesBps)) / BPS_DENOMINATOR; } /// @dev Calculates asset identifier. /// @param _chainId Current chain id. /// @param _tokenAddress Address of the asset on the other chain. function getDebridgeId(uint256 _chainId, address _tokenAddress) public pure returns (bytes32) { return keccak256(abi.encodePacked(_chainId, _tokenAddress)); } /// @dev Calculates asset identifier. /// @param _chainId Current chain id. /// @param _tokenAddress Address of the asset on the other chain. function getbDebridgeId(uint256 _chainId, bytes memory _tokenAddress) public pure returns (bytes32) { return keccak256(abi.encodePacked(_chainId, _tokenAddress)); } /// @dev Returns asset fixed fee value for specified debridge and chainId. /// @param _debridgeId Asset identifier. /// @param _chainId Chain id. function getDebridgeChainAssetFixedFee( bytes32 _debridgeId, uint256 _chainId ) external view override returns (uint256) { // if (!getDebridge[_debridgeId].exist) revert DebridgeNotFound(); return getDebridgeFeeInfo[_debridgeId].getChainFee[_chainId]; } /// @dev Calculate submission id for auto claimable transfer. /// @param _debridgeId Asset identifier. /// @param _chainIdFrom Chain identifier of the chain where tokens are sent from. /// @param _receiver Receiver address. /// @param _amount Amount of the transfered asset (note: the fee can be applyed). /// @param _nonce Submission id. function getSubmissionIdFrom( bytes32 _debridgeId, uint256 _chainIdFrom, uint256 _amount, address _receiver, uint256 _nonce, SubmissionAutoParamsFrom memory autoParams, bool hasAutoParams ) public view returns (bytes32) { bytes memory packedSubmission = abi.encodePacked( _debridgeId, _chainIdFrom, getChainId(), _amount, _receiver, _nonce ); if (hasAutoParams) { // auto submission return keccak256( abi.encodePacked( packedSubmission, autoParams.executionFee, autoParams.flags, autoParams.fallbackAddress, autoParams.data, autoParams.nativeSender ) ); } // regular submission return keccak256(packedSubmission); } function getSubmissionIdTo( bytes32 _debridgeId, uint256 _chainIdTo, uint256 _amount, bytes memory _receiver, SubmissionAutoParamsTo memory autoParams, bool hasAutoParams ) private view returns (bytes32) { bytes memory packedSubmission = abi.encodePacked( _debridgeId, getChainId(), _chainIdTo, _amount, _receiver, nonce ); if (hasAutoParams) { // auto submission return keccak256( abi.encodePacked( packedSubmission, autoParams.executionFee, autoParams.flags, autoParams.fallbackAddress, autoParams.data, msg.sender ) ); } // regular submission return keccak256(packedSubmission); } function getNativeTokenInfo(address currentTokenAddress) external view override returns (uint256 nativeChainId, bytes memory nativeAddress) { TokenInfo memory tokenInfo = getNativeInfo[currentTokenAddress]; return (tokenInfo.nativeChainId, tokenInfo.nativeAddress); } function getChainId() public view virtual returns (uint256 cid) { assembly { cid := chainid() } } // ============ Version Control ============ function version() external pure returns (uint256) { return 120; // 1.2.0 } } // 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 Contracts guidelines: functions revert * instead 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 default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _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"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal 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"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(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"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(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 transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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 pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view 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 ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view 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()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ 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.7; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "../interfaces/IERC20Permit.sol"; interface IDeBridgeToken is IERC20Upgradeable, IERC20Permit { function mint(address _receiver, uint256 _amount) external; function burn(uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface IDeBridgeTokenDeployer { function deployAsset( bytes32 _debridgeId, string memory _name, string memory _symbol, uint8 _decimals ) external returns (address deTokenAddress); event DeBridgeTokenDeployed( address asset, string name, string symbol, uint8 decimals ); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface ISignatureVerifier { /* ========== EVENTS ========== */ event Confirmed(bytes32 submissionId, address operator); // emitted once the submission is confirmed by the only oracle event DeployConfirmed(bytes32 deployId, address operator); // emitted once the submission is confirmed by one oracle /* ========== FUNCTIONS ========== */ function submit( bytes32 _submissionId, bytes memory _signatures, uint8 _excessConfirmations ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface IWETH { function deposit() external payable; function withdraw(uint256 wad) external; 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); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface IDeBridgeGate { /* ========== STRUCTS ========== */ struct TokenInfo { uint256 nativeChainId; bytes nativeAddress; } struct DebridgeInfo { uint256 chainId; // native chain id uint256 maxAmount; // maximum amount to transfer uint256 balance; // total locked assets uint256 lockedInStrategies; // total locked assets in strategy (AAVE, Compound, etc) address tokenAddress; // asset address on the current chain uint16 minReservesBps; // minimal hot reserves in basis points (1/10000) bool exist; } struct DebridgeFeeInfo { uint256 collectedFees; // total collected fees uint256 withdrawnFees; // fees that already withdrawn mapping(uint256 => uint256) getChainFee; // whether the chain for the asset is supported } struct ChainSupportInfo { uint256 fixedNativeFee; // transfer fixed fee bool isSupported; // whether the chain for the asset is supported uint16 transferFeeBps; // transfer fee rate nominated in basis points (1/10000) of transferred amount } struct DiscountInfo { uint16 discountFixBps; // fix discount in BPS uint16 discountTransferBps; // transfer % discount in BPS } /// @param executionFee Fee paid to the transaction executor. /// @param fallbackAddress Receiver of the tokens if the call fails. struct SubmissionAutoParamsTo { uint256 executionFee; uint256 flags; bytes fallbackAddress; bytes data; } /// @param executionFee Fee paid to the transaction executor. /// @param fallbackAddress Receiver of the tokens if the call fails. struct SubmissionAutoParamsFrom { uint256 executionFee; uint256 flags; address fallbackAddress; bytes data; bytes nativeSender; } struct FeeParams { uint256 receivedAmount; uint256 fixFee; uint256 transferFee; bool useAssetFee; bool isNativeToken; } /* ========== PUBLIC VARS GETTERS ========== */ function isSubmissionUsed(bytes32 submissionId) external returns (bool); /* ========== FUNCTIONS ========== */ /// @dev Locks asset on the chain and enables minting on the other chain. /// @param _tokenAddress Asset identifier. /// @param _receiver Receiver address. /// @param _amount Amount to be transfered (note: the fee can be applyed). /// @param _chainIdTo Chain id of the target chain. function send( address _tokenAddress, uint256 _amount, uint256 _chainIdTo, bytes memory _receiver, bytes memory _permit, bool _useAssetFee, uint32 _referralCode, bytes calldata _autoParams ) external payable; /// @dev Unlock the asset on the current chain and transfer to receiver. /// @param _debridgeId Asset identifier. /// @param _receiver Receiver address. /// @param _amount Amount of the transfered asset (note: the fee can be applyed). /// @param _nonce Submission id. function claim( bytes32 _debridgeId, uint256 _amount, uint256 _chainIdFrom, address _receiver, uint256 _nonce, bytes calldata _signatures, bytes calldata _autoParams ) external; function flash( address _tokenAddress, address _receiver, uint256 _amount, bytes memory _data ) external; function getDefiAvaliableReserves(address _tokenAddress) external view returns (uint256); /// @dev Request the assets to be used in defi protocol. /// @param _tokenAddress Asset address. /// @param _amount Amount of tokens to request. function requestReserves(address _tokenAddress, uint256 _amount) external; /// @dev Return the assets that were used in defi protocol. /// @param _tokenAddress Asset address. /// @param _amount Amount of tokens to claim. function returnReserves(address _tokenAddress, uint256 _amount) external; /// @dev Withdraw fees. /// @param _debridgeId Asset identifier. function withdrawFee(bytes32 _debridgeId) external; function getNativeTokenInfo(address currentTokenAddress) external view returns (uint256 chainId, bytes memory nativeAddress); function getDebridgeChainAssetFixedFee( bytes32 _debridgeId, uint256 _chainId ) external view returns (uint256); /* ========== EVENTS ========== */ event Sent( bytes32 submissionId, bytes32 indexed debridgeId, uint256 amount, bytes receiver, uint256 nonce, uint256 indexed chainIdTo, uint32 referralCode, FeeParams feeParams, bytes autoParams, address nativeSender // bool isNativeToken //added to feeParams ); // emited once the native tokens are locked to be sent to the other chain event Claimed( bytes32 submissionId, bytes32 indexed debridgeId, uint256 amount, address indexed receiver, uint256 nonce, uint256 indexed chainIdFrom, bytes autoParams, bool isNativeToken ); // emited once the tokens are withdrawn on native chain event PairAdded( bytes32 debridgeId, address tokenAddress, bytes nativeAddress, uint256 indexed nativeChainId, uint256 maxAmount, uint16 minReservesBps ); // emited when new asset is supported event ChainSupportUpdated(uint256 chainId, bool isSupported, bool isChainFrom); // Emits when the asset is allowed/disallowed to be transferred to the chain. event ChainsSupportUpdated( uint256 chainIds, ChainSupportInfo chainSupportInfo, bool isChainFrom); // emited when the supported assets are updated event CallProxyUpdated(address callProxy); // emited when the new call proxy set event AutoRequestExecuted( bytes32 submissionId, bool indexed success, address callProxy ); // emited when the new call proxy set event Blocked(bytes32 submissionId); //Block submission event Unblocked(bytes32 submissionId); //UnBlock submission event Flash( address sender, address indexed tokenAddress, address indexed receiver, uint256 amount, uint256 paid ); event WithdrawnFee(bytes32 debridgeId, uint256 fee); event FixedNativeFeeUpdated( uint256 globalFixedNativeFee, uint256 globalTransferFeeBps); event FixedNativeFeeAutoUpdated(uint256 globalFixedNativeFee); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface ICallProxy { function submissionChainIdFrom() external returns (uint256); function submissionNativeSender() external returns (bytes memory); function call( address _fallbackAddress, address _receiver, bytes memory _data, uint256 _flags, bytes memory _nativeSender, uint256 _chainIdFrom ) external payable returns (bool); function callERC20( address _token, address _fallbackAddress, address _receiver, bytes memory _data, uint256 _flags, bytes memory _nativeSender, uint256 _chainIdFrom ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /// @title Callback for IDeBridgeGate#flash /// @notice Any contract that calls IDeBridgeGate#flash must implement this interface interface IFlashCallback { /// @param fee The fee amount in token due to the pool by the end of the flash /// @param data Any data passed through by the caller via the IDeBridgeGate#flash call function flashCallback(uint256 fee, bytes calldata data) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.7; library SignatureUtil { /* ========== ERRORS ========== */ error WrongArgumentLength(); error SignatureInvalidLength(); error SignatureInvalidV(); /// @dev Prepares raw msg that was signed by the oracle. /// @param _submissionId Submission identifier. function getUnsignedMsg(bytes32 _submissionId) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _submissionId)); } /// @dev Splits signature bytes to r,s,v components. /// @param _signature Signature bytes in format r+s+v. function splitSignature(bytes memory _signature) internal pure returns ( bytes32 r, bytes32 s, uint8 v ) { if (_signature.length != 65) revert SignatureInvalidLength(); return parseSignature(_signature, 0); } function parseSignature(bytes memory _signatures, uint256 offset) internal pure returns ( bytes32 r, bytes32 s, uint8 v ) { assembly { r := mload(add(_signatures, add(32, offset))) s := mload(add(_signatures, add(64, offset))) v := and(mload(add(_signatures, add(65, offset))), 0xff) } if (v < 27) v += 27; if (v != 27 && v != 28) revert SignatureInvalidV(); } function toUint256(bytes memory _bytes, uint256 _offset) internal pure returns (uint256 result) { if (_bytes.length < _offset + 32) revert WrongArgumentLength(); assembly { result := mload(add(add(_bytes, 0x20), _offset)) } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.7; library Flags { /* ========== FLAGS ========== */ // Flag to unwrap ETH uint256 public constant UNWRAP_ETH = 0; // Flag to revert if external call fails uint256 public constant REVERT_IF_EXTERNAL_FAIL = 1; // Flag to call proxy with a sender contract uint256 public constant PROXY_WITH_SENDER = 2; function getFlag( uint256 _packedFlags, uint256 _flag ) internal pure returns (bool) { uint256 flag = (_packedFlags >> _flag) & uint256(1); return flag == 1; } // function setFlag( // uint256 _packedFlags, // uint256 _flag, // bool _value // ) internal pure returns (uint256) { // if (_value) // return _packedFlags | uint256(1) << _flag; // else // return _packedFlags & ~(uint256(1) << _flag); // } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.7; interface IWethGate { function withdraw(address receiver, uint wad) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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); }
emited when the supported assets are updated
bool isChainFrom);
321,020
[ 1, 351, 16261, 1347, 326, 3260, 7176, 854, 3526, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1426, 353, 3893, 1265, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x3Bd85DF9633eF0205206BB519E4dDee152Bb0005/sources/contracts/token/RewardsDistributor.sol
* Apply specific BABL mining weights to baseline BABL mining rewards based on mining benchmark params Benchmark creates 3 different segments to differentiate between bad, break even or good strategies @param _returned Strategy capital returned @param _allocated Strategy capital allocated @param _rewards Strategy baseline BABL rewards @param _executedAt Strategy timestamp of initial execution/ Real time profit Any heart garden strategy get boosted by 150% We categorize the strategy APY profits into one of the 3 segments (very bad, regular and cool strategies) Bad and regular will be penalized from bigger penalization to lower Cool strategies will be boosted As we get real time profit (returned / allocated) we need to annualize the strategy profits (APY) Time weighted profit if > 1e18 duration less than 1 year, < 1e18 longer than 1 year Strategy is on positive profit We calculate expected absolute returns in reserve asset decimals If strategy is less than 1 year, APY earnings will be higher else, APY earnings will be lower than today (we need to estimate annualized earnings) Strategy is in loss We calculate expected absolute returns in reserve asset decimals If strategy is less than 1 year, APY loses will be higher else, APY loses will be lower than today (we need to estimate annualized loses) TODO: Replace _allocated by avgCapitalAllocated to handle adding or removing capital from strategy with lower impact along the time Segment 1: Bad strategy, usually gets penalty by benchmark[2] factor Segment 2: Not a cool strategy, can get penalty by benchmark[3] factor Segment 3: A real cool strategy, can get boost by benchmark[4] factor. Must be always >= 1e18
function _getBenchmarkRewards( uint256 _returned, uint256 _allocated, uint256 _rewards, uint256 _executedAt, address _strategy ) private view returns (uint256) { uint256 rewardsFactor; uint256 percentageProfit = _returned.preciseDiv(_allocated); if (address(IStrategy(_strategy).garden()) == address(IHeart(controller.heart()).heartGarden())) { rewardsFactor = 15e17; uint256 timedAPY = uint256(365 days).preciseDiv(block.timestamp > _executedAt ? block.timestamp.sub(_executedAt) : 1); if (percentageProfit >= 1e18) { returnedAPY = _allocated.add(_returned.sub(_allocated).preciseMul(timedAPY)); returnedAPY = _allocated.sub(_returned).preciseMul(timedAPY); returnedAPY = returnedAPY < _allocated ? _allocated.sub(returnedAPY) : 0; } if (profitAPY < benchmark[0]) { rewardsFactor = benchmark[2]; rewardsFactor = benchmark[3]; rewardsFactor = benchmark[4]; } } return _rewards.preciseMul(bablPrincipalWeight).add( _rewards.preciseMul(bablProfitWeight).preciseMul(percentageProfit).preciseMul(rewardsFactor) ); }
3,050,180
[ 1, 7001, 2923, 605, 2090, 48, 1131, 310, 5376, 358, 14243, 605, 2090, 48, 1131, 310, 283, 6397, 2511, 603, 1131, 310, 14128, 859, 21854, 3414, 890, 3775, 5155, 358, 3775, 3840, 3086, 5570, 16, 898, 5456, 578, 7494, 20417, 225, 389, 2463, 329, 6647, 19736, 12872, 2106, 225, 389, 28172, 1850, 19736, 12872, 11977, 225, 389, 266, 6397, 5411, 19736, 14243, 605, 2090, 48, 283, 6397, 225, 389, 4177, 4817, 861, 540, 19736, 2858, 434, 2172, 4588, 19, 15987, 813, 450, 7216, 5502, 3904, 485, 314, 24466, 6252, 336, 14994, 329, 635, 18478, 9, 1660, 31921, 554, 326, 6252, 14410, 61, 9214, 1282, 1368, 1245, 434, 326, 890, 5155, 261, 3242, 5570, 16, 6736, 471, 27367, 20417, 13, 6107, 471, 6736, 903, 506, 14264, 287, 1235, 628, 18983, 14264, 287, 1588, 358, 2612, 385, 1371, 20417, 903, 506, 14994, 329, 2970, 732, 336, 2863, 813, 450, 7216, 261, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 389, 588, 30672, 17631, 14727, 12, 203, 3639, 2254, 5034, 389, 2463, 329, 16, 203, 3639, 2254, 5034, 389, 28172, 16, 203, 3639, 2254, 5034, 389, 266, 6397, 16, 203, 3639, 2254, 5034, 389, 4177, 4817, 861, 16, 203, 3639, 1758, 389, 14914, 203, 565, 262, 3238, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 283, 6397, 6837, 31, 203, 3639, 2254, 5034, 11622, 626, 7216, 273, 389, 2463, 329, 18, 4036, 784, 7244, 24899, 28172, 1769, 203, 3639, 309, 261, 2867, 12, 45, 4525, 24899, 14914, 2934, 75, 24466, 10756, 422, 1758, 12, 45, 5256, 485, 12, 5723, 18, 580, 485, 1435, 2934, 580, 485, 43, 24466, 1435, 3719, 288, 203, 5411, 283, 6397, 6837, 273, 4711, 73, 4033, 31, 203, 5411, 2254, 5034, 7491, 2203, 61, 273, 203, 7734, 2254, 5034, 12, 5718, 25, 4681, 2934, 4036, 784, 7244, 12, 2629, 18, 5508, 405, 389, 4177, 4817, 861, 692, 1203, 18, 5508, 18, 1717, 24899, 4177, 4817, 861, 13, 294, 404, 1769, 203, 5411, 309, 261, 18687, 626, 7216, 1545, 404, 73, 2643, 13, 288, 203, 7734, 2106, 2203, 61, 273, 389, 28172, 18, 1289, 24899, 2463, 329, 18, 1717, 24899, 28172, 2934, 4036, 784, 27860, 12, 20905, 2203, 61, 10019, 203, 7734, 2106, 2203, 61, 273, 389, 28172, 18, 1717, 24899, 2463, 329, 2934, 4036, 784, 27860, 12, 20905, 2203, 61, 1769, 203, 7734, 2106, 2203, 61, 273, 2106, 2203, 61, 411, 389, 28172, 692, 389, 28172, 18, 1717, 12, 2463, 329, 2203, 61, 13, 294, 2 ]
/* =============================================== * Flattened with Solidifier by Coinage * * https://solidifier.coina.ge * =============================================== */ pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: SafeDecimalMath.sol version: 2.0 author: Kevin Brown Gavin Conway date: 2018-10-18 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A library providing safe mathematical operations for division and multiplication with the capability to round or truncate the results to the nearest increment. Operations can return a standard precision or high precision decimal. High precision decimals are useful for example when attempting to calculate percentages or fractions accurately. ----------------------------------------------------------------- */ /** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals of a specified precision (either standard * or high). */ library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Owned.sol version: 1.1 author: Anton Jurisevic Dominic Romanowski date: 2018-2-26 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- An Owned contract, to be inherited by other contracts. Requires its owner to be explicitly set in the constructor. Provides an onlyOwner access modifier. To change owner, the current owner must nominate the next owner, who then has to accept the nomination. The nomination can be cancelled before it is accepted by the new owner by having the previous owner change the nomination (setting it to 0). ----------------------------------------------------------------- */ /** * @title A contract with an owner. * @notice Contract ownership can be transferred by first nominating the new owner, * who must then accept the ownership, which prevents accidental incorrect ownership transfers. */ contract Owned { address public owner; address public nominatedOwner; /** * @dev Owned Constructor */ constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } /** * @notice Nominate a new owner of this contract. * @dev Only the current owner may nominate a new owner. */ function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } /** * @notice Accept the nomination to be owner. */ function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } contract IFeePool { address public FEE_ADDRESS; function amountReceivedFromExchange(uint value) external view returns (uint); function amountReceivedFromTransfer(uint value) external view returns (uint); function feePaid(bytes4 currencyKey, uint amount) external; function appendAccountIssuanceRecord(address account, uint lockedAmount, uint debtEntryIndex) external; function rewardsMinted(uint amount) external; function transferFeeIncurred(uint value) public view returns (uint); } contract ISynthetixState { // A struct for handing values associated with an individual user's debt position struct IssuanceData { // Percentage of the total debt owned at the time // of issuance. This number is modified by the global debt // delta array. You can figure out a user's exit price and // collateralisation ratio using a combination of their initial // debt and the slice of global debt delta which applies to them. uint initialDebtOwnership; // This lets us know when (in relative terms) the user entered // the debt pool so we can calculate their exit price and // collateralistion ratio uint debtEntryIndex; } uint[] public debtLedger; uint public issuanceRatio; mapping(address => IssuanceData) public issuanceData; function debtLedgerLength() external view returns (uint); function hasIssued(address account) external view returns (bool); function incrementTotalIssuerCount() external; function decrementTotalIssuerCount() external; function setCurrentIssuanceData(address account, uint initialDebtOwnership) external; function lastDebtLedgerEntry() external view returns (uint); function appendDebtLedgerValue(uint value) external; function clearIssuanceData(address account) external; } interface ISynth { function burn(address account, uint amount) external; function issue(address account, uint amount) external; function transfer(address to, uint value) public returns (bool); function triggerTokenFallbackIfNeeded(address sender, address recipient, uint amount) external; function transferFrom(address from, address to, uint value) public returns (bool); } /** * @title SynthetixEscrow interface */ interface ISynthetixEscrow { function balanceOf(address account) public view returns (uint); function appendVestingEntry(address account, uint quantity) public; } /** * @title ExchangeRates interface */ interface IExchangeRates { function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey) public view returns (uint); function rateForCurrency(bytes4 currencyKey) public view returns (uint); function anyRateIsStale(bytes4[] currencyKeys) external view returns (bool); function rateIsStale(bytes4 currencyKey) external view returns (bool); } /** * @title Synthetix interface contract * @dev pseudo interface, actually declared as contract to hold the public getters */ contract ISynthetix { // ========== PUBLIC STATE VARIABLES ========== IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ISynthetixState public synthetixState; IExchangeRates public exchangeRates; // ========== PUBLIC FUNCTIONS ========== function balanceOf(address account) public view returns (uint); function transfer(address to, uint value) public returns (bool); function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey) public view returns (uint); function synthInitiatedFeePayment(address from, bytes4 sourceCurrencyKey, uint sourceAmount) external returns (bool); function synthInitiatedExchange( address from, bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress) external returns (bool); function collateralisationRatio(address issuer) public view returns (uint); function totalIssuedSynths(bytes4 currencyKey) public view returns (uint); function getSynth(bytes4 currencyKey) public view returns (ISynth); function debtBalanceOf(address issuer, bytes4 currencyKey) public view returns (uint); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: RewardEscrow.sol version: 1.0 author: Jackson Chan Clinton Ennis date: 2019-03-01 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Escrows the SNX rewards from the inflationary supply awarded to users for staking their SNX and maintaining the c-rationn target. SNW rewards are escrowed for 1 year from the claim date and users can call vest in 12 months time. ----------------------------------------------------------------- */ /** * @title A contract to hold escrowed SNX and free them at given schedules. */ contract RewardEscrow is Owned { using SafeMath for uint; /* The corresponding Synthetix contract. */ ISynthetix public synthetix; IFeePool public feePool; /* Lists of (timestamp, quantity) pairs per account, sorted in ascending time order. * These are the times at which each given quantity of SNX vests. */ mapping(address => uint[2][]) public vestingSchedules; /* An account's total escrowed synthetix balance to save recomputing this for fee extraction purposes. */ mapping(address => uint) public totalEscrowedAccountBalance; /* An account's total vested reward synthetix. */ mapping(address => uint) public totalVestedAccountBalance; /* The total remaining escrowed balance, for verifying the actual synthetix balance of this contract against. */ uint public totalEscrowedBalance; uint constant TIME_INDEX = 0; uint constant QUANTITY_INDEX = 1; /* Limit vesting entries to disallow unbounded iteration over vesting schedules. * There are 5 years of the supply scedule */ uint constant public MAX_VESTING_ENTRIES = 52*5; /* ========== CONSTRUCTOR ========== */ constructor(address _owner, ISynthetix _synthetix, IFeePool _feePool) Owned(_owner) public { synthetix = _synthetix; feePool = _feePool; } /* ========== SETTERS ========== */ /** * @notice set the synthetix contract address as we need to transfer SNX when the user vests */ function setSynthetix(ISynthetix _synthetix) external onlyOwner { synthetix = _synthetix; emit SynthetixUpdated(_synthetix); } /** * @notice set the FeePool contract as it is the only authority to be able to call * appendVestingEntry with the onlyFeePool modifer */ function setFeePool(IFeePool _feePool) external onlyOwner { feePool = _feePool; emit FeePoolUpdated(_feePool); } /* ========== VIEW FUNCTIONS ========== */ /** * @notice A simple alias to totalEscrowedAccountBalance: provides ERC20 balance integration. */ function balanceOf(address account) public view returns (uint) { return totalEscrowedAccountBalance[account]; } /** * @notice The number of vesting dates in an account's schedule. */ function numVestingEntries(address account) public view returns (uint) { return vestingSchedules[account].length; } /** * @notice Get a particular schedule entry for an account. * @return A pair of uints: (timestamp, synthetix quantity). */ function getVestingScheduleEntry(address account, uint index) public view returns (uint[2]) { return vestingSchedules[account][index]; } /** * @notice Get the time at which a given schedule entry will vest. */ function getVestingTime(address account, uint index) public view returns (uint) { return getVestingScheduleEntry(account,index)[TIME_INDEX]; } /** * @notice Get the quantity of SNX associated with a given schedule entry. */ function getVestingQuantity(address account, uint index) public view returns (uint) { return getVestingScheduleEntry(account,index)[QUANTITY_INDEX]; } /** * @notice Obtain the index of the next schedule entry that will vest for a given user. */ function getNextVestingIndex(address account) public view returns (uint) { uint len = numVestingEntries(account); for (uint i = 0; i < len; i++) { if (getVestingTime(account, i) != 0) { return i; } } return len; } /** * @notice Obtain the next schedule entry that will vest for a given user. * @return A pair of uints: (timestamp, synthetix quantity). */ function getNextVestingEntry(address account) public view returns (uint[2]) { uint index = getNextVestingIndex(account); if (index == numVestingEntries(account)) { return [uint(0), 0]; } return getVestingScheduleEntry(account, index); } /** * @notice Obtain the time at which the next schedule entry will vest for a given user. */ function getNextVestingTime(address account) external view returns (uint) { return getNextVestingEntry(account)[TIME_INDEX]; } /** * @notice Obtain the quantity which the next schedule entry will vest for a given user. */ function getNextVestingQuantity(address account) external view returns (uint) { return getNextVestingEntry(account)[QUANTITY_INDEX]; } /** * @notice return the full vesting schedule entries vest for a given user. */ function checkAccountSchedule(address account) public view returns (uint[520]) { uint[520] memory _result; uint schedules = numVestingEntries(account); for (uint i = 0; i < schedules; i++) { uint[2] memory pair = getVestingScheduleEntry(account, i); _result[i*2] = pair[0]; _result[i*2 + 1] = pair[1]; } return _result; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Add a new vesting entry at a given time and quantity to an account's schedule. * @dev A call to this should accompany a previous successfull call to synthetix.transfer(tewardEscrow, amount), * to ensure that when the funds are withdrawn, there is enough balance. * Note; although this function could technically be used to produce unbounded * arrays, it's only withinn the 4 year period of the weekly inflation schedule. * @param account The account to append a new vesting entry to. * @param quantity The quantity of SNX that will be escrowed. */ function appendVestingEntry(address account, uint quantity) public onlyFeePool { /* No empty or already-passed vesting entries allowed. */ require(quantity != 0, "Quantity cannot be zero"); /* There must be enough balance in the contract to provide for the vesting entry. */ totalEscrowedBalance = totalEscrowedBalance.add(quantity); require(totalEscrowedBalance <= synthetix.balanceOf(this), "Must be enough balance in the contract to provide for the vesting entry"); /* Disallow arbitrarily long vesting schedules in light of the gas limit. */ uint scheduleLength = vestingSchedules[account].length; require(scheduleLength <= MAX_VESTING_ENTRIES, "Vesting schedule is too long"); /* Escrow the tokens for 1 year. */ uint time = now + 52 weeks; if (scheduleLength == 0) { totalEscrowedAccountBalance[account] = quantity; } else { /* Disallow adding new vested SNX earlier than the last one. * Since entries are only appended, this means that no vesting date can be repeated. */ require(getVestingTime(account, numVestingEntries(account) - 1) < time, "Cannot add new vested entries earlier than the last one"); totalEscrowedAccountBalance[account] = totalEscrowedAccountBalance[account].add(quantity); } vestingSchedules[account].push([time, quantity]); emit VestingEntryCreated(account, now, quantity); } /** * @notice Allow a user to withdraw any SNX in their schedule that have vested. */ function vest() external { uint numEntries = numVestingEntries(msg.sender); uint total; for (uint i = 0; i < numEntries; i++) { uint time = getVestingTime(msg.sender, i); /* The list is sorted; when we reach the first future time, bail out. */ if (time > now) { break; } uint qty = getVestingQuantity(msg.sender, i); if (qty == 0) { continue; } vestingSchedules[msg.sender][i] = [0, 0]; total = total.add(qty); } if (total != 0) { totalEscrowedBalance = totalEscrowedBalance.sub(total); totalEscrowedAccountBalance[msg.sender] = totalEscrowedAccountBalance[msg.sender].sub(total); totalVestedAccountBalance[msg.sender] = totalVestedAccountBalance[msg.sender].add(total); synthetix.transfer(msg.sender, total); emit Vested(msg.sender, now, total); } } /* ========== MODIFIERS ========== */ modifier onlyFeePool() { bool isFeePool = msg.sender == address(feePool); require(isFeePool, "Only the FeePool contracts can perform this action"); _; } /* ========== EVENTS ========== */ event SynthetixUpdated(address newSynthetix); event FeePoolUpdated(address newFeePool); event Vested(address indexed beneficiary, uint time, uint value); event VestingEntryCreated(address indexed beneficiary, uint time, uint value); }
* @return The result of safely dividing x and y. The return value is as a rounded decimal in the precision unit specified in the parameter. @dev y is divided after the product of x and the specified precision unit is evaluated, so the product of x and the specified precision unit must be less than 2256. The result is rounded to the nearest increment./
function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; }
1,027,961
[ 1, 2463, 1021, 563, 434, 15303, 3739, 10415, 619, 471, 677, 18, 1021, 327, 460, 353, 487, 279, 16729, 6970, 316, 326, 6039, 2836, 1269, 316, 326, 1569, 18, 225, 677, 353, 26057, 1839, 326, 3017, 434, 619, 471, 326, 1269, 6039, 2836, 353, 12697, 16, 1427, 326, 3017, 434, 619, 471, 326, 1269, 6039, 2836, 1297, 506, 5242, 2353, 576, 5034, 18, 1021, 563, 353, 16729, 358, 326, 11431, 5504, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2892, 831, 5749, 11066, 12, 11890, 619, 16, 2254, 677, 16, 2254, 6039, 2802, 13, 203, 3639, 3238, 203, 3639, 16618, 203, 3639, 1135, 261, 11890, 13, 203, 565, 288, 203, 3639, 2254, 563, 10694, 25601, 273, 619, 18, 16411, 12, 14548, 2802, 380, 1728, 2934, 2892, 12, 93, 1769, 203, 203, 3639, 309, 261, 2088, 10694, 25601, 738, 1728, 1545, 1381, 13, 288, 203, 5411, 563, 10694, 25601, 1011, 1728, 31, 203, 3639, 289, 203, 203, 3639, 327, 563, 10694, 25601, 342, 1728, 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 ]
./full_match/11155111/0xBCd79bb256cA2FB714B7640460f719af43a0c117/sources/project:/contracts/TokenStorageLib.sol
@title TokenStorageLib @dev Implementation of an[external storage for tokens./
library TokenStorageLib { struct TokenStorage { mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; uint256 totalSupply; } function addBalance( TokenStorage storage self, address to, uint256 amount ) external { self.totalSupply = self.totalSupply + amount; self.balances[to] = self.balances[to] + amount; } function subBalance( TokenStorage storage self, address from, uint256 amount ) external { self.totalSupply = self.totalSupply - amount; self.balances[from] = self.balances[from] - amount; } function setAllowed( TokenStorage storage self, address owner, address spender, uint256 amount ) external { self.allowed[owner][spender] = amount; } function getSupply(TokenStorage storage self) external view returns (uint) { return self.totalSupply; } function getBalance( TokenStorage storage self, address who ) external view returns (uint) { return self.balances[who]; } function getAllowed( TokenStorage storage self, address owner, address spender ) external view returns (uint) { return self.allowed[owner][spender]; } }
3,824,979
[ 1, 1345, 3245, 5664, 225, 25379, 434, 392, 63, 9375, 2502, 364, 2430, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3155, 3245, 5664, 288, 203, 203, 565, 1958, 3155, 3245, 288, 203, 3639, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 3639, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 3639, 2254, 5034, 2078, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 527, 13937, 12, 203, 3639, 3155, 3245, 2502, 365, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 3903, 288, 203, 3639, 365, 18, 4963, 3088, 1283, 273, 365, 18, 4963, 3088, 1283, 397, 3844, 31, 203, 3639, 365, 18, 70, 26488, 63, 869, 65, 273, 365, 18, 70, 26488, 63, 869, 65, 397, 3844, 31, 203, 565, 289, 203, 203, 565, 445, 720, 13937, 12, 203, 3639, 3155, 3245, 2502, 365, 16, 203, 3639, 1758, 628, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 3903, 288, 203, 3639, 365, 18, 4963, 3088, 1283, 273, 365, 18, 4963, 3088, 1283, 300, 3844, 31, 203, 3639, 365, 18, 70, 26488, 63, 2080, 65, 273, 365, 18, 70, 26488, 63, 2080, 65, 300, 3844, 31, 203, 565, 289, 203, 203, 565, 445, 14252, 12, 203, 3639, 3155, 3245, 2502, 365, 16, 203, 3639, 1758, 3410, 16, 203, 3639, 1758, 17571, 264, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 3903, 288, 203, 3639, 365, 18, 8151, 63, 8443, 6362, 87, 1302, 264, 65, 273, 3844, 31, 203, 565, 289, 203, 203, 565, 445, 10755, 1283, 12, 1345, 3245, 2502, 365, 13, 3903, 1476, 1135, 261, 11890, 13, 2 ]
// Pulled in from Cryptofin Solidity package in order to control Solidity compiler version // https://github.com/cryptofinlabs/cryptofin-solidity/blob/master/contracts/array-utils/AddressArrayUtils.sol pragma solidity 0.5.7; library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (0, false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { bool isIn; (, isIn) = indexOf(A, a); return isIn; } /// @return Returns index and isIn for the first occurrence starting from /// end function indexOfFromEnd(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = length; i > 0; i--) { if (A[i - 1] == a) { return (i, true); } } return (0, false); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Returns the array with a appended to A. * @param A The first array * @param a The value to append * @return Returns A appended by a */ function append(address[] memory A, address a) internal pure returns (address[] memory) { address[] memory newAddresses = new address[](A.length + 1); for (uint256 i = 0; i < A.length; i++) { newAddresses[i] = A[i]; } newAddresses[A.length] = a; return newAddresses; } /** * Returns the combination of two storage arrays. * @param A The first array * @param B The second array * @return Returns A appended by a */ function sExtend(address[] storage A, address[] storage B) internal { uint256 length = B.length; for (uint256 i = 0; i < length; i++) { A.push(B[i]); } } /** * Returns the intersection of two arrays. Arrays are treated as collections, so duplicates are kept. * @param A The first array * @param B The second array * @return The intersection of the two arrays */ function intersect(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 newLength = 0; for (uint256 i = 0; i < length; i++) { if (contains(B, A[i])) { includeMap[i] = true; newLength++; } } address[] memory newAddresses = new address[](newLength); uint256 j = 0; for (uint256 k = 0; k < length; k++) { if (includeMap[k]) { newAddresses[j] = A[k]; j++; } } return newAddresses; } /** * Returns the union of the two arrays. Order is not guaranteed. * @param A The first array * @param B The second array * @return The union of the two arrays */ function union(address[] memory A, address[] memory B) internal pure returns (address[] memory) { address[] memory leftDifference = difference(A, B); address[] memory rightDifference = difference(B, A); address[] memory intersection = intersect(A, B); return extend(leftDifference, extend(intersection, rightDifference)); } /** * Alternate implementation * Assumes there are no duplicates */ function unionB(address[] memory A, address[] memory B) internal pure returns (address[] memory) { bool[] memory includeMap = new bool[](A.length + B.length); uint256 count = 0; for (uint256 i = 0; i < A.length; i++) { includeMap[i] = true; count++; } for (uint256 j = 0; j < B.length; j++) { if (!contains(A, B[j])) { includeMap[A.length + j] = true; count++; } } address[] memory newAddresses = new address[](count); uint256 k = 0; for (uint256 m = 0; m < A.length; m++) { if (includeMap[m]) { newAddresses[k] = A[m]; k++; } } for (uint256 n = 0; n < B.length; n++) { if (includeMap[A.length + n]) { newAddresses[k] = B[n]; k++; } } return newAddresses; } /** * Computes the difference of two arrays. Assumes there are no duplicates. * @param A The first array * @param B The second array * @return The difference of the two arrays */ function difference(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 count = 0; // First count the new length because can't push for in-memory arrays for (uint256 i = 0; i < length; i++) { address e = A[i]; if (!contains(B, e)) { includeMap[i] = true; count++; } } address[] memory newAddresses = new address[](count); uint256 j = 0; for (uint256 k = 0; k < length; k++) { if (includeMap[k]) { newAddresses[j] = A[k]; j++; } } return newAddresses; } /** * @dev Reverses storage array in place */ function sReverse(address[] storage A) internal { address t; uint256 length = A.length; for (uint256 i = 0; i < length / 2; i++) { t = A[i]; A[i] = A[A.length - i - 1]; A[A.length - i - 1] = t; } } /** * Removes specified index from array * Resulting ordering is not guaranteed * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * @return Returns the new array */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert(); } else { (address[] memory _A,) = pop(A, index); return _A; } } function sPop(address[] storage A, uint256 index) internal returns (address) { uint256 length = A.length; if (index >= length) { revert("Error: index out of bounds"); } address entry = A[index]; for (uint256 i = index; i < length - 1; i++) { A[i] = A[i + 1]; } A.length--; return entry; } /** * Deletes address at index and fills the spot with the last address. * Order is not preserved. * @return Returns the removed entry */ function sPopCheap(address[] storage A, uint256 index) internal returns (address) { uint256 length = A.length; if (index >= length) { revert("Error: index out of bounds"); } address entry = A[index]; if (index != length - 1) { A[index] = A[length - 1]; delete A[length - 1]; } A.length--; return entry; } /** * Deletes address at index. Works by swapping it with the last address, then deleting. * Order is not preserved * @param A Storage array to remove from */ function sRemoveCheap(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Error: entry not found"); } else { sPopCheap(A, index); return; } } /** * Returns whether or not there's a duplicate. Runs in O(n^2). * @param A Array to search * @return Returns true if duplicate, false otherwise */ function hasDuplicate(address[] memory A) internal pure returns (bool) { if (A.length == 0) { return false; } for (uint256 i = 0; i < A.length - 1; i++) { for (uint256 j = i + 1; j < A.length; j++) { if (A[i] == A[j]) { return true; } } } return false; } /** * Returns whether the two arrays are equal. * @param A The first array * @param B The second array * @return True is the arrays are equal, false if not. */ function isEqual(address[] memory A, address[] memory B) internal pure returns (bool) { if (A.length != B.length) { return false; } for (uint256 i = 0; i < A.length; i++) { if (A[i] != B[i]) { return false; } } return true; } /** * Returns the elements indexed at indexArray. * @param A The array to index * @param indexArray The array to use to index * @return Returns array containing elements indexed at indexArray */ function argGet(address[] memory A, uint256[] memory indexArray) internal pure returns (address[] memory) { address[] memory array = new address[](indexArray.length); for (uint256 i = 0; i < indexArray.length; i++) { array[i] = A[indexArray[i]]; } return array; } }
* @dev Reverses storage array in place/
function sReverse(address[] storage A) internal { address t; uint256 length = A.length; for (uint256 i = 0; i < length / 2; i++) { t = A[i]; A[i] = A[A.length - i - 1]; A[A.length - i - 1] = t; } }
1,041,813
[ 1, 426, 2496, 281, 2502, 526, 316, 3166, 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, 272, 12650, 12, 2867, 8526, 2502, 432, 13, 2713, 288, 203, 3639, 1758, 268, 31, 203, 3639, 2254, 5034, 769, 273, 432, 18, 2469, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 769, 342, 576, 31, 277, 27245, 288, 203, 5411, 268, 273, 432, 63, 77, 15533, 203, 5411, 432, 63, 77, 65, 273, 432, 63, 37, 18, 2469, 300, 277, 300, 404, 15533, 203, 5411, 432, 63, 37, 18, 2469, 300, 277, 300, 404, 65, 273, 268, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.10; library SafeMath { 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); } } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } 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); } } function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } 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 (bytes32 ); function symbol() external pure returns (bytes32 ); 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; } // IVC (Internal Virtual Chain) // (c) Kaiba DeFi DAO 2021 // This source code is distributed under the CC-BY-ND-4.0 License https://spdx.org/licenses/CC-BY-ND-4.0.html#licenseText interface ERC20 { function totalSupply() external view returns (uint); function balanceOf(address tokenOwner) external view returns (uint balance); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function transfer(address to, uint tokens) external returns (bool success); function approve(address spender, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); function symbol() external view returns (bytes32 ); function name() external view returns (bytes32 ); function decimals() external view returns (uint8); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } /////////////////////////////////////////////////////// Plugin interface interface IVC_Plugin { // pay extreme attention to these methods function exists() external view returns (bool success); function svt_method_call_id(uint256 mid) external returns (bool, bytes32 ); function svt_method_call_name(bytes32 mname) external returns (bool, bytes32 ); } contract Kaiba_IVC { using SafeMath for uint256; /// @notice Fees balances uint256 tax_multiplier = 995; //0.05% uint256 taxes_eth_total; mapping(address => uint256) taxes_token_total; mapping (uint256 => uint256) taxes_native_total; address kaiba_address = 0x8BB048845Ee0d75BE8e07954b2e1E5b51B64b442; address owner; // Rinkeby: 0xc778417E063141139Fce010982780140Aa0cD5Ab // Mainnet: 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 address constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address constant ZERO = 0x000000000000000000000000000000000000dEaD; ERC20 kaiba = ERC20(kaiba_address); // Constructor constructor () { is_team[msg.sender] = true; owner = msg.sender; is_locked[841] = true; is_locked[471] = true; /// @notice defining WETH -> KVETH SVT_address[0].deployed = true; SVT_address[0].tokenOwner = owner; SVT_address[0].totalSupply = 0; SVT_address[0].circulatingSupply = 0; SVT_address[0].name = "Kaiba Virtual ETH"; SVT_address[0].ticker = "WETH"; SVT_address[0].isBridged = true; SVT_address[0].original_token = WETH; SVT_address[0].SVT_Liquidity_storage = 0; /// @notice also defining the liquidity SVT_Liquidity_index[0].deployed = true; SVT_Liquidity_index[0].active = true; SVT_Liquidity_index[0].liq_mode = 4; SVT_Liquidity_index[0].token_1 = ERC20(SVT_address[0].original_token); SVT_Liquidity_index[0].SVT_token_id = 0; } /////////////////////////////////////////////////////// Access control /// @notice this part defines plugins that can access to editing methods. Be careful mapping(address => bool) has_access; mapping(address => mapping(uint256 => bool)) has_access_to; mapping (address => bool) is_team; struct auth_control { mapping(address => bool) is_auth; } mapping(address => auth_control) bridge_is_auth; mapping(uint256 => bool) is_locked; bool internal locked; bool internal open_bridge; modifier can_access(uint256 specific) { if(specific==0) { require(has_access[msg.sender], "Not authorized"); } else { require(has_access_to[msg.sender][specific], "Not authorized"); } _; } modifier safe() { require(!locked, "No re-entrancy"); locked = true; _; locked = false; } modifier Unlocked(uint256 name) { require(!is_locked[name]); _; } modifier onlyAuth(address to_bridge) { require(bridge_is_auth[msg.sender].is_auth[to_bridge] || msg.sender==owner || open_bridge, "Not authorized"); _; } modifier onlyTeam { require(is_team[msg.sender]); _; } function acl_check_access(uint256 specific) public view returns(bool) { if(specific==0) { return has_access[msg.sender]; } else { return has_access_to[msg.sender][specific]; } } function acl_give_access(address addy, bool booly) public onlyTeam { has_access[addy] = booly; } function acl_give_specific_access(address addy, uint256 specific, bool booly) public onlyTeam { has_access_to[addy][specific] = booly; } function acl_add_team(address addy) public onlyTeam { is_team[addy] = true; } function acl_remove_team(address addy) public onlyTeam { is_team[addy] = false; } function acl_locked_function(uint256 name, bool booly) public onlyTeam { is_locked[name] = booly; } function acl_open_bridge(bool booly) public onlyTeam { open_bridge = booly; } function acl_set_kaiba(address addy) public onlyTeam { kaiba_address = addy; } function acl_set_tax_multiplier(uint256 multiplier) public onlyTeam { tax_multiplier = multiplier; } /////////////////////////////////////////////////////// Structures struct SVTLiquidity { // This struct defines the types of liquidity and the relative properties bool active; bool deployed; bool native_pair; ERC20 token_1; // Always the SVT token ERC20 token_2; // Always the native or the paired uint256 token_1_qty; uint256 token_2_qty; uint256 SVT_token_id; uint256 liq_mode; // 1: Direct pair, 2: synthetic, 3: native, 4: WETH // Mode specific variables IUniswapV2Pair pair; // Needed in mode 2, 3 uint256 token_2_native; } mapping (uint256 => SVTLiquidity) SVT_Liquidity_index; uint256 svt_liquidity_last_id = 0; struct SVT { // This struct defines a typical SVT token bool deployed; bool is_svt_native; bool is_synthetic; string balance_url; address tokenOwner; uint256 totalSupply; uint256 circulatingSupply; mapping (address => uint256) balance; uint256[] fees; mapping(uint256 => uint256) fees_storage; bytes32 name; bytes32 ticker; bool isBridged; address original_token; address pair_address; uint256 SVT_Liquidity_storage; mapping(address => bool) synthesis_control; } mapping (uint256 => SVT) SVT_address; uint256 svt_last_id = 0; /// @notice Manage the imported status of ERC20 tokens mapping (address => bool) imported; mapping (address => uint256) imported_id; struct pairs_for_token { address token_address; mapping(address => bool) paired_with; } mapping (bytes32 => bool) liquidity; /// @notice Tracking imported balances of IVC addresses mapping (address => uint256) IVC_native_balance; uint256 IVC_native_balance_total; /////////////////////////////////////////////////////// Access endpoints function modify_address_balance(bool native, uint256 svt_id, address addy, uint256 ending) public can_access(0) { if(native) { IVC_native_balance[addy] = ending; SVT_address[0].balance[addy] = ending; } else { SVT_address[svt_id].balance[addy] = ending; } } function modify_update_pair(uint256 svt_liq_id, uint256 tkn_1_qty, uint256 tkn_2_qty, address tkn_1, address tkn_2) public can_access(0) { if(tkn_2 == WETH) { SVT_Liquidity_index[svt_liq_id].native_pair = true; } else { SVT_Liquidity_index[svt_liq_id].native_pair = false; } SVT_Liquidity_index[svt_liq_id].token_1 =ERC20(tkn_1); // Always the SVT token SVT_Liquidity_index[svt_liq_id].token_2 =ERC20(tkn_2); SVT_Liquidity_index[svt_liq_id].token_1_qty = tkn_1_qty; SVT_Liquidity_index[svt_liq_id].token_2_qty = tkn_2_qty; } /////////////////////////////////////////////////////// Get endpoints // List of deployed tokens function get_svt_pools() external view returns (uint256) { return svt_last_id; } // Address to SVT id function get_svt_id(address addy) external view returns(bool, uint256) { if(imported[addy]) { return (true, imported_id[addy]); } else { return (false, 0); } } // Get the internal liquidity of a SVT token function get_svt_liquidity(uint256 svt_id) external view returns (bool, bool, address, address, uint256, uint256, uint256, address, uint256, bool) { require(SVT_address[svt_id].deployed, "SVT Token does not exist"); require(!SVT_address[svt_id].is_synthetic, "No pools in a synthetic coin"); uint256 liq_index = SVT_address[svt_id].SVT_Liquidity_storage; require(SVT_Liquidity_index[liq_index].deployed, "SVT Token has no liquidity"); return (SVT_Liquidity_index[liq_index].active, SVT_Liquidity_index[liq_index].deployed, address(SVT_Liquidity_index[liq_index].token_1), address(SVT_Liquidity_index[liq_index].token_2), SVT_Liquidity_index[liq_index].token_1_qty, SVT_Liquidity_index[liq_index].token_2_qty, SVT_Liquidity_index[liq_index].liq_mode, address(SVT_Liquidity_index[liq_index].pair), 0, SVT_Liquidity_index[liq_index].native_pair); } function get_synthetic_svt_liquidity(uint256 svt_id) external view returns (address, address, uint256, uint256) { require(SVT_address[svt_id].deployed, "SVT Token does not exist"); require(SVT_address[svt_id].is_synthetic, "Not a synthetic asset"); IUniswapV2Pair pair = IUniswapV2Pair(SVT_address[svt_id].pair_address); address token0_frompair = pair.token0(); address token1_frompair = pair.token1(); (uint Res0, uint Res1,) = pair.getReserves(); return(token0_frompair, token1_frompair, Res0, Res1); } // Get the price of a token in eth function get_token_price(address pairAddress, uint amount) external view returns(uint) { IUniswapV2Pair pair = IUniswapV2Pair(pairAddress); address token1_frompair = pair.token1(); ERC20 token1 = ERC20(token1_frompair); (uint Res0, uint Res1,) = pair.getReserves(); // decimals uint res0 = Res0*(10**token1.decimals()); return((amount*res0)/Res1); // return amount of token0 needed to buy token1 } // Return the SVT balance of an address function get_svt_address_balance(address addy, uint256 svt_id) public view returns(uint256) { require(SVT_address[svt_id].deployed, "This token does not exists"); return SVT_address[svt_id].balance[addy]; } // Return the IVC balance of an address function get_ivc_balance(address addy) public view returns(uint256) { return(IVC_native_balance[addy]); } function get_ivc_stats() external view returns(uint256) { return(IVC_native_balance_total); } // Return the properties of a SVT token function get_svt(uint256 addy) external view returns (address, uint256, uint256, uint256[] memory, bytes32 , bytes32 ) { require(SVT_address[addy].deployed, "Token not deployed"); address tokenOwner = SVT_address[addy].tokenOwner; uint256 supply = SVT_address[addy].totalSupply; uint256 circulatingSupply = SVT_address[addy].circulatingSupply; uint256[] memory fees = SVT_address[addy].fees; bytes32 name = SVT_address[addy].name; bytes32 ticker = SVT_address[addy].ticker; return (tokenOwner, supply, circulatingSupply, fees, name, ticker); } // Return bridged status of a SVT token function get_svt_bridge_status(uint256 addy) external view returns (bool, address) { return(SVT_address[addy].isBridged, SVT_address[addy].original_token); } // Return KVETH balance of an address function get_svt_kveth_balance(address addy) external view returns (uint256) { return(IVC_native_balance[addy]); } ///////////////////////////////////////////////////// // Transfer functions function operate_mass_synthetic_update(uint256 svt_id, string calldata url) public can_access(1) { require(SVT_address[svt_id].deployed, "No assets"); require(SVT_address[svt_id].is_synthetic, "No synthetic"); require(SVT_address[svt_id].synthesis_control[msg.sender], "Denied"); SVT_address[svt_id].balance_url = url; } function operate_delegated_synthetic_retrieve(address to, uint256 svt_id, uint256 qty, uint256 delegated_balance, address main_reserve) public can_access(1) { require(SVT_address[svt_id].deployed, "No assets"); require(SVT_address[svt_id].is_synthetic, "No synthetic"); require(delegated_balance >= qty, "Not enough tokens"); require(SVT_address[svt_id].synthesis_control[msg.sender], "Denied"); ERC20 on_main = ERC20(SVT_address[svt_id].original_token); require(on_main.balanceOf(SVT_address[svt_id].original_token) >= qty, "Not enough tokens on mainnet"); require(on_main.allowance(main_reserve, address(this)) >= qty, "Allowance too low"); on_main.transferFrom(main_reserve, to, qty); } function operate_tx_swap(uint256 svt_id, uint256 qty, address receiver, uint256 direction) public safe returns (uint256, uint256, uint256, uint256) { uint256 to_deposit_liq; uint256 to_withdraw_liq; /// @notice Sanity checks require(SVT_address[svt_id].deployed, "SVT token does not exist"); uint256 liq_index = SVT_address[svt_id].SVT_Liquidity_storage; require(SVT_Liquidity_index[liq_index].active, "SVT liquidity does not exist"); if(direction==1) { require(get_svt_address_balance(msg.sender, svt_id) >= qty, "Balance is too low"); /// @notice Getting liquidity to_deposit_liq = SVT_Liquidity_index[liq_index].token_1_qty; to_withdraw_liq = SVT_Liquidity_index[liq_index].token_2_qty; } else { require(IVC_native_balance[msg.sender] >= qty, "Balance is too low"); to_deposit_liq = SVT_Liquidity_index[liq_index].token_2_qty; to_withdraw_liq = SVT_Liquidity_index[liq_index].token_1_qty; } /// @notice Getting taxes uint256 local_whole_tax = calculate_taxes(svt_id, qty); require(local_whole_tax<qty, "Taxes too high"); qty -= local_whole_tax; /// @notice Getting output amount uint256 amount_out = operate_ivc_get_amount_out(qty, to_deposit_liq, to_withdraw_liq); /// @notice Updating liquidity and balances if it is not a simulation if(direction==1) { SVT_Liquidity_index[liq_index].token_1_qty += qty; SVT_address[svt_id].balance[msg.sender] -= qty; SVT_Liquidity_index[liq_index].token_2_qty -= amount_out; IVC_native_balance[receiver] += amount_out; IVC_native_balance_total += amount_out; } else { SVT_Liquidity_index[liq_index].token_1_qty -= amount_out; SVT_address[svt_id].balance[receiver] += amount_out; SVT_Liquidity_index[liq_index].token_2_qty += qty; IVC_native_balance[msg.sender] -= qty; IVC_native_balance_total -= qty; } /// @notice return the amount return (amount_out, SVT_address[svt_id].balance[receiver], IVC_native_balance[msg.sender], svt_id); } function simulate_tx_swap(uint256 svt_id, uint256 qty, uint8 direction) public view returns (uint256) { /// @notice Sanity checks require(SVT_address[svt_id].deployed, "SVT token does not exist"); uint256 liq_index = SVT_address[svt_id].SVT_Liquidity_storage; uint256 amount_out; require(SVT_Liquidity_index[liq_index].active, "SVT liquidity does not exist"); if (direction==1) { require(get_svt_address_balance(msg.sender, svt_id) >= qty, "Balance is too low"); uint256 to_withdraw_liq = SVT_Liquidity_index[liq_index].token_2_qty; uint256 to_deposit_liq = SVT_Liquidity_index[liq_index].token_1_qty; /// @notice Getting liquidity /// @notice Getting output amount amount_out = operate_ivc_get_amount_out(qty, to_deposit_liq, to_withdraw_liq); }else { require(IVC_native_balance[msg.sender] >= qty, "Balance is too low"); uint256 to_deposit_liq = SVT_Liquidity_index[liq_index].token_2_qty; uint256 to_withdraw_liq = SVT_Liquidity_index[liq_index].token_1_qty; /// @notice Getting liquidity /// @notice Getting output amount amount_out = operate_ivc_get_amount_out(qty, to_deposit_liq, to_withdraw_liq); } /// @notice Updating liquidity and balances if it is not a simulation /// @notice return the amount return amount_out; } /////////////////////////////////////////////////////// Entry and exit point functions uint256 exit_lock_time = 5 minutes; uint256 entry_lock_time = 2 minutes; mapping(address => bool) exit_suspended; mapping(address => bool) entry_suspended; mapping(address => uint256) exit_lock; mapping(address => uint256) entry_lock; function entry_from_eth() public payable safe returns (uint256){ require(msg.value >= 10000000000000000, "Unpayable"); require(!entry_suspended[msg.sender], "Suspended"); require(entry_lock[msg.sender] + entry_lock_time < block.timestamp, "Please wait"); uint256 qty_to_credit = msg.value; SVT_address[0].balance[msg.sender] += taxes_include_fee(qty_to_credit); IVC_native_balance[msg.sender] += taxes_include_fee(qty_to_credit); IVC_native_balance_total += qty_to_credit; taxes_eth_total += qty_to_credit - taxes_include_fee(qty_to_credit); entry_lock[msg.sender] = block.timestamp; return qty_to_credit; } function exit_to_eth(uint256 qty, address recv) public safe returns (uint256) { require(address(this).balance > qty, "Unpayable: No liq?"); require(IVC_native_balance[msg.sender] >= qty, "No KVETH"); require(SVT_address[0].balance[msg.sender] >= qty, "No KVETH"); require(!exit_suspended[msg.sender], "Suspended"); require(!exit_suspended[recv], "Suspended"); require(exit_lock[msg.sender] + exit_lock_time < block.timestamp, "Please wait"); require(exit_lock[recv] + exit_lock_time < block.timestamp, "Please wait"); exit_lock[msg.sender] = block.timestamp; IVC_native_balance[msg.sender] -= qty; IVC_native_balance_total -= taxes_include_fee(qty); SVT_address[0].balance[msg.sender] -= qty; payable(recv).transfer(taxes_include_fee(qty)); taxes_native_total[0] += qty - taxes_include_fee(qty); return qty; } /// @notice Unbridge to ETH a quantity of SVT token function exit_to_token(address token, uint256 qty) public safe { ERC20 from_token = ERC20(token); // Security and uniqueness checks require(imported[token], "This token is not imported"); uint256 unbridge_id = imported_id[token]; require(SVT_address[unbridge_id].balance[msg.sender] >= qty, "You don't have enough tokens"); require(from_token.balanceOf(address(this)) >= qty, "There aren't enough tokens"); from_token.transfer(msg.sender, taxes_include_fee(qty)); if (SVT_address[unbridge_id].circulatingSupply < 0) { SVT_address[unbridge_id].circulatingSupply = 0; } SVT_address[unbridge_id].balance[msg.sender] -= qty; taxes_native_total[unbridge_id] += qty - taxes_include_fee(qty); } /////////////////////////////////////////////////////// Public functions function operate_transfer_svt(uint256 svt_id, address sender, address receiver, uint256 qty) public { require(SVT_address[svt_id].deployed, "This token does not exists"); require(SVT_address[svt_id].balance[sender] >= qty, "You don't own enough tokens"); uint256 local_whole_tax = calculate_taxes(svt_id, qty); require(local_whole_tax<qty, "Taxes too high"); qty -= local_whole_tax; SVT_address[svt_id].balance[sender] -= taxes_include_fee(qty) ; delete sender; SVT_address[svt_id].balance[receiver] += taxes_include_fee(qty); delete receiver; delete qty; taxes_native_total[svt_id] += taxes_include_fee(qty); } /////////////////////////////////////////////////////// Plugins functions mapping(uint256 => IVC_Plugin) plugin_loaded; uint256 plugin_free_id = 0; mapping(uint256 => uint256[]) plugins_methods_id; mapping(uint256 => bytes32[]) plugins_methods_strings; function add_svt_plugin(address plugin_address) public onlyTeam returns (uint256){ plugin_loaded[plugin_free_id] = IVC_Plugin(plugin_address); plugin_free_id += 1; return (plugin_free_id -1); } /// @notice The next two functions are responsible to check against the initialized plugin methods ids or names. Require is used to avoid tx execution with gas if fails function check_ivc_plugin_method_id(uint256 plugin, uint256 id) public view onlyTeam returns (bool) { require(plugin_loaded[plugin].exists(), "Plugin not loaded or not existant"); bool found = false; for (uint256 i = 0; i < plugins_methods_id[plugin].length; i++) { if (plugins_methods_id[plugin][i] == id) { return true; } } require(found); return false; } function check_ivc_plugin_method_name(uint256 plugin, bytes32 name) public view onlyTeam returns (bool) { require(plugin_loaded[plugin].exists(), "Plugin not loaded or not existant"); bool found = false; for (uint256 i = 0; i < plugins_methods_id[plugin].length; i++) { if (plugins_methods_strings[plugin][i] == name) { return true; } } require(found); return false; } /// @notice The following methods are able to call either a method id or method name from a given plugin function execute_ivc_plugin_method_id(uint256 plugin, uint256 id) public onlyTeam returns (bool, bytes32 ) { require(check_ivc_plugin_method_id(plugin, id), "Error in verifying method"); return plugin_loaded[plugin].svt_method_call_id(id); } function execute_ivc_plugin_method_id(uint256 plugin, bytes32 name) public onlyTeam returns (bool, bytes32 ) { require(check_ivc_plugin_method_name(plugin, name), "Error in verifying method"); return plugin_loaded[plugin].svt_method_call_name(name); } /////////////////////////////////////////////////////// Utility functions function taxes_include_fee(uint256 initial) private view returns (uint256) { return( (initial*tax_multiplier) / 1000 ); } function calculate_taxes(uint256 svt_id, uint256 qty) private returns (uint256) { uint256 local_whole_tax = 0; for(uint i=0; i<SVT_address[svt_id].fees.length; i++) { SVT_address[svt_id].fees_storage[i] += (qty * SVT_address[svt_id].fees[i])/100; local_whole_tax += (qty * SVT_address[svt_id].fees[i])/100; } return local_whole_tax; } function operate_ivc_get_amount_out(uint256 to_deposit, uint256 to_deposit_liq, uint256 to_withdraw_liq) public pure returns (uint256 out_qty) { require(to_deposit > 0, 'KaibaSwap: INSUFFICIENT_INPUT_AMOUNT'); require(to_deposit_liq > 0 && to_withdraw_liq > 0, 'KaibaSwap: INSUFFICIENT_LIQUIDITY'); uint to_deposit_with_fee = to_deposit.mul(997); uint numerator = to_deposit_with_fee.mul(to_withdraw_liq); uint denominator = to_deposit_liq.mul(1000).add(to_deposit_with_fee); out_qty = numerator / denominator; return out_qty; } /// @notice Authorize a specific address to operate on a token function authorize_on_token(address to_authorize, address to_bridge) public onlyTeam { bridge_is_auth[to_authorize].is_auth[to_bridge] = true; } /// @notice This function allows issuance of native coins function issue_native_svt( bytes32 name, bytes32 ticker, uint256 max_supply, uint256[] calldata fees) public Unlocked(1553) safe { uint256 thisAddress = svt_last_id+1; SVT_address[thisAddress].deployed = true; SVT_address[thisAddress].circulatingSupply = max_supply; SVT_address[thisAddress].totalSupply = max_supply; SVT_address[thisAddress].fees = fees; SVT_address[thisAddress].name = name; SVT_address[thisAddress].ticker = ticker; SVT_address[thisAddress].isBridged = true; SVT_address[thisAddress].original_token = ZERO; SVT_address[thisAddress].balance[msg.sender] = taxes_include_fee(max_supply); SVT_address[thisAddress].SVT_Liquidity_storage = svt_liquidity_last_id + 1; svt_liquidity_last_id += 1; taxes_native_total[thisAddress] += max_supply - taxes_include_fee(max_supply); } function native_add_liq(uint256 svt_id, uint256 qty) payable public safe { require(msg.value > 10000000000000000, "Too low"); require(SVT_address[svt_id].deployed, "SVT does not exists"); uint256 thisLiquidity = SVT_address[svt_id].SVT_Liquidity_storage; require(!SVT_Liquidity_index[thisLiquidity].active, "Pair is already alive"); SVT_Liquidity_index[thisLiquidity].active = true; SVT_Liquidity_index[thisLiquidity].deployed = true; SVT_Liquidity_index[thisLiquidity].token_1 = ERC20(WETH); SVT_Liquidity_index[thisLiquidity].token_2 = ERC20(ZERO); SVT_Liquidity_index[thisLiquidity].token_1_qty += msg.value; SVT_Liquidity_index[thisLiquidity].token_2_qty += qty; SVT_Liquidity_index[thisLiquidity].SVT_token_id = svt_id; SVT_Liquidity_index[thisLiquidity].liq_mode = 1; } /// @notice this returns the url with synthetic balances function get_synthetic_svt_url(uint256 svt_id) public returns (string memory, address, address) { require(SVT_address[svt_id].deployed=true, "No token"); require(SVT_address[svt_id].is_synthetic=true, "No synthesis"); return(SVT_address[svt_id].balance_url, SVT_address[svt_id].pair_address, SVT_address[svt_id].original_token); } /// @notice struct and methods to assign liquidity struct liquidity_owner_stats { mapping(bytes32 => bool) owned; mapping(bytes32 => uint256) qty_1; mapping(bytes32 => uint256) qty_2; } mapping(address => liquidity_owner_stats) liquidity_owned; /// @notice If authorized, allows to pair two ERC20 tokens to an SVT Liquidity Pair /// @dev remember to approve beforehand function create_svt_synthetic(address to_bridge, address pair, string calldata url) public Unlocked(5147) onlyAuth(to_bridge) { require(!imported[to_bridge], "Already synthetized"); svt_last_id +=1; uint256 thisAddress = svt_last_id; imported[to_bridge] = true; imported_id[to_bridge] = thisAddress; SVT_address[thisAddress].deployed = true; SVT_address[thisAddress].totalSupply = ERC20(to_bridge).totalSupply(); SVT_address[thisAddress].circulatingSupply = ERC20(to_bridge).totalSupply(); SVT_address[thisAddress].is_synthetic = true; SVT_address[thisAddress].balance_url = url; SVT_address[thisAddress].original_token = to_bridge; SVT_address[thisAddress].pair_address = pair; SVT_address[thisAddress].name = ERC20(to_bridge).name(); SVT_address[thisAddress].ticker = ERC20(to_bridge).symbol(); } function create_svt_native(bytes32[] calldata strings, uint256[] calldata params, uint256[] calldata fees) public Unlocked(471) returns(uint256, uint256){ svt_last_id += 1; svt_liquidity_last_id += 1; SVT_address[svt_last_id].deployed = true; SVT_address[svt_last_id].is_svt_native = true; SVT_address[svt_last_id].tokenOwner = msg.sender; SVT_address[svt_last_id].totalSupply = params[0]; SVT_address[svt_last_id].circulatingSupply = params[1]; SVT_address[svt_last_id].balance[msg.sender] = params[0]; SVT_address[svt_last_id].fees = fees; SVT_address[svt_last_id].name = strings[0]; SVT_address[svt_last_id].ticker = strings[1]; SVT_address[svt_last_id].SVT_Liquidity_storage = svt_liquidity_last_id; return (svt_last_id, svt_liquidity_last_id); } function create_svt_native_pair(uint256 to_add, uint256 to_bridge, uint256 qty_1, uint256 qty_2) public Unlocked(471) { require(SVT_address[to_add].deployed && SVT_address[to_bridge].deployed, "Missing tokens"); require((SVT_address[to_add].balance[msg.sender] >= qty_1) && (SVT_address[to_bridge].balance[msg.sender] >= qty_2), "Not enough tokens"); uint256 to_add_liq = SVT_address[to_add].SVT_Liquidity_storage; if(!SVT_Liquidity_index[to_add_liq].active) { SVT_Liquidity_index[to_add_liq].active = true; } else { uint256 ratio = (SVT_Liquidity_index[to_add_liq].token_1_qty / SVT_Liquidity_index[to_add_liq].token_2_qty); require((qty_1/qty_2) == ratio, "Wrong ratio"); } SVT_address[to_add].balance[msg.sender] -= qty_1; SVT_address[to_bridge].balance[msg.sender] -= qty_2; SVT_Liquidity_index[to_add_liq].token_1_qty += taxes_include_fee(qty_1); SVT_Liquidity_index[to_add_liq].token_2_qty += taxes_include_fee(qty_2); SVT_address[to_add].balance[owner] += (qty_1 - taxes_include_fee(qty_1)); SVT_address[to_bridge].balance[owner] += (qty_2 - taxes_include_fee(qty_2)); SVT_Liquidity_index[to_add_liq].SVT_token_id = to_add; SVT_Liquidity_index[to_add_liq].token_2_native = to_bridge; SVT_Liquidity_index[to_add_liq].liq_mode = 3; } function create_svt_pair(address to_bridge, address to_pair, uint256 qty_1, uint256 qty_2) public Unlocked(841) onlyAuth(to_bridge) { ERC20 from_token = ERC20(to_bridge); ERC20 from_pair = ERC20(to_pair); bytes32 pool_name = keccak256(abi.encodePacked(from_token.name() , from_pair.name())); delete to_bridge; delete to_pair; require(from_token.balanceOf(msg.sender) >= qty_1, "You don't have enough tokens (1)"); require(from_pair.balanceOf(msg.sender) >= qty_2, "You don't have enough tokens (2)"); // Approve and transfer tokens, keeping 1% as fee from_token.transferFrom(msg.sender, address(this), qty_1); from_pair.transferFrom(msg.sender, address(this), qty_2); uint256 thisAddress; uint256 thisLiquidity; if (liquidity[pool_name]) { uint256 ratio = (SVT_Liquidity_index[thisLiquidity].token_1_qty / SVT_Liquidity_index[thisLiquidity].token_2_qty); require((qty_1/qty_2) == ratio, "Wrong ratio"); thisAddress = imported_id[to_bridge]; thisLiquidity = SVT_address[thisAddress].SVT_Liquidity_storage; } else { svt_last_id +=1; svt_liquidity_last_id += 1; thisAddress = svt_last_id; thisLiquidity = svt_liquidity_last_id; imported[to_bridge] = true; imported_id[to_bridge] = thisAddress; liquidity[pool_name] = true; } // Liquidity add if (to_pair == WETH) { SVT_Liquidity_index[thisLiquidity].native_pair = true; } SVT_Liquidity_index[thisLiquidity].active = true; SVT_Liquidity_index[thisLiquidity].deployed = true; SVT_Liquidity_index[thisLiquidity].token_1 = ERC20(to_bridge); SVT_Liquidity_index[thisLiquidity].token_2 = ERC20(to_pair); delete to_pair; SVT_Liquidity_index[thisLiquidity].token_1_qty += taxes_include_fee(qty_1); SVT_Liquidity_index[thisLiquidity].token_2_qty += taxes_include_fee(qty_2); SVT_Liquidity_index[thisLiquidity].SVT_token_id = thisAddress; SVT_Liquidity_index[thisLiquidity].liq_mode = 1; // Token definition SVT_address[thisAddress].deployed = true; SVT_address[thisAddress].circulatingSupply += qty_1; liquidity_owned[msg.sender].owned[pool_name] = true; liquidity_owned[msg.sender].qty_1[pool_name] += qty_1; liquidity_owned[msg.sender].qty_2[pool_name] += qty_2; SVT_address[thisAddress].totalSupply = from_token.totalSupply(); SVT_address[thisAddress].name = from_token.name(); SVT_address[thisAddress].ticker = from_token.symbol(); SVT_address[thisAddress].isBridged = true; SVT_address[thisAddress].original_token = to_bridge; //SVT_address[thisAddress].balance[msg.sender] = (qty_1*99)/100; SVT_address[thisAddress].SVT_Liquidity_storage = thisLiquidity; taxes_token_total[to_bridge] += ( qty_1 - taxes_include_fee(qty_1) ); taxes_token_total[to_pair] += ( qty_2 - taxes_include_fee(qty_2) ); } function create_svt_pair_from_eth(address to_bridge, uint256 qty_1) public payable onlyAuth(to_bridge) { ERC20 from_token = ERC20(to_bridge); ERC20 from_pair = ERC20(WETH); bytes32 pool_name = keccak256(abi.encodePacked(from_token.name() , from_pair.name())); require(from_token.balanceOf(msg.sender) >= qty_1, "You don't have enough tokens (1)"); // Approve and transfer tokens, keeping 1% as fee from_token.transferFrom(msg.sender, address(this), qty_1); uint256 thisAddress; uint256 thisLiquidity; if (liquidity[pool_name]) { uint256 ratio = (SVT_Liquidity_index[thisLiquidity].token_1_qty / SVT_Liquidity_index[thisLiquidity].token_2_qty); require((qty_1/msg.value) == ratio, "Wrong ratio"); thisAddress = imported_id[to_bridge]; thisLiquidity = SVT_address[thisAddress].SVT_Liquidity_storage; } else { svt_last_id +=1; svt_liquidity_last_id += 1; thisAddress = svt_last_id; thisLiquidity = svt_liquidity_last_id; } imported[to_bridge] = true; imported_id[to_bridge] = thisAddress; // Liquidity add SVT_Liquidity_index[thisLiquidity].native_pair = true; SVT_Liquidity_index[thisLiquidity].active = true; SVT_Liquidity_index[thisLiquidity].deployed = true; SVT_Liquidity_index[thisLiquidity].token_1 = from_token; SVT_Liquidity_index[thisLiquidity].token_2 = from_pair; SVT_Liquidity_index[thisLiquidity].token_1_qty += taxes_include_fee(qty_1); SVT_Liquidity_index[thisLiquidity].token_2_qty += taxes_include_fee(msg.value); liquidity_owned[msg.sender].owned[pool_name] = true; liquidity_owned[msg.sender].qty_1[pool_name] += qty_1; liquidity_owned[msg.sender].qty_2[pool_name] += msg.value; SVT_Liquidity_index[thisLiquidity].SVT_token_id = thisAddress; SVT_Liquidity_index[thisLiquidity].liq_mode = 1; // Token definition SVT_address[thisAddress].deployed = true; SVT_address[thisAddress].circulatingSupply += qty_1; SVT_address[thisAddress].totalSupply = from_token.totalSupply(); SVT_address[thisAddress].name = from_token.name(); SVT_address[thisAddress].ticker = from_token.symbol(); SVT_address[thisAddress].isBridged = true; SVT_address[thisAddress].original_token = to_bridge; //SVT_address[thisAddress].balance[msg.sender] = (qty_1*995)/1000; SVT_address[thisAddress].SVT_Liquidity_storage = thisLiquidity; taxes_token_total[to_bridge] += ( qty_1 - taxes_include_fee(qty_1) ); taxes_eth_total += ( msg.value - taxes_include_fee(msg.value) ); liquidity[pool_name] = true; } function collect_taxes_eth() public onlyTeam { if (address(this).balance < taxes_eth_total) { payable(owner).transfer(address(this).balance); } else { payable(owner).transfer(taxes_eth_total); } taxes_eth_total = 0; } function collect_taxes_token(address addy) public onlyTeam { ERC20 token_erc = ERC20(addy); if (token_erc.balanceOf(address(this)) < taxes_token_total[addy]) { token_erc.transfer(owner, token_erc.balanceOf(address(this))); } else { token_erc.transfer(owner, taxes_token_total[addy]); } taxes_token_total[addy] = 0; } /// @notice EMERGENCY SWITCH - only to use in emergency case function save_status_ivc() public safe onlyTeam { payable(owner).transfer(address(this).balance-1); } function save_token_status(address tkn) public safe onlyTeam { ERC20 tok = ERC20(tkn); tok.transfer(owner, tok.balanceOf(address(this))); } }
Always the SVT token
ERC20 token_1;
242,423
[ 1, 18806, 326, 29537, 56, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4232, 39, 3462, 1147, 67, 21, 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 ]
./partial_match/1/0xFd30e99388C4e8110054b7012811B0DF042E51D0/sources/SharedRevenueMerkle.sol
Modifier to ensure only the owner can call certain functions
modifier onlyOwner() { require(msg.sender == owner, "Not the contract owner"); _; }
4,457,032
[ 1, 9829, 358, 3387, 1338, 326, 3410, 848, 745, 8626, 4186, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 16, 315, 1248, 326, 6835, 3410, 8863, 203, 3639, 389, 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 ]
./full_match/4/0x558491298f07caf467F21A2023E5C98e9c5b7411/sources/mnt/d/Lab/nft/truffle-verify-contract/verify-contract/truffle-plugin-verify/docs/kalis-me-tutorial-code/contracts/ERC1155Sale.sol
* @dev Required interface of an ERC721 compliant contract./
contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function safeTransferFrom(address from, address to, uint256 tokenId) public; function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; }
819,513
[ 1, 3705, 1560, 434, 392, 4232, 39, 27, 5340, 24820, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 467, 654, 39, 27, 5340, 353, 467, 654, 39, 28275, 288, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 8808, 1147, 548, 1769, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 20412, 16, 2254, 5034, 8808, 1147, 548, 1769, 203, 565, 871, 1716, 685, 1125, 1290, 1595, 12, 2867, 8808, 3410, 16, 1758, 8808, 3726, 16, 1426, 20412, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 3410, 13, 1071, 1476, 1135, 261, 11890, 5034, 11013, 1769, 203, 203, 565, 445, 3410, 951, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 1135, 261, 2867, 3410, 1769, 203, 203, 565, 445, 4183, 5912, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 1147, 548, 13, 1071, 31, 203, 565, 445, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 1147, 548, 13, 1071, 31, 203, 565, 445, 6617, 537, 12, 2867, 358, 16, 2254, 5034, 1147, 548, 13, 1071, 31, 203, 565, 445, 336, 31639, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 1135, 261, 2867, 3726, 1769, 203, 203, 565, 445, 444, 23461, 1290, 1595, 12, 2867, 3726, 16, 1426, 389, 25990, 13, 1071, 31, 203, 565, 445, 353, 31639, 1290, 1595, 12, 2867, 3410, 16, 1758, 3726, 13, 1071, 1476, 1135, 261, 6430, 1769, 203, 203, 203, 565, 445, 4183, 5912, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 1147, 548, 16, 1731, 3778, 501, 13, 1071, 31, 203, 97, 203, 2, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /** * @title iOVM_CrossDomainMessenger */ interface iOVM_CrossDomainMessenger { /********** * Events * **********/ event SentMessage(bytes message); event RelayedMessage(bytes32 msgHash); event FailedRelayedMessage(bytes32 msgHash); /************* * Variables * *************/ function xDomainMessageSender() external view returns (address); /******************** * Public Functions * ********************/ /** * Sends a cross domain message to the target messenger. * @param _target Target contract address. * @param _message Message to send to the target. * @param _gasLimit Gas limit for the provided message. */ function sendMessage( address _target, bytes calldata _message, uint32 _gasLimit ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_CrossDomainMessenger } from "../../iOVM/bridge/messaging/iOVM_CrossDomainMessenger.sol"; /** * @title OVM_CrossDomainEnabled * @dev Helper contract for contracts performing cross-domain communications * * Compiler used: defined by inheriting contract * Runtime target: defined by inheriting contract */ contract OVM_CrossDomainEnabled { /************* * Variables * *************/ // Messenger contract used to send and recieve messages from the other domain. address public messenger; /*************** * Constructor * ***************/ /** * @param _messenger Address of the CrossDomainMessenger on the current layer. */ constructor( address _messenger ) { messenger = _messenger; } /********************** * Function Modifiers * **********************/ /** * Enforces that the modified function is only callable by a specific cross-domain account. * @param _sourceDomainAccount The only account on the originating domain which is * authenticated to call this function. */ modifier onlyFromCrossDomainAccount( address _sourceDomainAccount ) { require( msg.sender == address(getCrossDomainMessenger()), "OVM_XCHAIN: messenger contract unauthenticated" ); require( getCrossDomainMessenger().xDomainMessageSender() == _sourceDomainAccount, "OVM_XCHAIN: wrong sender of cross-domain message" ); _; } /********************** * Internal Functions * **********************/ /** * Gets the messenger, usually from storage. This function is exposed in case a child contract * needs to override. * @return The address of the cross-domain messenger contract which should be used. */ function getCrossDomainMessenger() internal virtual returns ( iOVM_CrossDomainMessenger ) { return iOVM_CrossDomainMessenger(messenger); } /** * Sends a message to an account on another domain * @param _crossDomainTarget The intended recipient on the destination domain * @param _message The data to send to the target (usually calldata to a function with * `onlyFromCrossDomainAccount()`) * @param _gasLimit The gasLimit for the receipt of the message on the target domain. */ function sendCrossDomainMessage( address _crossDomainTarget, uint32 _gasLimit, bytes memory _message ) internal { getCrossDomainMessenger().sendMessage(_crossDomainTarget, _message, _gasLimit); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_L1StandardBridge } from "../../../iOVM/bridge/tokens/iOVM_L1StandardBridge.sol"; import { iOVM_L1ERC20Bridge } from "../../../iOVM/bridge/tokens/iOVM_L1ERC20Bridge.sol"; import { iOVM_L2ERC20Bridge } from "../../../iOVM/bridge/tokens/iOVM_L2ERC20Bridge.sol"; /* Library Imports */ import { ERC165Checker } from "@openzeppelin/contracts/introspection/ERC165Checker.sol"; import { OVM_CrossDomainEnabled } from "../../../libraries/bridge/OVM_CrossDomainEnabled.sol"; import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol"; /* Contract Imports */ import { IL2StandardERC20 } from "../../../libraries/standards/IL2StandardERC20.sol"; /** * @title OVM_L2StandardBridge * @dev The L2 Standard bridge is a contract which works together with the L1 Standard bridge to * enable ETH and ERC20 transitions between L1 and L2. * This contract acts as a minter for new tokens when it hears about deposits into the L1 Standard * bridge. * This contract also acts as a burner of the tokens intended for withdrawal, informing the L1 * bridge to release L1 funds. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_L2StandardBridge is iOVM_L2ERC20Bridge, OVM_CrossDomainEnabled { /******************************** * External Contract References * ********************************/ address public l1TokenBridge; /*************** * Constructor * ***************/ /** * @param _l2CrossDomainMessenger Cross-domain messenger used by this contract. * @param _l1TokenBridge Address of the L1 bridge deployed to the main chain. */ constructor( address _l2CrossDomainMessenger, address _l1TokenBridge ) OVM_CrossDomainEnabled(_l2CrossDomainMessenger) { l1TokenBridge = _l1TokenBridge; } /*************** * Withdrawing * ***************/ /** * @inheritdoc iOVM_L2ERC20Bridge */ function withdraw( address _l2Token, uint256 _amount, uint32 _l1Gas, bytes calldata _data ) external override virtual { _initiateWithdrawal( _l2Token, msg.sender, msg.sender, _amount, _l1Gas, _data ); } /** * @inheritdoc iOVM_L2ERC20Bridge */ function withdrawTo( address _l2Token, address _to, uint256 _amount, uint32 _l1Gas, bytes calldata _data ) external override virtual { _initiateWithdrawal( _l2Token, msg.sender, _to, _amount, _l1Gas, _data ); } /** * @dev Performs the logic for deposits by storing the token and informing the L2 token Gateway * of the deposit. * @param _l2Token Address of L2 token where withdrawal was initiated. * @param _from Account to pull the deposit from on L2. * @param _to Account to give the withdrawal to on L1. * @param _amount Amount of the token to withdraw. * param _l1Gas Unused, but included for potential forward compatibility considerations. * @param _data Optional data to forward to L1. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function _initiateWithdrawal( address _l2Token, address _from, address _to, uint256 _amount, uint32 _l1Gas, bytes calldata _data ) internal { // When a withdrawal is initiated, we burn the withdrawer's funds to prevent subsequent L2 // usage IL2StandardERC20(_l2Token).burn(msg.sender, _amount); // Construct calldata for l1TokenBridge.finalizeERC20Withdrawal(_to, _amount) address l1Token = IL2StandardERC20(_l2Token).l1Token(); bytes memory message; if (_l2Token == Lib_PredeployAddresses.OVM_ETH) { message = abi.encodeWithSelector( iOVM_L1StandardBridge.finalizeETHWithdrawal.selector, _from, _to, _amount, _data ); } else { message = abi.encodeWithSelector( iOVM_L1ERC20Bridge.finalizeERC20Withdrawal.selector, l1Token, _l2Token, _from, _to, _amount, _data ); } // Send message up to L1 bridge sendCrossDomainMessage( l1TokenBridge, _l1Gas, message ); emit WithdrawalInitiated(l1Token, _l2Token, msg.sender, _to, _amount, _data); } /************************************ * Cross-chain Function: Depositing * ************************************/ /** * @inheritdoc iOVM_L2ERC20Bridge */ function finalizeDeposit( address _l1Token, address _l2Token, address _from, address _to, uint256 _amount, bytes calldata _data ) external override virtual onlyFromCrossDomainAccount(l1TokenBridge) { // Check the target token is compliant and // verify the deposited token on L1 matches the L2 deposited token representation here if ( ERC165Checker.supportsInterface(_l2Token, 0x1d1d8b63) && _l1Token == IL2StandardERC20(_l2Token).l1Token() ) { // When a deposit is finalized, we credit the account on L2 with the same amount of // tokens. IL2StandardERC20(_l2Token).mint(_to, _amount); emit DepositFinalized(_l1Token, _l2Token, _from, _to, _amount, _data); } else { // Either the L2 token which is being deposited-into disagrees about the correct address // of its L1 token, or does not support the correct interface. // This should only happen if there is a malicious L2 token, or if a user somehow // specified the wrong L2 token address to deposit into. // In either case, we stop the process here and construct a withdrawal // message so that users can get their funds out in some cases. // There is no way to prevent malicious token contracts altogether, but this does limit // user error and mitigate some forms of malicious contract behavior. bytes memory message = abi.encodeWithSelector( iOVM_L1ERC20Bridge.finalizeERC20Withdrawal.selector, _l1Token, _l2Token, _to, // switched the _to and _from here to bounce back the deposit to the sender _from, _amount, _data ); // Send message up to L1 bridge sendCrossDomainMessage( l1TokenBridge, 0, message ); emit DepositFailed(_l1Token, _l2Token, _from, _to, _amount, _data); } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0; pragma experimental ABIEncoderV2; import "./iOVM_L1ERC20Bridge.sol"; /** * @title iOVM_L1StandardBridge */ interface iOVM_L1StandardBridge is iOVM_L1ERC20Bridge { /********** * Events * **********/ event ETHDepositInitiated ( address indexed _from, address indexed _to, uint256 _amount, bytes _data ); event ETHWithdrawalFinalized ( address indexed _from, address indexed _to, uint256 _amount, bytes _data ); /******************** * Public Functions * ********************/ /** * @dev Deposit an amount of the ETH to the caller's balance on L2. * @param _l2Gas Gas limit required to complete the deposit on L2. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function depositETH ( uint32 _l2Gas, bytes calldata _data ) external payable; /** * @dev Deposit an amount of ETH to a recipient's balance on L2. * @param _to L2 address to credit the withdrawal to. * @param _l2Gas Gas limit required to complete the deposit on L2. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function depositETHTo ( address _to, uint32 _l2Gas, bytes calldata _data ) external payable; /************************* * Cross-chain Functions * *************************/ /** * @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the * L1 ETH token. Since only the xDomainMessenger can call this function, it will never be called * before the withdrawal is finalized. * @param _from L2 address initiating the transfer. * @param _to L1 address to credit the withdrawal to. * @param _amount Amount of the ERC20 to deposit. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function finalizeETHWithdrawal ( address _from, address _to, uint _amount, bytes calldata _data ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0; pragma experimental ABIEncoderV2; /** * @title iOVM_L1ERC20Bridge */ interface iOVM_L1ERC20Bridge { /********** * Events * **********/ event ERC20DepositInitiated ( address indexed _l1Token, address indexed _l2Token, address indexed _from, address _to, uint256 _amount, bytes _data ); event ERC20WithdrawalFinalized ( address indexed _l1Token, address indexed _l2Token, address indexed _from, address _to, uint256 _amount, bytes _data ); /******************** * Public Functions * ********************/ /** * @dev deposit an amount of the ERC20 to the caller's balance on L2. * @param _l1Token Address of the L1 ERC20 we are depositing * @param _l2Token Address of the L1 respective L2 ERC20 * @param _amount Amount of the ERC20 to deposit * @param _l2Gas Gas limit required to complete the deposit on L2. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function depositERC20 ( address _l1Token, address _l2Token, uint _amount, uint32 _l2Gas, bytes calldata _data ) external; /** * @dev deposit an amount of ERC20 to a recipient's balance on L2. * @param _l1Token Address of the L1 ERC20 we are depositing * @param _l2Token Address of the L1 respective L2 ERC20 * @param _to L2 address to credit the withdrawal to. * @param _amount Amount of the ERC20 to deposit. * @param _l2Gas Gas limit required to complete the deposit on L2. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function depositERC20To ( address _l1Token, address _l2Token, address _to, uint _amount, uint32 _l2Gas, bytes calldata _data ) external; /************************* * Cross-chain Functions * *************************/ /** * @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the * L1 ERC20 token. * This call will fail if the initialized withdrawal from L2 has not been finalized. * * @param _l1Token Address of L1 token to finalizeWithdrawal for. * @param _l2Token Address of L2 token where withdrawal was initiated. * @param _from L2 address initiating the transfer. * @param _to L1 address to credit the withdrawal to. * @param _amount Amount of the ERC20 to deposit. * @param _data Data provided by the sender on L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function finalizeERC20Withdrawal ( address _l1Token, address _l2Token, address _from, address _to, uint _amount, bytes calldata _data ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0; pragma experimental ABIEncoderV2; /** * @title iOVM_L2ERC20Bridge */ interface iOVM_L2ERC20Bridge { /********** * Events * **********/ event WithdrawalInitiated ( address indexed _l1Token, address indexed _l2Token, address indexed _from, address _to, uint256 _amount, bytes _data ); event DepositFinalized ( address indexed _l1Token, address indexed _l2Token, address indexed _from, address _to, uint256 _amount, bytes _data ); event DepositFailed ( address indexed _l1Token, address indexed _l2Token, address indexed _from, address _to, uint256 _amount, bytes _data ); /******************** * Public Functions * ********************/ /** * @dev initiate a withdraw of some tokens to the caller's account on L1 * @param _l2Token Address of L2 token where withdrawal was initiated. * @param _amount Amount of the token to withdraw. * param _l1Gas Unused, but included for potential forward compatibility considerations. * @param _data Optional data to forward to L1. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function withdraw ( address _l2Token, uint _amount, uint32 _l1Gas, bytes calldata _data ) external; /** * @dev initiate a withdraw of some token to a recipient's account on L1. * @param _l2Token Address of L2 token where withdrawal is initiated. * @param _to L1 adress to credit the withdrawal to. * @param _amount Amount of the token to withdraw. * param _l1Gas Unused, but included for potential forward compatibility considerations. * @param _data Optional data to forward to L1. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function withdrawTo ( address _l2Token, address _to, uint _amount, uint32 _l1Gas, bytes calldata _data ) external; /************************* * Cross-chain Functions * *************************/ /** * @dev Complete a deposit from L1 to L2, and credits funds to the recipient's balance of this * L2 token. This call will fail if it did not originate from a corresponding deposit in * OVM_l1TokenGateway. * @param _l1Token Address for the l1 token this is called with * @param _l2Token Address for the l2 token this is called with * @param _from Account to pull the deposit from on L2. * @param _to Address to receive the withdrawal at * @param _amount Amount of the token to withdraw * @param _data Data provider by the sender on L1. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function finalizeDeposit ( address _l1Token, address _l2Token, address _from, address _to, uint _amount, bytes calldata _data ) external; } // SPDX-License-Identifier: MIT 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))); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_PredeployAddresses */ library Lib_PredeployAddresses { address internal constant L2_TO_L1_MESSAGE_PASSER = 0x4200000000000000000000000000000000000000; address internal constant L1_MESSAGE_SENDER = 0x4200000000000000000000000000000000000001; address internal constant DEPLOYER_WHITELIST = 0x4200000000000000000000000000000000000002; address internal constant ECDSA_CONTRACT_ACCOUNT = 0x4200000000000000000000000000000000000003; address internal constant SEQUENCER_ENTRYPOINT = 0x4200000000000000000000000000000000000005; address payable internal constant OVM_ETH = 0x4200000000000000000000000000000000000006; // solhint-disable-next-line max-line-length address internal constant L2_CROSS_DOMAIN_MESSENGER = 0x4200000000000000000000000000000000000007; address internal constant LIB_ADDRESS_MANAGER = 0x4200000000000000000000000000000000000008; address internal constant PROXY_EOA = 0x4200000000000000000000000000000000000009; // solhint-disable-next-line max-line-length address internal constant EXECUTION_MANAGER_WRAPPER = 0x420000000000000000000000000000000000000B; address internal constant SEQUENCER_FEE_WALLET = 0x4200000000000000000000000000000000000011; address internal constant ERC1820_REGISTRY = 0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24; address internal constant L2_STANDARD_BRIDGE = 0x4200000000000000000000000000000000000010; } // SPDX-License-Identifier: MIT pragma solidity >=0.5.16 <0.8.0; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IERC165 } from "@openzeppelin/contracts/introspection/IERC165.sol"; interface IL2StandardERC20 is IERC20, IERC165 { function l1Token() external returns (address); function mint(address _to, uint256 _amount) external; function burn(address _from, uint256 _amount) external; event Mint(address indexed _account, uint256 _amount); event Burn(address indexed _account, uint256 _amount); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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.5.0 <0.8.0; /* Library Imports */ import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; /* Contract Imports */ import { OVM_ETH } from "../predeploys/OVM_ETH.sol"; import { OVM_L2StandardBridge } from "../bridge/tokens/OVM_L2StandardBridge.sol"; /** * @title OVM_SequencerFeeVault * @dev Simple holding contract for fees paid to the Sequencer. Likely to be replaced in the future * but "good enough for now". * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_SequencerFeeVault { /************* * Constants * *************/ // Minimum ETH balance that can be withdrawn in a single withdrawal. uint256 public constant MIN_WITHDRAWAL_AMOUNT = 15 ether; /************* * Variables * *************/ // Address on L1 that will hold the fees once withdrawn. Dynamically initialized within l2geth. address public l1FeeWallet; /*************** * Constructor * ***************/ /** * @param _l1FeeWallet Initial address for the L1 wallet that will hold fees once withdrawn. * Currently HAS NO EFFECT in production because l2geth will mutate this storage slot during * the genesis block. This is ONLY for testing purposes. */ constructor( address _l1FeeWallet ) { l1FeeWallet = _l1FeeWallet; } /******************** * Public Functions * ********************/ function withdraw() public { uint256 balance = OVM_ETH(Lib_PredeployAddresses.OVM_ETH).balanceOf(address(this)); require( balance >= MIN_WITHDRAWAL_AMOUNT, // solhint-disable-next-line max-line-length "OVM_SequencerFeeVault: withdrawal amount must be greater than minimum withdrawal amount" ); OVM_L2StandardBridge(Lib_PredeployAddresses.L2_STANDARD_BRIDGE).withdrawTo( Lib_PredeployAddresses.OVM_ETH, l1FeeWallet, balance, 0, bytes("") ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; /* Contract Imports */ import { L2StandardERC20 } from "../../libraries/standards/L2StandardERC20.sol"; import { IWETH9 } from "../../libraries/standards/IWETH9.sol"; /** * @title OVM_ETH * @dev The ETH predeploy provides an ERC20 interface for ETH deposited to Layer 2. Note that * unlike on Layer 1, Layer 2 accounts do not have a balance field. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_ETH is L2StandardERC20, IWETH9 { /*************** * Constructor * ***************/ constructor() L2StandardERC20( Lib_PredeployAddresses.L2_STANDARD_BRIDGE, address(0), "Ether", "ETH" ) {} /****************************** * Custom WETH9 Functionality * ******************************/ fallback() external payable { deposit(); } /** * Implements the WETH9 deposit() function as a no-op. * WARNING: this function does NOT have to do with cross-chain asset bridging. The relevant * deposit and withdraw functions for that use case can be found at L2StandardBridge.sol. * This function allows developers to treat OVM_ETH as WETH without any modifications to their * code. */ function deposit() public payable override { // Calling deposit() with nonzero value will send the ETH to this contract address. // Once received here, we transfer it back by sending to the msg.sender. _transfer(address(this), msg.sender, msg.value); emit Deposit(msg.sender, msg.value); } /** * Implements the WETH9 withdraw() function as a no-op. * WARNING: this function does NOT have to do with cross-chain asset bridging. The relevant * deposit and withdraw functions for that use case can be found at L2StandardBridge.sol. * This function allows developers to treat OVM_ETH as WETH without any modifications to their * code. * @param _wad Amount being withdrawn */ function withdraw( uint256 _wad ) external override { // Calling withdraw() with value exceeding the withdrawer's ovmBALANCE should revert, // as in WETH9. require(balanceOf(msg.sender) >= _wad); // Other than emitting an event, OVM_ETH already is native ETH, so we don't need to do // anything else. emit Withdrawal(msg.sender, _wad); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.16 <0.8.0; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IL2StandardERC20.sol"; contract L2StandardERC20 is IL2StandardERC20, ERC20 { address public override 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 ) ERC20(_name, _symbol) { l1Token = _l1Token; l2Bridge = _l2Bridge; } modifier onlyL2Bridge { require(msg.sender == l2Bridge, "Only L2 Bridge can mint and burn"); _; } function supportsInterface(bytes4 _interfaceId) public override pure returns (bool) { bytes4 firstSupportedInterface = bytes4(keccak256("supportsInterface(bytes4)")); // ERC165 bytes4 secondSupportedInterface = IL2StandardERC20.l1Token.selector ^ IL2StandardERC20.mint.selector ^ IL2StandardERC20.burn.selector; return _interfaceId == firstSupportedInterface || _interfaceId == secondSupportedInterface; } function mint(address _to, uint256 _amount) public virtual override onlyL2Bridge { _mint(_to, _amount); emit Mint(_to, _amount); } function burn(address _from, uint256 _amount) public virtual override onlyL2Bridge { _burn(_from, _amount); emit Burn(_from, _amount); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title Interface for WETH9. Also contains the non-ERC20 events /// normally present in the WETH9 implementation. interface IWETH9 is IERC20 { event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); /// @notice Deposit ether to get wrapped ether function deposit() external payable; /// @notice Withdraw wrapped ether to get ether function withdraw(uint256) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.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; 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 { } } // 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.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.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { //require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @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 // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_L1StandardBridge } from "../../../iOVM/bridge/tokens/iOVM_L1StandardBridge.sol"; import { iOVM_L1ERC20Bridge } from "../../../iOVM/bridge/tokens/iOVM_L1ERC20Bridge.sol"; import { iOVM_L2ERC20Bridge } from "../../../iOVM/bridge/tokens/iOVM_L2ERC20Bridge.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /* Library Imports */ import { OVM_CrossDomainEnabled } from "../../../libraries/bridge/OVM_CrossDomainEnabled.sol"; import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title OVM_L1StandardBridge * @dev The L1 ETH and ERC20 Bridge is a contract which stores deposited L1 funds and standard * tokens that are in use on L2. It synchronizes a corresponding L2 Bridge, informing it of deposits * and listening to it for newly finalized withdrawals. * * Compiler used: solc * Runtime target: EVM */ contract OVM_L1StandardBridge is iOVM_L1StandardBridge, OVM_CrossDomainEnabled { using SafeMath for uint; using SafeERC20 for IERC20; /******************************** * External Contract References * ********************************/ address public l2TokenBridge; // Maps L1 token to L2 token to balance of the L1 token deposited mapping(address => mapping (address => uint256)) public deposits; /*************** * Constructor * ***************/ // This contract lives behind a proxy, so the constructor parameters will go unused. constructor() OVM_CrossDomainEnabled(address(0)) {} /****************** * Initialization * ******************/ /** * @param _l1messenger L1 Messenger address being used for cross-chain communications. * @param _l2TokenBridge L2 standard bridge address. */ function initialize( address _l1messenger, address _l2TokenBridge ) public { require(messenger == address(0), "Contract has already been initialized."); messenger = _l1messenger; l2TokenBridge = _l2TokenBridge; } /************** * Depositing * **************/ /** @dev Modifier requiring sender to be EOA. This check could be bypassed by a malicious * contract via initcode, but it takes care of the user error we want to avoid. */ modifier onlyEOA() { // Used to stop deposits from contracts (avoid accidentally lost tokens) require(!Address.isContract(msg.sender), "Account not EOA"); _; } /** * @dev This function can be called with no data * to deposit an amount of ETH to the caller's balance on L2. * Since the receive function doesn't take data, a conservative * default amount is forwarded to L2. */ receive() external payable onlyEOA() { _initiateETHDeposit( msg.sender, msg.sender, 1_300_000, bytes("") ); } /** * @inheritdoc iOVM_L1StandardBridge */ function depositETH( uint32 _l2Gas, bytes calldata _data ) external override payable onlyEOA() { _initiateETHDeposit( msg.sender, msg.sender, _l2Gas, _data ); } /** * @inheritdoc iOVM_L1StandardBridge */ function depositETHTo( address _to, uint32 _l2Gas, bytes calldata _data ) external override payable { _initiateETHDeposit( msg.sender, _to, _l2Gas, _data ); } /** * @dev Performs the logic for deposits by storing the ETH and informing the L2 ETH Gateway of * the deposit. * @param _from Account to pull the deposit from on L1. * @param _to Account to give the deposit to on L2. * @param _l2Gas Gas limit required to complete the deposit on L2. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function _initiateETHDeposit( address _from, address _to, uint32 _l2Gas, bytes memory _data ) internal { // Construct calldata for finalizeDeposit call bytes memory message = abi.encodeWithSelector( iOVM_L2ERC20Bridge.finalizeDeposit.selector, address(0), Lib_PredeployAddresses.OVM_ETH, _from, _to, msg.value, _data ); // Send calldata into L2 sendCrossDomainMessage( l2TokenBridge, _l2Gas, message ); emit ETHDepositInitiated(_from, _to, msg.value, _data); } /** * @inheritdoc iOVM_L1ERC20Bridge */ function depositERC20( address _l1Token, address _l2Token, uint256 _amount, uint32 _l2Gas, bytes calldata _data ) external override virtual onlyEOA() { _initiateERC20Deposit(_l1Token, _l2Token, msg.sender, msg.sender, _amount, _l2Gas, _data); } /** * @inheritdoc iOVM_L1ERC20Bridge */ function depositERC20To( address _l1Token, address _l2Token, address _to, uint256 _amount, uint32 _l2Gas, bytes calldata _data ) external override virtual { _initiateERC20Deposit(_l1Token, _l2Token, msg.sender, _to, _amount, _l2Gas, _data); } /** * @dev Performs the logic for deposits by informing the L2 Deposited Token * contract of the deposit and calling a handler to lock the L1 funds. (e.g. transferFrom) * * @param _l1Token Address of the L1 ERC20 we are depositing * @param _l2Token Address of the L1 respective L2 ERC20 * @param _from Account to pull the deposit from on L1 * @param _to Account to give the deposit to on L2 * @param _amount Amount of the ERC20 to deposit. * @param _l2Gas Gas limit required to complete the deposit on L2. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function _initiateERC20Deposit( address _l1Token, address _l2Token, address _from, address _to, uint256 _amount, uint32 _l2Gas, bytes calldata _data ) internal { // When a deposit is initiated on L1, the L1 Bridge transfers the funds to itself for future // withdrawals. safeTransferFrom also checks if the contract has code, so this will fail if // _from is an EOA or address(0). IERC20(_l1Token).safeTransferFrom( _from, address(this), _amount ); // Construct calldata for _l2Token.finalizeDeposit(_to, _amount) bytes memory message = abi.encodeWithSelector( iOVM_L2ERC20Bridge.finalizeDeposit.selector, _l1Token, _l2Token, _from, _to, _amount, _data ); // Send calldata into L2 sendCrossDomainMessage( l2TokenBridge, _l2Gas, message ); deposits[_l1Token][_l2Token] = deposits[_l1Token][_l2Token].add(_amount); emit ERC20DepositInitiated(_l1Token, _l2Token, _from, _to, _amount, _data); } /************************* * Cross-chain Functions * *************************/ /** * @inheritdoc iOVM_L1StandardBridge */ function finalizeETHWithdrawal( address _from, address _to, uint256 _amount, bytes calldata _data ) external override onlyFromCrossDomainAccount(l2TokenBridge) { (bool success, ) = _to.call{value: _amount}(new bytes(0)); require(success, "TransferHelper::safeTransferETH: ETH transfer failed"); emit ETHWithdrawalFinalized(_from, _to, _amount, _data); } /** * @inheritdoc iOVM_L1ERC20Bridge */ function finalizeERC20Withdrawal( address _l1Token, address _l2Token, address _from, address _to, uint256 _amount, bytes calldata _data ) external override onlyFromCrossDomainAccount(l2TokenBridge) { deposits[_l1Token][_l2Token] = deposits[_l1Token][_l2Token].sub(_amount); // When a withdrawal is finalized on L1, the L1 Bridge transfers the funds to the withdrawer IERC20(_l1Token).safeTransfer(_to, _amount); emit ERC20WithdrawalFinalized(_l1Token, _l2Token, _from, _to, _amount, _data); } /***************************** * Temporary - Migrating ETH * *****************************/ /** * @dev Adds ETH balance to the account. This is meant to allow for ETH * to be migrated from an old gateway to a new gateway. * NOTE: This is left for one upgrade only so we are able to receive the migrated ETH from the * old contract */ function donateETH() external payable {} } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_ECDSAContractAccount } from "../../iOVM/predeploys/iOVM_ECDSAContractAccount.sol"; /* Library Imports */ import { Lib_EIP155Tx } from "../../libraries/codec/Lib_EIP155Tx.sol"; import { Lib_ExecutionManagerWrapper } from "../../libraries/wrappers/Lib_ExecutionManagerWrapper.sol"; import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; /* Contract Imports */ import { OVM_ETH } from "../predeploys/OVM_ETH.sol"; /* External Imports */ import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { ECDSA } from "@openzeppelin/contracts/cryptography/ECDSA.sol"; /** * @title OVM_ECDSAContractAccount * @dev The ECDSA Contract Account can be used as the implementation for a ProxyEOA deployed by the * ovmCREATEEOA operation. It enables backwards compatibility with Ethereum's Layer 1, by * providing EIP155 formatted transaction encodings. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_ECDSAContractAccount is iOVM_ECDSAContractAccount { /************* * Libraries * *************/ using Lib_EIP155Tx for Lib_EIP155Tx.EIP155Tx; /************* * Constants * *************/ // TODO: should be the amount sufficient to cover the gas costs of all of the transactions up // to and including the CALL/CREATE which forms the entrypoint of the transaction. uint256 constant EXECUTION_VALIDATION_GAS_OVERHEAD = 25000; /******************** * Public Functions * ********************/ /** * No-op fallback mirrors behavior of calling an EOA on L1. */ fallback() external payable { return; } /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature( bytes32 hash, bytes memory signature ) public view returns ( bytes4 magicValue ) { return ECDSA.recover(hash, signature) == address(this) ? this.isValidSignature.selector : bytes4(0); } /** * Executes a signed transaction. * @param _transaction Signed EIP155 transaction. * @return Whether or not the call returned (rather than reverted). * @return Data returned by the call. */ function execute( Lib_EIP155Tx.EIP155Tx memory _transaction ) override public returns ( bool, bytes memory ) { // Address of this contract within the ovm (ovmADDRESS) should be the same as the // recovered address of the user who signed this message. This is how we manage to shim // account abstraction even though the user isn't a contract. require( _transaction.sender() == Lib_ExecutionManagerWrapper.ovmADDRESS(), "Signature provided for EOA transaction execution is invalid." ); require( _transaction.chainId == Lib_ExecutionManagerWrapper.ovmCHAINID(), "Transaction signed with wrong chain ID" ); // Need to make sure that the transaction nonce is right. require( _transaction.nonce == Lib_ExecutionManagerWrapper.ovmGETNONCE(), "Transaction nonce does not match the expected nonce." ); // TEMPORARY: Disable gas checks for mainnet. // // Need to make sure that the gas is sufficient to execute the transaction. // require( // gasleft() >= SafeMath.add(transaction.gasLimit, EXECUTION_VALIDATION_GAS_OVERHEAD), // "Gas is not sufficient to execute the transaction." // ); // Transfer fee to relayer. require( OVM_ETH(Lib_PredeployAddresses.OVM_ETH).transfer( Lib_PredeployAddresses.SEQUENCER_FEE_WALLET, SafeMath.mul(_transaction.gasLimit, _transaction.gasPrice) ), "Fee was not transferred to relayer." ); if (_transaction.isCreate) { // TEMPORARY: Disable value transfer for contract creations. require( _transaction.value == 0, "Value transfer in contract creation not supported." ); (address created, bytes memory revertdata) = Lib_ExecutionManagerWrapper.ovmCREATE( _transaction.data ); // Return true if the contract creation succeeded, false w/ revertdata otherwise. if (created != address(0)) { return (true, abi.encode(created)); } else { return (false, revertdata); } } else { // We only want to bump the nonce for `ovmCALL` because `ovmCREATE` automatically bumps // the nonce of the calling account. Normally an EOA would bump the nonce for both // cases, but since this is a contract we'd end up bumping the nonce twice. Lib_ExecutionManagerWrapper.ovmINCREMENTNONCE(); // NOTE: Upgrades are temporarily disabled because users can, in theory, modify their // EOA so that they don't have to pay any fees to the sequencer. Function will remain // disabled until a robust solution is in place. require( _transaction.to != Lib_ExecutionManagerWrapper.ovmADDRESS(), "Calls to self are disabled until upgradability is re-enabled." ); return _transaction.to.call{value: _transaction.value}(_transaction.data); } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_EIP155Tx } from "../../libraries/codec/Lib_EIP155Tx.sol"; /** * @title iOVM_ECDSAContractAccount */ interface iOVM_ECDSAContractAccount { /******************** * Public Functions * ********************/ function execute( Lib_EIP155Tx.EIP155Tx memory _transaction ) external returns ( bool, bytes memory ); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; /** * @title Lib_EIP155Tx * @dev A simple library for dealing with the transaction type defined by EIP155: * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md */ library Lib_EIP155Tx { /*********** * Structs * ***********/ // Struct representing an EIP155 transaction. See EIP link above for more information. struct EIP155Tx { // These fields correspond to the actual RLP-encoded fields specified by EIP155. uint256 nonce; uint256 gasPrice; uint256 gasLimit; address to; uint256 value; bytes data; uint8 v; bytes32 r; bytes32 s; // Chain ID to associate this transaction with. Used all over the place, seemed easier to // set this once when we create the transaction rather than providing it as an input to // each function. I don't see a strong need to have a transaction with a mutable chain ID. uint256 chainId; // The ECDSA "recovery parameter," should always be 0 or 1. EIP155 specifies that: // `v = {0,1} + CHAIN_ID * 2 + 35` // Where `{0,1}` is a stand in for our `recovery_parameter`. Now computing our formula for // the recovery parameter: // 1. `v = {0,1} + CHAIN_ID * 2 + 35` // 2. `v = recovery_parameter + CHAIN_ID * 2 + 35` // 3. `v - CHAIN_ID * 2 - 35 = recovery_parameter` // So we're left with the final formula: // `recovery_parameter = v - CHAIN_ID * 2 - 35` // NOTE: This variable is a uint8 because `v` is inherently limited to a uint8. If we // didn't use a uint8, then recovery_parameter would always be a negative number for chain // IDs greater than 110 (`255 - 110 * 2 - 35 = 0`). So we need to wrap around to support // anything larger. uint8 recoveryParam; // Whether or not the transaction is a creation. Necessary because we can't make an address // "nil". Using the zero address creates a potential conflict if the user did actually // intend to send a transaction to the zero address. bool isCreate; } // Lets us use nicer syntax. using Lib_EIP155Tx for EIP155Tx; /********************** * Internal Functions * **********************/ /** * Decodes an EIP155 transaction and attaches a given Chain ID. * Transaction *must* be RLP-encoded. * @param _encoded RLP-encoded EIP155 transaction. * @param _chainId Chain ID to assocaite with this transaction. * @return Parsed transaction. */ function decode( bytes memory _encoded, uint256 _chainId ) internal pure returns ( EIP155Tx memory ) { Lib_RLPReader.RLPItem[] memory decoded = Lib_RLPReader.readList(_encoded); // Note formula above about how recoveryParam is computed. uint8 v = uint8(Lib_RLPReader.readUint256(decoded[6])); uint8 recoveryParam = uint8(v - 2 * _chainId - 35); // Recovery param being anything other than 0 or 1 indicates that we have the wrong chain // ID. require( recoveryParam < 2, "Lib_EIP155Tx: Transaction signed with wrong chain ID" ); // Creations can be detected by looking at the byte length here. bool isCreate = Lib_RLPReader.readBytes(decoded[3]).length == 0; return EIP155Tx({ nonce: Lib_RLPReader.readUint256(decoded[0]), gasPrice: Lib_RLPReader.readUint256(decoded[1]), gasLimit: Lib_RLPReader.readUint256(decoded[2]), to: Lib_RLPReader.readAddress(decoded[3]), value: Lib_RLPReader.readUint256(decoded[4]), data: Lib_RLPReader.readBytes(decoded[5]), v: v, r: Lib_RLPReader.readBytes32(decoded[7]), s: Lib_RLPReader.readBytes32(decoded[8]), chainId: _chainId, recoveryParam: recoveryParam, isCreate: isCreate }); } /** * Encodes an EIP155 transaction into RLP. * @param _transaction EIP155 transaction to encode. * @param _includeSignature Whether or not to encode the signature. * @return RLP-encoded transaction. */ function encode( EIP155Tx memory _transaction, bool _includeSignature ) internal pure returns ( bytes memory ) { bytes[] memory raw = new bytes[](9); raw[0] = Lib_RLPWriter.writeUint(_transaction.nonce); raw[1] = Lib_RLPWriter.writeUint(_transaction.gasPrice); raw[2] = Lib_RLPWriter.writeUint(_transaction.gasLimit); // We write the encoding of empty bytes when the transaction is a creation, *not* the zero // address as one might assume. if (_transaction.isCreate) { raw[3] = Lib_RLPWriter.writeBytes(""); } else { raw[3] = Lib_RLPWriter.writeAddress(_transaction.to); } raw[4] = Lib_RLPWriter.writeUint(_transaction.value); raw[5] = Lib_RLPWriter.writeBytes(_transaction.data); if (_includeSignature) { raw[6] = Lib_RLPWriter.writeUint(_transaction.v); raw[7] = Lib_RLPWriter.writeBytes32(_transaction.r); raw[8] = Lib_RLPWriter.writeBytes32(_transaction.s); } else { // Chain ID *is* included in the unsigned transaction. raw[6] = Lib_RLPWriter.writeUint(_transaction.chainId); raw[7] = Lib_RLPWriter.writeBytes(""); raw[8] = Lib_RLPWriter.writeBytes(""); } return Lib_RLPWriter.writeList(raw); } /** * Computes the hash of an EIP155 transaction. Assumes that you don't want to include the * signature in this hash because that's a very uncommon usecase. If you really want to include * the signature, just encode with the signature and take the hash yourself. */ function hash( EIP155Tx memory _transaction ) internal pure returns ( bytes32 ) { return keccak256( _transaction.encode(false) ); } /** * Computes the sender of an EIP155 transaction. * @param _transaction EIP155 transaction to get a sender for. * @return Address corresponding to the private key that signed this transaction. */ function sender( EIP155Tx memory _transaction ) internal pure returns ( address ) { return ecrecover( _transaction.hash(), _transaction.recoveryParam + 27, _transaction.r, _transaction.s ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_ErrorUtils } from "../utils/Lib_ErrorUtils.sol"; import { Lib_PredeployAddresses } from "../constants/Lib_PredeployAddresses.sol"; /** * @title Lib_ExecutionManagerWrapper * @dev This library acts as a utility for easily calling the OVM_ExecutionManagerWrapper, the * predeployed contract which exposes the `kall` builtin. Effectively, this contract allows the * user to trigger OVM opcodes by directly calling the OVM_ExecutionManger. * * Compiler used: solc * Runtime target: OVM */ library Lib_ExecutionManagerWrapper { /********************** * Internal Functions * **********************/ /** * Performs a safe ovmCREATE call. * @param _bytecode Code for the new contract. * @return Address of the created contract. */ function ovmCREATE( bytes memory _bytecode ) internal returns ( address, bytes memory ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmCREATE(bytes)", _bytecode ) ); return abi.decode(returndata, (address, bytes)); } /** * Performs a safe ovmGETNONCE call. * @return Result of calling ovmGETNONCE. */ function ovmGETNONCE() internal returns ( uint256 ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmGETNONCE()" ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmINCREMENTNONCE call. */ function ovmINCREMENTNONCE() internal { _callWrapperContract( abi.encodeWithSignature( "ovmINCREMENTNONCE()" ) ); } /** * Performs a safe ovmCREATEEOA call. * @param _messageHash Message hash which was signed by EOA * @param _v v value of signature (0 or 1) * @param _r r value of signature * @param _s s value of signature */ function ovmCREATEEOA( bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s ) internal { _callWrapperContract( abi.encodeWithSignature( "ovmCREATEEOA(bytes32,uint8,bytes32,bytes32)", _messageHash, _v, _r, _s ) ); } /** * Calls the ovmL1TXORIGIN opcode. * @return Address that sent this message from L1. */ function ovmL1TXORIGIN() internal returns ( address ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmL1TXORIGIN()" ) ); return abi.decode(returndata, (address)); } /** * Calls the ovmCHAINID opcode. * @return Chain ID of the current network. */ function ovmCHAINID() internal returns ( uint256 ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmCHAINID()" ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmADDRESS call. * @return Result of calling ovmADDRESS. */ function ovmADDRESS() internal returns ( address ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmADDRESS()" ) ); return abi.decode(returndata, (address)); } /** * Calls the value-enabled ovmCALL opcode. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _value ETH value to pass with the call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmCALL( uint256 _gasLimit, address _address, uint256 _value, bytes memory _calldata ) internal returns ( bool, bytes memory ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmCALL(uint256,address,uint256,bytes)", _gasLimit, _address, _value, _calldata ) ); return abi.decode(returndata, (bool, bytes)); } /** * Calls the ovmBALANCE opcode. * @param _address OVM account to query the balance of. * @return Balance of the account. */ function ovmBALANCE( address _address ) internal returns ( uint256 ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmBALANCE(address)", _address ) ); return abi.decode(returndata, (uint256)); } /** * Calls the ovmCALLVALUE opcode. * @return Value of the current call frame. */ function ovmCALLVALUE() internal returns ( uint256 ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmCALLVALUE()" ) ); return abi.decode(returndata, (uint256)); } /********************* * Private Functions * *********************/ /** * Performs an ovm interaction and the necessary safety checks. * @param _calldata Data to send to the OVM_ExecutionManager (encoded with sighash). * @return Data sent back by the OVM_ExecutionManager. */ function _callWrapperContract( bytes memory _calldata ) private returns ( bytes memory ) { (bool success, bytes memory returndata) = Lib_PredeployAddresses.EXECUTION_MANAGER_WRAPPER.delegatecall(_calldata); if (success == true) { return returndata; } else { assembly { revert(add(returndata, 0x20), mload(returndata)) } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ 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 (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_RLPReader * @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]). */ library Lib_RLPReader { /************* * Constants * *************/ uint256 constant internal MAX_LIST_LENGTH = 32; /********* * Enums * *********/ enum RLPItemType { DATA_ITEM, LIST_ITEM } /*********** * Structs * ***********/ struct RLPItem { uint256 length; uint256 ptr; } /********************** * Internal Functions * **********************/ /** * Converts bytes to a reference to memory position and length. * @param _in Input bytes to convert. * @return Output memory reference. */ function toRLPItem( bytes memory _in ) internal pure returns ( RLPItem memory ) { uint256 ptr; assembly { ptr := add(_in, 32) } return RLPItem({ length: _in.length, ptr: ptr }); } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList( RLPItem memory _in ) internal pure returns ( RLPItem[] memory ) { ( uint256 listOffset, , RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.LIST_ITEM, "Invalid RLP list value." ); // Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by // writing to the length. Since we can't know the number of RLP items without looping over // the entire input, we'd have to loop twice to accurately size this array. It's easier to // simply set a reasonable maximum list length and decrease the size before we finish. RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH); uint256 itemCount = 0; uint256 offset = listOffset; while (offset < _in.length) { require( itemCount < MAX_LIST_LENGTH, "Provided RLP list exceeds max list length." ); ( uint256 itemOffset, uint256 itemLength, ) = _decodeLength(RLPItem({ length: _in.length - offset, ptr: _in.ptr + offset })); out[itemCount] = RLPItem({ length: itemLength + itemOffset, ptr: _in.ptr + offset }); itemCount += 1; offset += itemOffset + itemLength; } // Decrease the array size to match the actual item count. assembly { mstore(out, itemCount) } return out; } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList( bytes memory _in ) internal pure returns ( RLPItem[] memory ) { return readList( toRLPItem(_in) ); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes( RLPItem memory _in ) internal pure returns ( bytes memory ) { ( uint256 itemOffset, uint256 itemLength, RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes value." ); return _copy(_in.ptr, itemOffset, itemLength); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes( bytes memory _in ) internal pure returns ( bytes memory ) { return readBytes( toRLPItem(_in) ); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString( RLPItem memory _in ) internal pure returns ( string memory ) { return string(readBytes(_in)); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString( bytes memory _in ) internal pure returns ( string memory ) { return readString( toRLPItem(_in) ); } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32( RLPItem memory _in ) internal pure returns ( bytes32 ) { require( _in.length <= 33, "Invalid RLP bytes32 value." ); ( uint256 itemOffset, uint256 itemLength, RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes32 value." ); uint256 ptr = _in.ptr + itemOffset; bytes32 out; assembly { out := mload(ptr) // Shift the bytes over to match the item size. if lt(itemLength, 32) { out := div(out, exp(256, sub(32, itemLength))) } } return out; } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32( bytes memory _in ) internal pure returns ( bytes32 ) { return readBytes32( toRLPItem(_in) ); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256( RLPItem memory _in ) internal pure returns ( uint256 ) { return uint256(readBytes32(_in)); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256( bytes memory _in ) internal pure returns ( uint256 ) { return readUint256( toRLPItem(_in) ); } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool( RLPItem memory _in ) internal pure returns ( bool ) { require( _in.length == 1, "Invalid RLP boolean value." ); uint256 ptr = _in.ptr; uint256 out; assembly { out := byte(0, mload(ptr)) } require( out == 0 || out == 1, "Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1" ); return out != 0; } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool( bytes memory _in ) internal pure returns ( bool ) { return readBool( toRLPItem(_in) ); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress( RLPItem memory _in ) internal pure returns ( address ) { if (_in.length == 1) { return address(0); } require( _in.length == 21, "Invalid RLP address value." ); return address(readUint256(_in)); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress( bytes memory _in ) internal pure returns ( address ) { return readAddress( toRLPItem(_in) ); } /** * Reads the raw bytes of an RLP item. * @param _in RLP item to read. * @return Raw RLP bytes. */ function readRawBytes( RLPItem memory _in ) internal pure returns ( bytes memory ) { return _copy(_in); } /********************* * Private Functions * *********************/ /** * Decodes the length of an RLP item. * @param _in RLP item to decode. * @return Offset of the encoded data. * @return Length of the encoded data. * @return RLP item type (LIST_ITEM or DATA_ITEM). */ function _decodeLength( RLPItem memory _in ) private pure returns ( uint256, uint256, RLPItemType ) { require( _in.length > 0, "RLP item cannot be null." ); uint256 ptr = _in.ptr; uint256 prefix; assembly { prefix := byte(0, mload(ptr)) } if (prefix <= 0x7f) { // Single byte. return (0, 1, RLPItemType.DATA_ITEM); } else if (prefix <= 0xb7) { // Short string. uint256 strLen = prefix - 0x80; require( _in.length > strLen, "Invalid RLP short string." ); return (1, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xbf) { // Long string. uint256 lenOfStrLen = prefix - 0xb7; require( _in.length > lenOfStrLen, "Invalid RLP long string length." ); uint256 strLen; assembly { // Pick out the string length. strLen := div( mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen)) ) } require( _in.length > lenOfStrLen + strLen, "Invalid RLP long string." ); return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xf7) { // Short list. uint256 listLen = prefix - 0xc0; require( _in.length > listLen, "Invalid RLP short list." ); return (1, listLen, RLPItemType.LIST_ITEM); } else { // Long list. uint256 lenOfListLen = prefix - 0xf7; require( _in.length > lenOfListLen, "Invalid RLP long list length." ); uint256 listLen; assembly { // Pick out the list length. listLen := div( mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen)) ) } require( _in.length > lenOfListLen + listLen, "Invalid RLP long list." ); return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM); } } /** * Copies the bytes from a memory location. * @param _src Pointer to the location to read from. * @param _offset Offset to start reading from. * @param _length Number of bytes to read. * @return Copied bytes. */ function _copy( uint256 _src, uint256 _offset, uint256 _length ) private pure returns ( bytes memory ) { bytes memory out = new bytes(_length); if (out.length == 0) { return out; } uint256 src = _src + _offset; uint256 dest; assembly { dest := add(out, 32) } // Copy over as many complete words as we can. for (uint256 i = 0; i < _length / 32; i++) { assembly { mstore(dest, mload(src)) } src += 32; dest += 32; } // Pick out the remaining bytes. uint256 mask = 256 ** (32 - (_length % 32)) - 1; assembly { mstore( dest, or( and(mload(src), not(mask)), and(mload(dest), mask) ) ) } return out; } /** * Copies an RLP item into bytes. * @param _in RLP item to copy. * @return Copied bytes. */ function _copy( RLPItem memory _in ) private pure returns ( bytes memory ) { return _copy(_in.ptr, 0, _in.length); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /** * @title Lib_RLPWriter * @author Bakaoh (with modifications) */ library Lib_RLPWriter { /********************** * Internal Functions * **********************/ /** * RLP encodes a byte string. * @param _in The byte string to encode. * @return The RLP encoded string in bytes. */ function writeBytes( bytes memory _in ) internal pure returns ( bytes memory ) { bytes memory encoded; if (_in.length == 1 && uint8(_in[0]) < 128) { encoded = _in; } else { encoded = abi.encodePacked(_writeLength(_in.length, 128), _in); } return encoded; } /** * RLP encodes a list of RLP encoded byte byte strings. * @param _in The list of RLP encoded byte strings. * @return The RLP encoded list of items in bytes. */ function writeList( bytes[] memory _in ) internal pure returns ( bytes memory ) { bytes memory list = _flatten(_in); return abi.encodePacked(_writeLength(list.length, 192), list); } /** * RLP encodes a string. * @param _in The string to encode. * @return The RLP encoded string in bytes. */ function writeString( string memory _in ) internal pure returns ( bytes memory ) { return writeBytes(bytes(_in)); } /** * RLP encodes an address. * @param _in The address to encode. * @return The RLP encoded address in bytes. */ function writeAddress( address _in ) internal pure returns ( bytes memory ) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a bytes32 value. * @param _in The bytes32 to encode. * @return _out The RLP encoded bytes32 in bytes. */ function writeBytes32( bytes32 _in ) internal pure returns ( bytes memory _out ) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a uint. * @param _in The uint256 to encode. * @return The RLP encoded uint256 in bytes. */ function writeUint( uint256 _in ) internal pure returns ( bytes memory ) { return writeBytes(_toBinary(_in)); } /** * RLP encodes a bool. * @param _in The bool to encode. * @return The RLP encoded bool in bytes. */ function writeBool( bool _in ) internal pure returns ( bytes memory ) { bytes memory encoded = new bytes(1); encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80)); return encoded; } /********************* * Private Functions * *********************/ /** * Encode the first byte, followed by the `len` in binary form if `length` is more than 55. * @param _len The length of the string or the payload. * @param _offset 128 if item is string, 192 if item is list. * @return RLP encoded bytes. */ function _writeLength( uint256 _len, uint256 _offset ) private pure returns ( bytes memory ) { bytes memory encoded; if (_len < 56) { encoded = new bytes(1); encoded[0] = byte(uint8(_len) + uint8(_offset)); } else { uint256 lenLen; uint256 i = 1; while (_len / i != 0) { lenLen++; i *= 256; } encoded = new bytes(lenLen + 1); encoded[0] = byte(uint8(lenLen) + uint8(_offset) + 55); for(i = 1; i <= lenLen; i++) { encoded[i] = byte(uint8((_len / (256**(lenLen-i))) % 256)); } } return encoded; } /** * Encode integer in big endian binary form with no leading zeroes. * @notice TODO: This should be optimized with assembly to save gas costs. * @param _x The integer to encode. * @return RLP encoded bytes. */ function _toBinary( uint256 _x ) private pure returns ( bytes memory ) { bytes memory b = abi.encodePacked(_x); uint256 i = 0; for (; i < 32; i++) { if (b[i] != 0) { break; } } bytes memory res = new bytes(32 - i); for (uint256 j = 0; j < res.length; j++) { res[j] = b[i++]; } return res; } /** * Copies a piece of memory to another location. * @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol. * @param _dest Destination location. * @param _src Source location. * @param _len Length of memory to copy. */ function _memcpy( uint256 _dest, uint256 _src, uint256 _len ) private pure { uint256 dest = _dest; uint256 src = _src; uint256 len = _len; for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } 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)) } } /** * Flattens a list of byte strings into one byte string. * @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol. * @param _list List of byte strings to flatten. * @return The flattened byte string. */ function _flatten( bytes[] memory _list ) private pure returns ( bytes memory ) { if (_list.length == 0) { return new bytes(0); } uint256 len; uint256 i = 0; for (; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint256 flattenedPtr; assembly { flattenedPtr := add(flattened, 0x20) } for(i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint256 listPtr; assembly { listPtr := add(item, 0x20)} _memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /** * @title Lib_ErrorUtils */ library Lib_ErrorUtils { /********************** * Internal Functions * **********************/ /** * Encodes an error string into raw solidity-style revert data. * (i.e. ascii bytes, prefixed with bytes4(keccak("Error(string))")) * Ref: https://docs.soliditylang.org/en/v0.8.2/control-structures.html?highlight=Error(string) * #panic-via-assert-and-error-via-require * @param _reason Reason for the reversion. * @return Standard solidity revert data for the given reason. */ function encodeRevertString( string memory _reason ) internal pure returns ( bytes memory ) { return abi.encodeWithSignature( "Error(string)", _reason ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol"; import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; import { Lib_ExecutionManagerWrapper } from "../../libraries/wrappers/Lib_ExecutionManagerWrapper.sol"; /** * @title OVM_ProxyEOA * @dev The Proxy EOA contract uses a delegate call to execute the logic in an implementation * contract. In combination with the logic implemented in the ECDSA Contract Account, this enables * a form of upgradable 'account abstraction' on layer 2. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_ProxyEOA { /********** * Events * **********/ event Upgraded( address indexed implementation ); /************* * Constants * *************/ // solhint-disable-next-line max-line-length bytes32 constant IMPLEMENTATION_KEY = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; //bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1); /********************* * Fallback Function * *********************/ fallback() external payable { (bool success, bytes memory returndata) = getImplementation().delegatecall(msg.data); if (success) { assembly { return(add(returndata, 0x20), mload(returndata)) } } else { assembly { revert(add(returndata, 0x20), mload(returndata)) } } } // WARNING: We use the deployed bytecode of this contract as a template to create ProxyEOA // contracts. As a result, we must *not* perform any constructor logic. Use initialization // functions if necessary. /******************** * Public Functions * ********************/ /** * Changes the implementation address. * @param _implementation New implementation address. */ function upgrade( address _implementation ) external { require( msg.sender == Lib_ExecutionManagerWrapper.ovmADDRESS(), "EOAs can only upgrade their own EOA implementation." ); _setImplementation(_implementation); emit Upgraded(_implementation); } /** * Gets the address of the current implementation. * @return Current implementation address. */ function getImplementation() public view returns ( address ) { bytes32 addr32; assembly { addr32 := sload(IMPLEMENTATION_KEY) } address implementation = Lib_Bytes32Utils.toAddress(addr32); if (implementation == address(0)) { return Lib_PredeployAddresses.ECDSA_CONTRACT_ACCOUNT; } else { return implementation; } } /********************** * Internal Functions * **********************/ function _setImplementation( address _implementation ) internal { bytes32 addr32 = Lib_Bytes32Utils.fromAddress(_implementation); assembly { sstore(IMPLEMENTATION_KEY, addr32) } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_Byte32Utils */ library Lib_Bytes32Utils { /********************** * Internal Functions * **********************/ /** * Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true." * @param _in Input bytes32 value. * @return Bytes32 as a boolean. */ function toBool( bytes32 _in ) internal pure returns ( bool ) { return _in != 0; } /** * Converts a boolean to a bytes32 value. * @param _in Input boolean value. * @return Boolean as a bytes32. */ function fromBool( bool _in ) internal pure returns ( bytes32 ) { return bytes32(uint256(_in ? 1 : 0)); } /** * Converts a bytes32 value to an address. Takes the *last* 20 bytes. * @param _in Input bytes32 value. * @return Bytes32 as an address. */ function toAddress( bytes32 _in ) internal pure returns ( address ) { return address(uint160(uint256(_in))); } /** * Converts an address to a bytes32. * @param _in Input address value. * @return Address as a bytes32. */ function fromAddress( address _in ) internal pure returns ( bytes32 ) { return bytes32(uint256(_in)); } /** * Removes the leading zeros from a bytes32 value and returns a new (smaller) bytes value. * @param _in Input bytes32 value. * @return Bytes32 without any leading zeros. */ function removeLeadingZeros( bytes32 _in ) internal pure returns ( bytes memory ) { bytes memory out; assembly { // Figure out how many leading zero bytes to remove. let shift := 0 for { let i := 0 } and(lt(i, 32), eq(byte(i, _in), 0)) { i := add(i, 1) } { shift := add(shift, 1) } // Reserve some space for our output and fix the free memory pointer. out := mload(0x40) mstore(0x40, add(out, 0x40)) // Shift the value and store it into the output bytes. mstore(add(out, 0x20), shl(mul(shift, 8), _in)) // Store the new size (with leading zero bytes removed) in the output byte size. mstore(out, sub(32, shift)) } return out; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_EIP155Tx } from "../../libraries/codec/Lib_EIP155Tx.sol"; import { Lib_ExecutionManagerWrapper } from "../../libraries/wrappers/Lib_ExecutionManagerWrapper.sol"; import { iOVM_ECDSAContractAccount } from "../../iOVM/predeploys/iOVM_ECDSAContractAccount.sol"; /** * @title OVM_SequencerEntrypoint * @dev The Sequencer Entrypoint is a predeploy which, despite its name, can in fact be called by * any account. It accepts a more efficient compressed calldata format, which it decompresses and * encodes to the standard EIP155 transaction format. * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_SequencerEntrypoint { /************* * Libraries * *************/ using Lib_EIP155Tx for Lib_EIP155Tx.EIP155Tx; /********************* * Fallback Function * *********************/ /** * Expects an RLP-encoded EIP155 transaction as input. See the EIP for a more detailed * description of this transaction format: * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md */ fallback() external { // We use this twice, so it's more gas efficient to store a copy of it (barely). bytes memory encodedTx = msg.data; // Decode the tx with the correct chain ID. Lib_EIP155Tx.EIP155Tx memory transaction = Lib_EIP155Tx.decode( encodedTx, Lib_ExecutionManagerWrapper.ovmCHAINID() ); // Value is computed on the fly. Keep it in the stack to save some gas. address target = transaction.sender(); bool isEmptyContract; assembly { isEmptyContract := iszero(extcodesize(target)) } // If the account is empty, deploy the default EOA to that address. if (isEmptyContract) { Lib_ExecutionManagerWrapper.ovmCREATEEOA( transaction.hash(), transaction.recoveryParam, transaction.r, transaction.s ); } // Forward the transaction over to the EOA. (bool success, bytes memory returndata) = target.call( abi.encodeWithSelector(iOVM_ECDSAContractAccount.execute.selector, transaction) ); if (success) { assembly { return(add(returndata, 0x20), mload(returndata)) } } else { assembly { revert(add(returndata, 0x20), mload(returndata)) } } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_EIP155Tx } from "../../optimistic-ethereum/libraries/codec/Lib_EIP155Tx.sol"; /** * @title TestLib_EIP155Tx */ contract TestLib_EIP155Tx { function decode( bytes memory _encoded, uint256 _chainId ) public pure returns ( Lib_EIP155Tx.EIP155Tx memory ) { return Lib_EIP155Tx.decode( _encoded, _chainId ); } function encode( Lib_EIP155Tx.EIP155Tx memory _transaction, bool _includeSignature ) public pure returns ( bytes memory ) { return Lib_EIP155Tx.encode( _transaction, _includeSignature ); } function hash( Lib_EIP155Tx.EIP155Tx memory _transaction ) public pure returns ( bytes32 ) { return Lib_EIP155Tx.hash( _transaction ); } function sender( Lib_EIP155Tx.EIP155Tx memory _transaction ) public pure returns ( address ) { return Lib_EIP155Tx.sender( _transaction ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPWriter } from "../../optimistic-ethereum/libraries/rlp/Lib_RLPWriter.sol"; import { TestERC20 } from "../../test-helpers/TestERC20.sol"; /** * @title TestLib_RLPWriter */ contract TestLib_RLPWriter { function writeBytes( bytes memory _in ) public pure returns ( bytes memory _out ) { return Lib_RLPWriter.writeBytes(_in); } function writeList( bytes[] memory _in ) public pure returns ( bytes memory _out ) { return Lib_RLPWriter.writeList(_in); } function writeString( string memory _in ) public pure returns ( bytes memory _out ) { return Lib_RLPWriter.writeString(_in); } function writeAddress( address _in ) public pure returns ( bytes memory _out ) { return Lib_RLPWriter.writeAddress(_in); } function writeUint( uint256 _in ) public pure returns ( bytes memory _out ) { return Lib_RLPWriter.writeUint(_in); } function writeBool( bool _in ) public pure returns ( bytes memory _out ) { return Lib_RLPWriter.writeBool(_in); } function writeAddressWithTaintedMemory( address _in ) public returns ( bytes memory _out ) { new TestERC20(); return Lib_RLPWriter.writeAddress(_in); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; // a test ERC20 token with an open mint function contract TestERC20 { using SafeMath for uint; string public constant name = 'Test'; string public constant symbol = 'TST'; uint8 public constant decimals = 18; uint256 public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); constructor() {} function mint(address to, uint256 value) public { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _approve(address owner, address spender, uint256 value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint256 value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint256 value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint256 value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint256 value) external returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } } library SafeMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_BytesUtils } from "../../optimistic-ethereum/libraries/utils/Lib_BytesUtils.sol"; import { TestERC20 } from "../../test-helpers/TestERC20.sol"; /** * @title TestLib_BytesUtils */ contract TestLib_BytesUtils { function concat( bytes memory _preBytes, bytes memory _postBytes ) public pure returns (bytes memory) { return abi.encodePacked( _preBytes, _postBytes ); } function slice( bytes memory _bytes, uint256 _start, uint256 _length ) public pure returns (bytes memory) { return Lib_BytesUtils.slice( _bytes, _start, _length ); } function toBytes32( bytes memory _bytes ) public pure returns (bytes32) { return Lib_BytesUtils.toBytes32( _bytes ); } function toUint256( bytes memory _bytes ) public pure returns (uint256) { return Lib_BytesUtils.toUint256( _bytes ); } function toNibbles( bytes memory _bytes ) public pure returns (bytes memory) { return Lib_BytesUtils.toNibbles( _bytes ); } function fromNibbles( bytes memory _bytes ) public pure returns (bytes memory) { return Lib_BytesUtils.fromNibbles( _bytes ); } function equal( bytes memory _bytes, bytes memory _other ) public pure returns (bool) { return Lib_BytesUtils.equal( _bytes, _other ); } function sliceWithTaintedMemory( bytes memory _bytes, uint256 _start, uint256 _length ) public returns (bytes memory) { new TestERC20(); return Lib_BytesUtils.slice( _bytes, _start, _length ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_BytesUtils */ library Lib_BytesUtils { /********************** * Internal Functions * **********************/ function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns ( bytes memory ) { require(_length + 31 >= _length, "slice_overflow"); require(_start + _length >= _start, "slice_overflow"); require(_bytes.length >= _start + _length, "slice_outOfBounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function slice( bytes memory _bytes, uint256 _start ) internal pure returns ( bytes memory ) { if (_start >= _bytes.length) { return bytes(""); } return slice(_bytes, _start, _bytes.length - _start); } function toBytes32PadLeft( bytes memory _bytes ) internal pure returns ( bytes32 ) { bytes32 ret; uint256 len = _bytes.length <= 32 ? _bytes.length : 32; assembly { ret := shr(mul(sub(32, len), 8), mload(add(_bytes, 32))) } return ret; } function toBytes32( bytes memory _bytes ) internal pure returns ( bytes32 ) { if (_bytes.length < 32) { bytes32 ret; assembly { ret := mload(add(_bytes, 32)) } return ret; } return abi.decode(_bytes,(bytes32)); // will truncate if input length > 32 bytes } function toUint256( bytes memory _bytes ) internal pure returns ( uint256 ) { return uint256(toBytes32(_bytes)); } function toUint24( bytes memory _bytes, uint256 _start ) internal pure returns ( uint24 ) { require(_start + 3 >= _start, "toUint24_overflow"); require(_bytes.length >= _start + 3 , "toUint24_outOfBounds"); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint8( bytes memory _bytes, uint256 _start ) internal pure returns ( uint8 ) { require(_start + 1 >= _start, "toUint8_overflow"); require(_bytes.length >= _start + 1 , "toUint8_outOfBounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toAddress( bytes memory _bytes, uint256 _start ) internal pure returns ( address ) { require(_start + 20 >= _start, "toAddress_overflow"); require(_bytes.length >= _start + 20, "toAddress_outOfBounds"); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toNibbles( bytes memory _bytes ) internal pure returns ( bytes memory ) { bytes memory nibbles = new bytes(_bytes.length * 2); for (uint256 i = 0; i < _bytes.length; i++) { nibbles[i * 2] = _bytes[i] >> 4; nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16); } return nibbles; } function fromNibbles( bytes memory _bytes ) internal pure returns ( bytes memory ) { bytes memory ret = new bytes(_bytes.length / 2); for (uint256 i = 0; i < ret.length; i++) { ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]); } return ret; } function equal( bytes memory _bytes, bytes memory _other ) internal pure returns ( bool ) { return keccak256(_bytes) == keccak256(_other); } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_EthUtils } from "../../libraries/utils/Lib_EthUtils.sol"; import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol"; import { Lib_BytesUtils } from "../../libraries/utils/Lib_BytesUtils.sol"; import { Lib_SecureMerkleTrie } from "../../libraries/trie/Lib_SecureMerkleTrie.sol"; import { Lib_RLPWriter } from "../../libraries/rlp/Lib_RLPWriter.sol"; import { Lib_RLPReader } from "../../libraries/rlp/Lib_RLPReader.sol"; /* Interface Imports */ import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol"; import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol"; import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol"; import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol"; import { iOVM_StateManagerFactory } from "../../iOVM/execution/iOVM_StateManagerFactory.sol"; /* Contract Imports */ import { Abs_FraudContributor } from "./Abs_FraudContributor.sol"; /** * @title OVM_StateTransitioner * @dev The State Transitioner coordinates the execution of a state transition during the evaluation * of a fraud proof. It feeds verified input to the Execution Manager's run(), and controls a * State Manager (which is uniquely created for each fraud proof). * Once a fraud proof has been initialized, this contract is provided with the pre-state root and * verifies that the OVM storage slots committed to the State Mangager are contained in that state * This contract controls the State Manager and Execution Manager, and uses them to calculate the * post-state root by applying the transaction. The Fraud Verifier can then check for fraud by * comparing the calculated post-state root with the proposed post-state root. * * Compiler used: solc * Runtime target: EVM */ contract OVM_StateTransitioner is Lib_AddressResolver, Abs_FraudContributor, iOVM_StateTransitioner { /******************* * Data Structures * *******************/ enum TransitionPhase { PRE_EXECUTION, POST_EXECUTION, COMPLETE } /******************************************* * Contract Variables: Contract References * *******************************************/ iOVM_StateManager public ovmStateManager; /******************************************* * Contract Variables: Internal Accounting * *******************************************/ bytes32 internal preStateRoot; bytes32 internal postStateRoot; TransitionPhase public phase; uint256 internal stateTransitionIndex; bytes32 internal transactionHash; /************* * Constants * *************/ // solhint-disable-next-line max-line-length bytes32 internal constant EMPTY_ACCOUNT_CODE_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line max-line-length bytes32 internal constant EMPTY_ACCOUNT_STORAGE_ROOT = 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. * @param _stateTransitionIndex Index of the state transition being verified. * @param _preStateRoot State root before the transition was executed. * @param _transactionHash Hash of the executed transaction. */ constructor( address _libAddressManager, uint256 _stateTransitionIndex, bytes32 _preStateRoot, bytes32 _transactionHash ) Lib_AddressResolver(_libAddressManager) { stateTransitionIndex = _stateTransitionIndex; preStateRoot = _preStateRoot; postStateRoot = _preStateRoot; transactionHash = _transactionHash; ovmStateManager = iOVM_StateManagerFactory(resolve("OVM_StateManagerFactory")) .create(address(this)); } /********************** * Function Modifiers * **********************/ /** * Checks that a function is only run during a specific phase. * @param _phase Phase the function must run within. */ modifier onlyDuringPhase( TransitionPhase _phase ) { require( phase == _phase, "Function must be called during the correct phase." ); _; } /********************************** * Public Functions: State Access * **********************************/ /** * Retrieves the state root before execution. * @return _preStateRoot State root before execution. */ function getPreStateRoot() override external view returns ( bytes32 _preStateRoot ) { return preStateRoot; } /** * Retrieves the state root after execution. * @return _postStateRoot State root after execution. */ function getPostStateRoot() override external view returns ( bytes32 _postStateRoot ) { return postStateRoot; } /** * Checks whether the transitioner is complete. * @return _complete Whether or not the transition process is finished. */ function isComplete() override external view returns ( bool _complete ) { return phase == TransitionPhase.COMPLETE; } /*********************************** * Public Functions: Pre-Execution * ***********************************/ /** * Allows a user to prove the initial state of a contract. * @param _ovmContractAddress Address of the contract on the OVM. * @param _ethContractAddress Address of the corresponding contract on L1. * @param _stateTrieWitness Proof of the account state. */ function proveContractState( address _ovmContractAddress, address _ethContractAddress, bytes memory _stateTrieWitness ) override external onlyDuringPhase(TransitionPhase.PRE_EXECUTION) contributesToFraudProof(preStateRoot, transactionHash) { // Exit quickly to avoid unnecessary work. require( ( ovmStateManager.hasAccount(_ovmContractAddress) == false && ovmStateManager.hasEmptyAccount(_ovmContractAddress) == false ), "Account state has already been proven." ); // Function will fail if the proof is not a valid inclusion or exclusion proof. ( bool exists, bytes memory encodedAccount ) = Lib_SecureMerkleTrie.get( abi.encodePacked(_ovmContractAddress), _stateTrieWitness, preStateRoot ); if (exists == true) { // Account exists, this was an inclusion proof. Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount( encodedAccount ); address ethContractAddress = _ethContractAddress; if (account.codeHash == EMPTY_ACCOUNT_CODE_HASH) { // Use a known empty contract to prevent an attack in which a user provides a // contract address here and then later deploys code to it. ethContractAddress = 0x0000000000000000000000000000000000000000; } else { // Otherwise, make sure that the code at the provided eth address matches the hash // of the code stored on L2. require( Lib_EthUtils.getCodeHash(ethContractAddress) == account.codeHash, // solhint-disable-next-line max-line-length "OVM_StateTransitioner: Provided L1 contract code hash does not match L2 contract code hash." ); } ovmStateManager.putAccount( _ovmContractAddress, Lib_OVMCodec.Account({ nonce: account.nonce, balance: account.balance, storageRoot: account.storageRoot, codeHash: account.codeHash, ethAddress: ethContractAddress, isFresh: false }) ); } else { // Account does not exist, this was an exclusion proof. ovmStateManager.putEmptyAccount(_ovmContractAddress); } } /** * Allows a user to prove the initial state of a contract storage slot. * @param _ovmContractAddress Address of the contract on the OVM. * @param _key Claimed account slot key. * @param _storageTrieWitness Proof of the storage slot. */ function proveStorageSlot( address _ovmContractAddress, bytes32 _key, bytes memory _storageTrieWitness ) override external onlyDuringPhase(TransitionPhase.PRE_EXECUTION) contributesToFraudProof(preStateRoot, transactionHash) { // Exit quickly to avoid unnecessary work. require( ovmStateManager.hasContractStorage(_ovmContractAddress, _key) == false, "Storage slot has already been proven." ); require( ovmStateManager.hasAccount(_ovmContractAddress) == true, "Contract must be verified before proving a storage slot." ); bytes32 storageRoot = ovmStateManager.getAccountStorageRoot(_ovmContractAddress); bytes32 value; if (storageRoot == EMPTY_ACCOUNT_STORAGE_ROOT) { // Storage trie was empty, so the user is always allowed to insert zero-byte values. value = bytes32(0); } else { // Function will fail if the proof is not a valid inclusion or exclusion proof. ( bool exists, bytes memory encodedValue ) = Lib_SecureMerkleTrie.get( abi.encodePacked(_key), _storageTrieWitness, storageRoot ); if (exists == true) { // Inclusion proof. // Stored values are RLP encoded, with leading zeros removed. value = Lib_BytesUtils.toBytes32PadLeft( Lib_RLPReader.readBytes(encodedValue) ); } else { // Exclusion proof, can only be zero bytes. value = bytes32(0); } } ovmStateManager.putContractStorage( _ovmContractAddress, _key, value ); } /******************************* * Public Functions: Execution * *******************************/ /** * Executes the state transition. * @param _transaction OVM transaction to execute. */ function applyTransaction( Lib_OVMCodec.Transaction memory _transaction ) override external onlyDuringPhase(TransitionPhase.PRE_EXECUTION) contributesToFraudProof(preStateRoot, transactionHash) { require( Lib_OVMCodec.hashTransaction(_transaction) == transactionHash, "Invalid transaction provided." ); // We require gas to complete the logic here in run() before/after execution, // But must ensure the full _tx.gasLimit can be given to the ovmCALL (determinism) // This includes 1/64 of the gas getting lost because of EIP-150 (lost twice--first // going into EM, then going into the code contract). require( // 1032/1000 = 1.032 = (64/63)^2 rounded up gasleft() >= 100000 + _transaction.gasLimit * 1032 / 1000, "Not enough gas to execute transaction deterministically." ); iOVM_ExecutionManager ovmExecutionManager = iOVM_ExecutionManager(resolve("OVM_ExecutionManager")); // We call `setExecutionManager` right before `run` (and not earlier) just in case the // OVM_ExecutionManager address was updated between the time when this contract was created // and when `applyTransaction` was called. ovmStateManager.setExecutionManager(address(ovmExecutionManager)); // `run` always succeeds *unless* the user hasn't provided enough gas to `applyTransaction` // or an INVALID_STATE_ACCESS flag was triggered. Either way, we won't get beyond this line // if that's the case. ovmExecutionManager.run(_transaction, address(ovmStateManager)); // Prevent the Execution Manager from calling this SM again. ovmStateManager.setExecutionManager(address(0)); phase = TransitionPhase.POST_EXECUTION; } /************************************ * Public Functions: Post-Execution * ************************************/ /** * Allows a user to commit the final state of a contract. * @param _ovmContractAddress Address of the contract on the OVM. * @param _stateTrieWitness Proof of the account state. */ function commitContractState( address _ovmContractAddress, bytes memory _stateTrieWitness ) override external onlyDuringPhase(TransitionPhase.POST_EXECUTION) contributesToFraudProof(preStateRoot, transactionHash) { require( ovmStateManager.getTotalUncommittedContractStorage() == 0, "All storage must be committed before committing account states." ); require ( ovmStateManager.commitAccount(_ovmContractAddress) == true, "Account state wasn't changed or has already been committed." ); Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress); postStateRoot = Lib_SecureMerkleTrie.update( abi.encodePacked(_ovmContractAddress), Lib_OVMCodec.encodeEVMAccount( Lib_OVMCodec.toEVMAccount(account) ), _stateTrieWitness, postStateRoot ); // Emit an event to help clients figure out the proof ordering. emit AccountCommitted( _ovmContractAddress ); } /** * Allows a user to commit the final state of a contract storage slot. * @param _ovmContractAddress Address of the contract on the OVM. * @param _key Claimed account slot key. * @param _storageTrieWitness Proof of the storage slot. */ function commitStorageSlot( address _ovmContractAddress, bytes32 _key, bytes memory _storageTrieWitness ) override external onlyDuringPhase(TransitionPhase.POST_EXECUTION) contributesToFraudProof(preStateRoot, transactionHash) { require( ovmStateManager.commitContractStorage(_ovmContractAddress, _key) == true, "Storage slot value wasn't changed or has already been committed." ); Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress); bytes32 value = ovmStateManager.getContractStorage(_ovmContractAddress, _key); account.storageRoot = Lib_SecureMerkleTrie.update( abi.encodePacked(_key), Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros(value) ), _storageTrieWitness, account.storageRoot ); ovmStateManager.putAccount(_ovmContractAddress, account); // Emit an event to help clients figure out the proof ordering. emit ContractStorageCommitted( _ovmContractAddress, _key ); } /********************************** * Public Functions: Finalization * **********************************/ /** * Finalizes the transition process. */ function completeTransition() override external onlyDuringPhase(TransitionPhase.POST_EXECUTION) { require( ovmStateManager.getTotalUncommittedAccounts() == 0, "All accounts must be committed before completing a transition." ); require( ovmStateManager.getTotalUncommittedContractStorage() == 0, "All storage must be committed before completing a transition." ); phase = TransitionPhase.COMPLETE; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol"; /** * @title Lib_OVMCodec */ library Lib_OVMCodec { /********* * Enums * *********/ enum QueueOrigin { SEQUENCER_QUEUE, L1TOL2_QUEUE } /*********** * Structs * ***********/ struct Account { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; address ethAddress; bool isFresh; } struct EVMAccount { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; } struct ChainBatchHeader { uint256 batchIndex; bytes32 batchRoot; uint256 batchSize; uint256 prevTotalElements; bytes extraData; } struct ChainInclusionProof { uint256 index; bytes32[] siblings; } struct Transaction { uint256 timestamp; uint256 blockNumber; QueueOrigin l1QueueOrigin; address l1TxOrigin; address entrypoint; uint256 gasLimit; bytes data; } struct TransactionChainElement { bool isSequenced; uint256 queueIndex; // QUEUED TX ONLY uint256 timestamp; // SEQUENCER TX ONLY uint256 blockNumber; // SEQUENCER TX ONLY bytes txData; // SEQUENCER TX ONLY } struct QueueElement { bytes32 transactionHash; uint40 timestamp; uint40 blockNumber; } /********************** * Internal Functions * **********************/ /** * Encodes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Encoded transaction bytes. */ function encodeTransaction( Transaction memory _transaction ) internal pure returns ( bytes memory ) { return abi.encodePacked( _transaction.timestamp, _transaction.blockNumber, _transaction.l1QueueOrigin, _transaction.l1TxOrigin, _transaction.entrypoint, _transaction.gasLimit, _transaction.data ); } /** * Hashes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Hashed transaction */ function hashTransaction( Transaction memory _transaction ) internal pure returns ( bytes32 ) { return keccak256(encodeTransaction(_transaction)); } /** * Converts an OVM account to an EVM account. * @param _in OVM account to convert. * @return Converted EVM account. */ function toEVMAccount( Account memory _in ) internal pure returns ( EVMAccount memory ) { return EVMAccount({ nonce: _in.nonce, balance: _in.balance, storageRoot: _in.storageRoot, codeHash: _in.codeHash }); } /** * @notice RLP-encodes an account state struct. * @param _account Account state struct. * @return RLP-encoded account state. */ function encodeEVMAccount( EVMAccount memory _account ) internal pure returns ( bytes memory ) { bytes[] memory raw = new bytes[](4); // Unfortunately we can't create this array outright because // Lib_RLPWriter.writeList will reject fixed-size arrays. Assigning // index-by-index circumvents this issue. raw[0] = Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros( bytes32(_account.nonce) ) ); raw[1] = Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros( bytes32(_account.balance) ) ); raw[2] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.storageRoot)); raw[3] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.codeHash)); return Lib_RLPWriter.writeList(raw); } /** * @notice Decodes an RLP-encoded account state into a useful struct. * @param _encoded RLP-encoded account state. * @return Account state struct. */ function decodeEVMAccount( bytes memory _encoded ) internal pure returns ( EVMAccount memory ) { Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded); return EVMAccount({ nonce: Lib_RLPReader.readUint256(accountState[0]), balance: Lib_RLPReader.readUint256(accountState[1]), storageRoot: Lib_RLPReader.readBytes32(accountState[2]), codeHash: Lib_RLPReader.readBytes32(accountState[3]) }); } /** * Calculates a hash for a given batch header. * @param _batchHeader Header to hash. * @return Hash of the header. */ function hashBatchHeader( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal pure returns ( bytes32 ) { return keccak256( abi.encode( _batchHeader.batchRoot, _batchHeader.batchSize, _batchHeader.prevTotalElements, _batchHeader.extraData ) ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_AddressManager } from "./Lib_AddressManager.sol"; /** * @title Lib_AddressResolver */ abstract contract Lib_AddressResolver { /************* * Variables * *************/ Lib_AddressManager public libAddressManager; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Lib_AddressManager. */ constructor( address _libAddressManager ) { libAddressManager = Lib_AddressManager(_libAddressManager); } /******************** * Public Functions * ********************/ /** * Resolves the address associated with a given name. * @param _name Name to resolve an address for. * @return Address associated with the given name. */ function resolve( string memory _name ) public view returns ( address ) { return libAddressManager.getAddress(_name); } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; import { Lib_Bytes32Utils } from "./Lib_Bytes32Utils.sol"; /** * @title Lib_EthUtils */ library Lib_EthUtils { /********************** * Internal Functions * **********************/ /** * Gets the code for a given address. * @param _address Address to get code for. * @param _offset Offset to start reading from. * @param _length Number of bytes to read. * @return Code read from the contract. */ function getCode( address _address, uint256 _offset, uint256 _length ) internal view returns ( bytes memory ) { bytes memory code; assembly { code := mload(0x40) mstore(0x40, add(code, add(_length, 0x20))) mstore(code, _length) extcodecopy(_address, add(code, 0x20), _offset, _length) } return code; } /** * Gets the full code for a given address. * @param _address Address to get code for. * @return Full code of the contract. */ function getCode( address _address ) internal view returns ( bytes memory ) { return getCode( _address, 0, getCodeSize(_address) ); } /** * Gets the size of a contract's code in bytes. * @param _address Address to get code size for. * @return Size of the contract's code in bytes. */ function getCodeSize( address _address ) internal view returns ( uint256 ) { uint256 codeSize; assembly { codeSize := extcodesize(_address) } return codeSize; } /** * Gets the hash of a contract's code. * @param _address Address to get a code hash for. * @return Hash of the contract's code. */ function getCodeHash( address _address ) internal view returns ( bytes32 ) { bytes32 codeHash; assembly { codeHash := extcodehash(_address) } return codeHash; } /** * Creates a contract with some given initialization code. * @param _code Contract initialization code. * @return Address of the created contract. */ function createContract( bytes memory _code ) internal returns ( address ) { address created; assembly { created := create( 0, add(_code, 0x20), mload(_code) ) } return created; } /** * Computes the address that would be generated by CREATE. * @param _creator Address creating the contract. * @param _nonce Creator's nonce. * @return Address to be generated by CREATE. */ function getAddressForCREATE( address _creator, uint256 _nonce ) internal pure returns ( address ) { bytes[] memory encoded = new bytes[](2); encoded[0] = Lib_RLPWriter.writeAddress(_creator); encoded[1] = Lib_RLPWriter.writeUint(_nonce); bytes memory encodedList = Lib_RLPWriter.writeList(encoded); return Lib_Bytes32Utils.toAddress(keccak256(encodedList)); } /** * Computes the address that would be generated by CREATE2. * @param _creator Address creating the contract. * @param _bytecode Bytecode of the contract to be created. * @param _salt 32 byte salt value mixed into the hash. * @return Address to be generated by CREATE2. */ function getAddressForCREATE2( address _creator, bytes memory _bytecode, bytes32 _salt ) internal pure returns ( address ) { bytes32 hashedData = keccak256(abi.encodePacked( byte(0xff), _creator, _salt, keccak256(_bytecode) )); return Lib_Bytes32Utils.toAddress(hashedData); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_MerkleTrie } from "./Lib_MerkleTrie.sol"; /** * @title Lib_SecureMerkleTrie */ library Lib_SecureMerkleTrie { /********************** * Internal Functions * **********************/ /** * @notice Verifies a proof that a given key/value pair is present in the * Merkle trie. * @param _key Key of the node to search for, as a hex string. * @param _value Value of the node to search for, as a hex string. * @param _proof Merkle trie inclusion proof for the desired node. Unlike * traditional Merkle trees, this proof is executed top-down and consists * of a list of RLP-encoded nodes that make a path down to the target node. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _verified `true` if the k/v pair exists in the trie, `false` otherwise. */ function verifyInclusionProof( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _verified ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.verifyInclusionProof(key, _value, _proof, _root); } /** * @notice Updates a Merkle trie and returns a new root hash. * @param _key Key of the node to update, as a hex string. * @param _value Value of the node to update, as a hex string. * @param _proof Merkle trie inclusion proof for the node *nearest* the * target node. If the key exists, we can simply update the value. * Otherwise, we need to modify the trie to handle the new k/v pair. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _updatedRoot Root hash of the newly constructed trie. */ function update( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bytes32 _updatedRoot ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.update(key, _value, _proof, _root); } /** * @notice Retrieves the value associated with a given key. * @param _key Key to search for, as hex bytes. * @param _proof Merkle trie inclusion proof for the key. * @param _root Known root of the Merkle trie. * @return _exists Whether or not the key exists. * @return _value Value of the key if it exists. */ function get( bytes memory _key, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _exists, bytes memory _value ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.get(key, _proof, _root); } /** * Computes the root hash for a trie with a single node. * @param _key Key for the single node. * @param _value Value for the single node. * @return _updatedRoot Hash of the trie. */ function getSingleNodeRootHash( bytes memory _key, bytes memory _value ) internal pure returns ( bytes32 _updatedRoot ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.getSingleNodeRootHash(key, _value); } /********************* * Private Functions * *********************/ /** * Computes the secure counterpart to a key. * @param _key Key to get a secure key from. * @return _secureKey Secure version of the key. */ function _getSecureKey( bytes memory _key ) private pure returns ( bytes memory _secureKey ) { return abi.encodePacked(keccak256(_key)); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /** * @title iOVM_StateTransitioner */ interface iOVM_StateTransitioner { /********** * Events * **********/ event AccountCommitted( address _address ); event ContractStorageCommitted( address _address, bytes32 _key ); /********************************** * Public Functions: State Access * **********************************/ function getPreStateRoot() external view returns (bytes32 _preStateRoot); function getPostStateRoot() external view returns (bytes32 _postStateRoot); function isComplete() external view returns (bool _complete); /*********************************** * Public Functions: Pre-Execution * ***********************************/ function proveContractState( address _ovmContractAddress, address _ethContractAddress, bytes calldata _stateTrieWitness ) external; function proveStorageSlot( address _ovmContractAddress, bytes32 _key, bytes calldata _storageTrieWitness ) external; /******************************* * Public Functions: Execution * *******************************/ function applyTransaction( Lib_OVMCodec.Transaction calldata _transaction ) external; /************************************ * Public Functions: Post-Execution * ************************************/ function commitContractState( address _ovmContractAddress, bytes calldata _stateTrieWitness ) external; function commitStorageSlot( address _ovmContractAddress, bytes32 _key, bytes calldata _storageTrieWitness ) external; /********************************** * Public Functions: Finalization * **********************************/ function completeTransition() external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; interface ERC20 { function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); } /// All the errors which may be encountered on the bond manager library Errors { string constant ERC20_ERR = "BondManager: Could not post bond"; // solhint-disable-next-line max-line-length string constant ALREADY_FINALIZED = "BondManager: Fraud proof for this pre-state root has already been finalized"; string constant SLASHED = "BondManager: Cannot finalize withdrawal, you probably got slashed"; string constant WRONG_STATE = "BondManager: Wrong bond state for proposer"; string constant CANNOT_CLAIM = "BondManager: Cannot claim yet. Dispute must be finalized first"; string constant WITHDRAWAL_PENDING = "BondManager: Withdrawal already pending"; string constant TOO_EARLY = "BondManager: Too early to finalize your withdrawal"; // solhint-disable-next-line max-line-length string constant ONLY_TRANSITIONER = "BondManager: Only the transitioner for this pre-state root may call this function"; // solhint-disable-next-line max-line-length string constant ONLY_FRAUD_VERIFIER = "BondManager: Only the fraud verifier may call this function"; // solhint-disable-next-line max-line-length string constant ONLY_STATE_COMMITMENT_CHAIN = "BondManager: Only the state commitment chain may call this function"; string constant WAIT_FOR_DISPUTES = "BondManager: Wait for other potential disputes"; } /** * @title iOVM_BondManager */ interface iOVM_BondManager { /******************* * Data Structures * *******************/ /// The lifecycle of a proposer's bond enum State { // Before depositing or after getting slashed, a user is uncollateralized NOT_COLLATERALIZED, // After depositing, a user is collateralized COLLATERALIZED, // After a user has initiated a withdrawal WITHDRAWING } /// A bond posted by a proposer struct Bond { // The user's state State state; // The timestamp at which a proposer issued their withdrawal request uint32 withdrawalTimestamp; // The time when the first disputed was initiated for this bond uint256 firstDisputeAt; // The earliest observed state root for this bond which has had fraud bytes32 earliestDisputedStateRoot; // The state root's timestamp uint256 earliestTimestamp; } // Per pre-state root, store the number of state provisions that were made // and how many of these calls were made by each user. Payouts will then be // claimed by users proportionally for that dispute. struct Rewards { // Flag to check if rewards for a fraud proof are claimable bool canClaim; // Total number of `recordGasSpent` calls made uint256 total; // The gas spent by each user to provide witness data. The sum of all // values inside this map MUST be equal to the value of `total` mapping(address => uint256) gasSpent; } /******************** * Public Functions * ********************/ function recordGasSpent( bytes32 _preStateRoot, bytes32 _txHash, address _who, uint256 _gasSpent ) external; function finalize( bytes32 _preStateRoot, address _publisher, uint256 _timestamp ) external; function deposit() external; function startWithdrawal() external; function finalizeWithdrawal() external; function claim( address _who ) external; function isCollateralized( address _who ) external view returns (bool); function getGasSpent( bytes32 _preStateRoot, address _who ) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; interface iOVM_ExecutionManager { /********** * Enums * *********/ enum RevertFlag { OUT_OF_GAS, INTENTIONAL_REVERT, EXCEEDS_NUISANCE_GAS, INVALID_STATE_ACCESS, UNSAFE_BYTECODE, CREATE_COLLISION, STATIC_VIOLATION, CREATOR_NOT_ALLOWED } enum GasMetadataKey { CURRENT_EPOCH_START_TIMESTAMP, CUMULATIVE_SEQUENCER_QUEUE_GAS, CUMULATIVE_L1TOL2_QUEUE_GAS, PREV_EPOCH_SEQUENCER_QUEUE_GAS, PREV_EPOCH_L1TOL2_QUEUE_GAS } enum MessageType { ovmCALL, ovmSTATICCALL, ovmDELEGATECALL, ovmCREATE, ovmCREATE2 } /*********** * Structs * ***********/ struct GasMeterConfig { uint256 minTransactionGasLimit; uint256 maxTransactionGasLimit; uint256 maxGasPerQueuePerEpoch; uint256 secondsPerEpoch; } struct GlobalContext { uint256 ovmCHAINID; } struct TransactionContext { Lib_OVMCodec.QueueOrigin ovmL1QUEUEORIGIN; uint256 ovmTIMESTAMP; uint256 ovmNUMBER; uint256 ovmGASLIMIT; uint256 ovmTXGASLIMIT; address ovmL1TXORIGIN; } struct TransactionRecord { uint256 ovmGasRefund; } struct MessageContext { address ovmCALLER; address ovmADDRESS; uint256 ovmCALLVALUE; bool isStatic; } struct MessageRecord { uint256 nuisanceGasLeft; } /************************************ * Transaction Execution Entrypoint * ************************************/ function run( Lib_OVMCodec.Transaction calldata _transaction, address _txStateManager ) external returns (bytes memory); /******************* * Context Opcodes * *******************/ function ovmCALLER() external view returns (address _caller); function ovmADDRESS() external view returns (address _address); function ovmCALLVALUE() external view returns (uint _callValue); function ovmTIMESTAMP() external view returns (uint256 _timestamp); function ovmNUMBER() external view returns (uint256 _number); function ovmGASLIMIT() external view returns (uint256 _gasLimit); function ovmCHAINID() external view returns (uint256 _chainId); /********************** * L2 Context Opcodes * **********************/ function ovmL1QUEUEORIGIN() external view returns (Lib_OVMCodec.QueueOrigin _queueOrigin); function ovmL1TXORIGIN() external view returns (address _l1TxOrigin); /******************* * Halting Opcodes * *******************/ function ovmREVERT(bytes memory _data) external; /***************************** * Contract Creation Opcodes * *****************************/ function ovmCREATE(bytes memory _bytecode) external returns (address _contract, bytes memory _revertdata); function ovmCREATE2(bytes memory _bytecode, bytes32 _salt) external returns (address _contract, bytes memory _revertdata); /******************************* * Account Abstraction Opcodes * ******************************/ function ovmGETNONCE() external returns (uint256 _nonce); function ovmINCREMENTNONCE() external; function ovmCREATEEOA(bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s) external; /**************************** * Contract Calling Opcodes * ****************************/ // Valueless ovmCALL for maintaining backwards compatibility with legacy OVM bytecode. function ovmCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); function ovmCALL(uint256 _gasLimit, address _address, uint256 _value, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); function ovmSTATICCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); function ovmDELEGATECALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); /**************************** * Contract Storage Opcodes * ****************************/ function ovmSLOAD(bytes32 _key) external returns (bytes32 _value); function ovmSSTORE(bytes32 _key, bytes32 _value) external; /************************* * Contract Code Opcodes * *************************/ function ovmEXTCODECOPY(address _contract, uint256 _offset, uint256 _length) external returns (bytes memory _code); function ovmEXTCODESIZE(address _contract) external returns (uint256 _size); function ovmEXTCODEHASH(address _contract) external returns (bytes32 _hash); /********************* * ETH Value Opcodes * *********************/ function ovmBALANCE(address _contract) external returns (uint256 _balance); function ovmSELFBALANCE() external returns (uint256 _balance); /*************************************** * Public Functions: Execution Context * ***************************************/ function getMaxTransactionGasLimit() external view returns (uint _maxTransactionGasLimit); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /** * @title iOVM_StateManager */ interface iOVM_StateManager { /******************* * Data Structures * *******************/ enum ItemState { ITEM_UNTOUCHED, ITEM_LOADED, ITEM_CHANGED, ITEM_COMMITTED } /*************************** * Public Functions: Misc * ***************************/ function isAuthenticated(address _address) external view returns (bool); /*************************** * Public Functions: Setup * ***************************/ function owner() external view returns (address _owner); function ovmExecutionManager() external view returns (address _ovmExecutionManager); function setExecutionManager(address _ovmExecutionManager) external; /************************************ * Public Functions: Account Access * ************************************/ function putAccount(address _address, Lib_OVMCodec.Account memory _account) external; function putEmptyAccount(address _address) external; function getAccount(address _address) external view returns (Lib_OVMCodec.Account memory _account); function hasAccount(address _address) external view returns (bool _exists); function hasEmptyAccount(address _address) external view returns (bool _exists); function setAccountNonce(address _address, uint256 _nonce) external; function getAccountNonce(address _address) external view returns (uint256 _nonce); function getAccountEthAddress(address _address) external view returns (address _ethAddress); function getAccountStorageRoot(address _address) external view returns (bytes32 _storageRoot); function initPendingAccount(address _address) external; function commitPendingAccount(address _address, address _ethAddress, bytes32 _codeHash) external; function testAndSetAccountLoaded(address _address) external returns (bool _wasAccountAlreadyLoaded); function testAndSetAccountChanged(address _address) external returns (bool _wasAccountAlreadyChanged); function commitAccount(address _address) external returns (bool _wasAccountCommitted); function incrementTotalUncommittedAccounts() external; function getTotalUncommittedAccounts() external view returns (uint256 _total); function wasAccountChanged(address _address) external view returns (bool); function wasAccountCommitted(address _address) external view returns (bool); /************************************ * Public Functions: Storage Access * ************************************/ function putContractStorage(address _contract, bytes32 _key, bytes32 _value) external; function getContractStorage(address _contract, bytes32 _key) external view returns (bytes32 _value); function hasContractStorage(address _contract, bytes32 _key) external view returns (bool _exists); function testAndSetContractStorageLoaded(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyLoaded); function testAndSetContractStorageChanged(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyChanged); function commitContractStorage(address _contract, bytes32 _key) external returns (bool _wasContractStorageCommitted); function incrementTotalUncommittedContractStorage() external; function getTotalUncommittedContractStorage() external view returns (uint256 _total); function wasContractStorageChanged(address _contract, bytes32 _key) external view returns (bool); function wasContractStorageCommitted(address _contract, bytes32 _key) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Contract Imports */ import { iOVM_StateManager } from "./iOVM_StateManager.sol"; /** * @title iOVM_StateManagerFactory */ interface iOVM_StateManagerFactory { /*************************************** * Public Functions: Contract Creation * ***************************************/ function create( address _owner ) external returns ( iOVM_StateManager _ovmStateManager ); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /// Minimal contract to be inherited by contracts consumed by users that provide /// data for fraud proofs abstract contract Abs_FraudContributor is Lib_AddressResolver { /// Decorate your functions with this modifier to store how much total gas was /// consumed by the sender, to reward users fairly modifier contributesToFraudProof(bytes32 preStateRoot, bytes32 txHash) { uint256 startGas = gasleft(); _; uint256 gasSpent = startGas - gasleft(); iOVM_BondManager(resolve("OVM_BondManager")) .recordGasSpent(preStateRoot, txHash, msg.sender, gasSpent); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* External Imports */ import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Lib_AddressManager */ contract Lib_AddressManager is Ownable { /********** * Events * **********/ event AddressSet( string indexed _name, address _newAddress, address _oldAddress ); /************* * Variables * *************/ mapping (bytes32 => address) private addresses; /******************** * Public Functions * ********************/ /** * Changes the address associated with a particular name. * @param _name String name to associate an address with. * @param _address Address to associate with the name. */ function setAddress( string memory _name, address _address ) external onlyOwner { bytes32 nameHash = _getNameHash(_name); address oldAddress = addresses[nameHash]; addresses[nameHash] = _address; emit AddressSet( _name, _address, oldAddress ); } /** * Retrieves the address associated with a given name. * @param _name Name to retrieve an address for. * @return Address associated with the given name. */ function getAddress( string memory _name ) external view returns ( address ) { return addresses[_getNameHash(_name)]; } /********************** * Internal Functions * **********************/ /** * Computes the hash of a name. * @param _name Name to compute a hash for. * @return Hash of the given name. */ function _getNameHash( string memory _name ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_name)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 () 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; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; /** * @title Lib_MerkleTrie */ library Lib_MerkleTrie { /******************* * Data Structures * *******************/ enum NodeType { BranchNode, ExtensionNode, LeafNode } struct TrieNode { bytes encoded; Lib_RLPReader.RLPItem[] decoded; } /********************** * Contract Constants * **********************/ // TREE_RADIX determines the number of elements per branch node. uint256 constant TREE_RADIX = 16; // Branch nodes have TREE_RADIX elements plus an additional `value` slot. uint256 constant BRANCH_NODE_LENGTH = TREE_RADIX + 1; // Leaf nodes and extension nodes always have two elements, a `path` and a `value`. uint256 constant LEAF_OR_EXTENSION_NODE_LENGTH = 2; // Prefixes are prepended to the `path` within a leaf or extension node and // allow us to differentiate between the two node types. `ODD` or `EVEN` is // determined by the number of nibbles within the unprefixed `path`. If the // number of nibbles if even, we need to insert an extra padding nibble so // the resulting prefixed `path` has an even number of nibbles. uint8 constant PREFIX_EXTENSION_EVEN = 0; uint8 constant PREFIX_EXTENSION_ODD = 1; uint8 constant PREFIX_LEAF_EVEN = 2; uint8 constant PREFIX_LEAF_ODD = 3; // Just a utility constant. RLP represents `NULL` as 0x80. bytes1 constant RLP_NULL = bytes1(0x80); bytes constant RLP_NULL_BYTES = hex'80'; bytes32 constant internal KECCAK256_RLP_NULL_BYTES = keccak256(RLP_NULL_BYTES); /********************** * Internal Functions * **********************/ /** * @notice Verifies a proof that a given key/value pair is present in the * Merkle trie. * @param _key Key of the node to search for, as a hex string. * @param _value Value of the node to search for, as a hex string. * @param _proof Merkle trie inclusion proof for the desired node. Unlike * traditional Merkle trees, this proof is executed top-down and consists * of a list of RLP-encoded nodes that make a path down to the target node. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _verified `true` if the k/v pair exists in the trie, `false` otherwise. */ function verifyInclusionProof( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _verified ) { ( bool exists, bytes memory value ) = get(_key, _proof, _root); return ( exists && Lib_BytesUtils.equal(_value, value) ); } /** * @notice Updates a Merkle trie and returns a new root hash. * @param _key Key of the node to update, as a hex string. * @param _value Value of the node to update, as a hex string. * @param _proof Merkle trie inclusion proof for the node *nearest* the * target node. If the key exists, we can simply update the value. * Otherwise, we need to modify the trie to handle the new k/v pair. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _updatedRoot Root hash of the newly constructed trie. */ function update( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bytes32 _updatedRoot ) { // Special case when inserting the very first node. if (_root == KECCAK256_RLP_NULL_BYTES) { return getSingleNodeRootHash(_key, _value); } TrieNode[] memory proof = _parseProof(_proof); (uint256 pathLength, bytes memory keyRemainder, ) = _walkNodePath(proof, _key, _root); TrieNode[] memory newPath = _getNewPath(proof, pathLength, _key, keyRemainder, _value); return _getUpdatedTrieRoot(newPath, _key); } /** * @notice Retrieves the value associated with a given key. * @param _key Key to search for, as hex bytes. * @param _proof Merkle trie inclusion proof for the key. * @param _root Known root of the Merkle trie. * @return _exists Whether or not the key exists. * @return _value Value of the key if it exists. */ function get( bytes memory _key, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _exists, bytes memory _value ) { TrieNode[] memory proof = _parseProof(_proof); (uint256 pathLength, bytes memory keyRemainder, bool isFinalNode) = _walkNodePath(proof, _key, _root); bool exists = keyRemainder.length == 0; require( exists || isFinalNode, "Provided proof is invalid." ); bytes memory value = exists ? _getNodeValue(proof[pathLength - 1]) : bytes(""); return ( exists, value ); } /** * Computes the root hash for a trie with a single node. * @param _key Key for the single node. * @param _value Value for the single node. * @return _updatedRoot Hash of the trie. */ function getSingleNodeRootHash( bytes memory _key, bytes memory _value ) internal pure returns ( bytes32 _updatedRoot ) { return keccak256(_makeLeafNode( Lib_BytesUtils.toNibbles(_key), _value ).encoded); } /********************* * Private Functions * *********************/ /** * @notice Walks through a proof using a provided key. * @param _proof Inclusion proof to walk through. * @param _key Key to use for the walk. * @param _root Known root of the trie. * @return _pathLength Length of the final path * @return _keyRemainder Portion of the key remaining after the walk. * @return _isFinalNode Whether or not we've hit a dead end. */ function _walkNodePath( TrieNode[] memory _proof, bytes memory _key, bytes32 _root ) private pure returns ( uint256 _pathLength, bytes memory _keyRemainder, bool _isFinalNode ) { uint256 pathLength = 0; bytes memory key = Lib_BytesUtils.toNibbles(_key); bytes32 currentNodeID = _root; uint256 currentKeyIndex = 0; uint256 currentKeyIncrement = 0; TrieNode memory currentNode; // Proof is top-down, so we start at the first element (root). for (uint256 i = 0; i < _proof.length; i++) { currentNode = _proof[i]; currentKeyIndex += currentKeyIncrement; // Keep track of the proof elements we actually need. // It's expensive to resize arrays, so this simply reduces gas costs. pathLength += 1; if (currentKeyIndex == 0) { // First proof element is always the root node. require( keccak256(currentNode.encoded) == currentNodeID, "Invalid root hash" ); } else if (currentNode.encoded.length >= 32) { // Nodes 32 bytes or larger are hashed inside branch nodes. require( keccak256(currentNode.encoded) == currentNodeID, "Invalid large internal hash" ); } else { // Nodes smaller than 31 bytes aren't hashed. require( Lib_BytesUtils.toBytes32(currentNode.encoded) == currentNodeID, "Invalid internal node hash" ); } if (currentNode.decoded.length == BRANCH_NODE_LENGTH) { if (currentKeyIndex == key.length) { // We've hit the end of the key // meaning the value should be within this branch node. break; } else { // We're not at the end of the key yet. // Figure out what the next node ID should be and continue. uint8 branchKey = uint8(key[currentKeyIndex]); Lib_RLPReader.RLPItem memory nextNode = currentNode.decoded[branchKey]; currentNodeID = _getNodeID(nextNode); currentKeyIncrement = 1; continue; } } else if (currentNode.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) { bytes memory path = _getNodePath(currentNode); uint8 prefix = uint8(path[0]); uint8 offset = 2 - prefix % 2; bytes memory pathRemainder = Lib_BytesUtils.slice(path, offset); bytes memory keyRemainder = Lib_BytesUtils.slice(key, currentKeyIndex); uint256 sharedNibbleLength = _getSharedNibbleLength(pathRemainder, keyRemainder); if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) { if ( pathRemainder.length == sharedNibbleLength && keyRemainder.length == sharedNibbleLength ) { // The key within this leaf matches our key exactly. // Increment the key index to reflect that we have no remainder. currentKeyIndex += sharedNibbleLength; } // We've hit a leaf node, so our next node should be NULL. currentNodeID = bytes32(RLP_NULL); break; } else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) { if (sharedNibbleLength != pathRemainder.length) { // Our extension node is not identical to the remainder. // We've hit the end of this path // updates will need to modify this extension. currentNodeID = bytes32(RLP_NULL); break; } else { // Our extension shares some nibbles. // Carry on to the next node. currentNodeID = _getNodeID(currentNode.decoded[1]); currentKeyIncrement = sharedNibbleLength; continue; } } else { revert("Received a node with an unknown prefix"); } } else { revert("Received an unparseable node."); } } // If our node ID is NULL, then we're at a dead end. bool isFinalNode = currentNodeID == bytes32(RLP_NULL); return (pathLength, Lib_BytesUtils.slice(key, currentKeyIndex), isFinalNode); } /** * @notice Creates new nodes to support a k/v pair insertion into a given Merkle trie path. * @param _path Path to the node nearest the k/v pair. * @param _pathLength Length of the path. Necessary because the provided path may include * additional nodes (e.g., it comes directly from a proof) and we can't resize in-memory * arrays without costly duplication. * @param _key Full original key. * @param _keyRemainder Portion of the initial key that must be inserted into the trie. * @param _value Value to insert at the given key. * @return _newPath A new path with the inserted k/v pair and extra supporting nodes. */ function _getNewPath( TrieNode[] memory _path, uint256 _pathLength, bytes memory _key, bytes memory _keyRemainder, bytes memory _value ) private pure returns ( TrieNode[] memory _newPath ) { bytes memory keyRemainder = _keyRemainder; // Most of our logic depends on the status of the last node in the path. TrieNode memory lastNode = _path[_pathLength - 1]; NodeType lastNodeType = _getNodeType(lastNode); // Create an array for newly created nodes. // We need up to three new nodes, depending on the contents of the last node. // Since array resizing is expensive, we'll keep track of the size manually. // We're using an explicit `totalNewNodes += 1` after insertions for clarity. TrieNode[] memory newNodes = new TrieNode[](3); uint256 totalNewNodes = 0; // solhint-disable-next-line max-line-length // Reference: https://github.com/ethereumjs/merkle-patricia-tree/blob/c0a10395aab37d42c175a47114ebfcbd7efcf059/src/baseTrie.ts#L294-L313 bool matchLeaf = false; if (lastNodeType == NodeType.LeafNode) { uint256 l = 0; if (_path.length > 0) { for (uint256 i = 0; i < _path.length - 1; i++) { if (_getNodeType(_path[i]) == NodeType.BranchNode) { l++; } else { l += _getNodeKey(_path[i]).length; } } } if ( _getSharedNibbleLength( _getNodeKey(lastNode), Lib_BytesUtils.slice(Lib_BytesUtils.toNibbles(_key), l) ) == _getNodeKey(lastNode).length && keyRemainder.length == 0 ) { matchLeaf = true; } } if (matchLeaf) { // We've found a leaf node with the given key. // Simply need to update the value of the node to match. newNodes[totalNewNodes] = _makeLeafNode(_getNodeKey(lastNode), _value); totalNewNodes += 1; } else if (lastNodeType == NodeType.BranchNode) { if (keyRemainder.length == 0) { // We've found a branch node with the given key. // Simply need to update the value of the node to match. newNodes[totalNewNodes] = _editBranchValue(lastNode, _value); totalNewNodes += 1; } else { // We've found a branch node, but it doesn't contain our key. // Reinsert the old branch for now. newNodes[totalNewNodes] = lastNode; totalNewNodes += 1; // Create a new leaf node, slicing our remainder since the first byte points // to our branch node. newNodes[totalNewNodes] = _makeLeafNode(Lib_BytesUtils.slice(keyRemainder, 1), _value); totalNewNodes += 1; } } else { // Our last node is either an extension node or a leaf node with a different key. bytes memory lastNodeKey = _getNodeKey(lastNode); uint256 sharedNibbleLength = _getSharedNibbleLength(lastNodeKey, keyRemainder); if (sharedNibbleLength != 0) { // We've got some shared nibbles between the last node and our key remainder. // We'll need to insert an extension node that covers these shared nibbles. bytes memory nextNodeKey = Lib_BytesUtils.slice(lastNodeKey, 0, sharedNibbleLength); newNodes[totalNewNodes] = _makeExtensionNode(nextNodeKey, _getNodeHash(_value)); totalNewNodes += 1; // Cut down the keys since we've just covered these shared nibbles. lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, sharedNibbleLength); keyRemainder = Lib_BytesUtils.slice(keyRemainder, sharedNibbleLength); } // Create an empty branch to fill in. TrieNode memory newBranch = _makeEmptyBranchNode(); if (lastNodeKey.length == 0) { // Key remainder was larger than the key for our last node. // The value within our last node is therefore going to be shifted into // a branch value slot. newBranch = _editBranchValue(newBranch, _getNodeValue(lastNode)); } else { // Last node key was larger than the key remainder. // We're going to modify some index of our branch. uint8 branchKey = uint8(lastNodeKey[0]); // Move on to the next nibble. lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, 1); if (lastNodeType == NodeType.LeafNode) { // We're dealing with a leaf node. // We'll modify the key and insert the old leaf node into the branch index. TrieNode memory modifiedLastNode = _makeLeafNode(lastNodeKey, _getNodeValue(lastNode)); newBranch = _editBranchIndex( newBranch, branchKey, _getNodeHash(modifiedLastNode.encoded)); } else if (lastNodeKey.length != 0) { // We're dealing with a shrinking extension node. // We need to modify the node to decrease the size of the key. TrieNode memory modifiedLastNode = _makeExtensionNode(lastNodeKey, _getNodeValue(lastNode)); newBranch = _editBranchIndex( newBranch, branchKey, _getNodeHash(modifiedLastNode.encoded)); } else { // We're dealing with an unnecessary extension node. // We're going to delete the node entirely. // Simply insert its current value into the branch index. newBranch = _editBranchIndex(newBranch, branchKey, _getNodeValue(lastNode)); } } if (keyRemainder.length == 0) { // We've got nothing left in the key remainder. // Simply insert the value into the branch value slot. newBranch = _editBranchValue(newBranch, _value); // Push the branch into the list of new nodes. newNodes[totalNewNodes] = newBranch; totalNewNodes += 1; } else { // We've got some key remainder to work with. // We'll be inserting a leaf node into the trie. // First, move on to the next nibble. keyRemainder = Lib_BytesUtils.slice(keyRemainder, 1); // Push the branch into the list of new nodes. newNodes[totalNewNodes] = newBranch; totalNewNodes += 1; // Push a new leaf node for our k/v pair. newNodes[totalNewNodes] = _makeLeafNode(keyRemainder, _value); totalNewNodes += 1; } } // Finally, join the old path with our newly created nodes. // Since we're overwriting the last node in the path, we use `_pathLength - 1`. return _joinNodeArrays(_path, _pathLength - 1, newNodes, totalNewNodes); } /** * @notice Computes the trie root from a given path. * @param _nodes Path to some k/v pair. * @param _key Key for the k/v pair. * @return _updatedRoot Root hash for the updated trie. */ function _getUpdatedTrieRoot( TrieNode[] memory _nodes, bytes memory _key ) private pure returns ( bytes32 _updatedRoot ) { bytes memory key = Lib_BytesUtils.toNibbles(_key); // Some variables to keep track of during iteration. TrieNode memory currentNode; NodeType currentNodeType; bytes memory previousNodeHash; // Run through the path backwards to rebuild our root hash. for (uint256 i = _nodes.length; i > 0; i--) { // Pick out the current node. currentNode = _nodes[i - 1]; currentNodeType = _getNodeType(currentNode); if (currentNodeType == NodeType.LeafNode) { // Leaf nodes are already correctly encoded. // Shift the key over to account for the nodes key. bytes memory nodeKey = _getNodeKey(currentNode); key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length); } else if (currentNodeType == NodeType.ExtensionNode) { // Shift the key over to account for the nodes key. bytes memory nodeKey = _getNodeKey(currentNode); key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length); // If this node is the last element in the path, it'll be correctly encoded // and we can skip this part. if (previousNodeHash.length > 0) { // Re-encode the node based on the previous node. currentNode = _editExtensionNodeValue(currentNode, previousNodeHash); } } else if (currentNodeType == NodeType.BranchNode) { // If this node is the last element in the path, it'll be correctly encoded // and we can skip this part. if (previousNodeHash.length > 0) { // Re-encode the node based on the previous node. uint8 branchKey = uint8(key[key.length - 1]); key = Lib_BytesUtils.slice(key, 0, key.length - 1); currentNode = _editBranchIndex(currentNode, branchKey, previousNodeHash); } } // Compute the node hash for the next iteration. previousNodeHash = _getNodeHash(currentNode.encoded); } // Current node should be the root at this point. // Simply return the hash of its encoding. return keccak256(currentNode.encoded); } /** * @notice Parses an RLP-encoded proof into something more useful. * @param _proof RLP-encoded proof to parse. * @return _parsed Proof parsed into easily accessible structs. */ function _parseProof( bytes memory _proof ) private pure returns ( TrieNode[] memory _parsed ) { Lib_RLPReader.RLPItem[] memory nodes = Lib_RLPReader.readList(_proof); TrieNode[] memory proof = new TrieNode[](nodes.length); for (uint256 i = 0; i < nodes.length; i++) { bytes memory encoded = Lib_RLPReader.readBytes(nodes[i]); proof[i] = TrieNode({ encoded: encoded, decoded: Lib_RLPReader.readList(encoded) }); } return proof; } /** * @notice Picks out the ID for a node. Node ID is referred to as the * "hash" within the specification, but nodes < 32 bytes are not actually * hashed. * @param _node Node to pull an ID for. * @return _nodeID ID for the node, depending on the size of its contents. */ function _getNodeID( Lib_RLPReader.RLPItem memory _node ) private pure returns ( bytes32 _nodeID ) { bytes memory nodeID; if (_node.length < 32) { // Nodes smaller than 32 bytes are RLP encoded. nodeID = Lib_RLPReader.readRawBytes(_node); } else { // Nodes 32 bytes or larger are hashed. nodeID = Lib_RLPReader.readBytes(_node); } return Lib_BytesUtils.toBytes32(nodeID); } /** * @notice Gets the path for a leaf or extension node. * @param _node Node to get a path for. * @return _path Node path, converted to an array of nibbles. */ function _getNodePath( TrieNode memory _node ) private pure returns ( bytes memory _path ) { return Lib_BytesUtils.toNibbles(Lib_RLPReader.readBytes(_node.decoded[0])); } /** * @notice Gets the key for a leaf or extension node. Keys are essentially * just paths without any prefix. * @param _node Node to get a key for. * @return _key Node key, converted to an array of nibbles. */ function _getNodeKey( TrieNode memory _node ) private pure returns ( bytes memory _key ) { return _removeHexPrefix(_getNodePath(_node)); } /** * @notice Gets the path for a node. * @param _node Node to get a value for. * @return _value Node value, as hex bytes. */ function _getNodeValue( TrieNode memory _node ) private pure returns ( bytes memory _value ) { return Lib_RLPReader.readBytes(_node.decoded[_node.decoded.length - 1]); } /** * @notice Computes the node hash for an encoded node. Nodes < 32 bytes * are not hashed, all others are keccak256 hashed. * @param _encoded Encoded node to hash. * @return _hash Hash of the encoded node. Simply the input if < 32 bytes. */ function _getNodeHash( bytes memory _encoded ) private pure returns ( bytes memory _hash ) { if (_encoded.length < 32) { return _encoded; } else { return abi.encodePacked(keccak256(_encoded)); } } /** * @notice Determines the type for a given node. * @param _node Node to determine a type for. * @return _type Type of the node; BranchNode/ExtensionNode/LeafNode. */ function _getNodeType( TrieNode memory _node ) private pure returns ( NodeType _type ) { if (_node.decoded.length == BRANCH_NODE_LENGTH) { return NodeType.BranchNode; } else if (_node.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) { bytes memory path = _getNodePath(_node); uint8 prefix = uint8(path[0]); if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) { return NodeType.LeafNode; } else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) { return NodeType.ExtensionNode; } } revert("Invalid node type"); } /** * @notice Utility; determines the number of nibbles shared between two * nibble arrays. * @param _a First nibble array. * @param _b Second nibble array. * @return _shared Number of shared nibbles. */ function _getSharedNibbleLength( bytes memory _a, bytes memory _b ) private pure returns ( uint256 _shared ) { uint256 i = 0; while (_a.length > i && _b.length > i && _a[i] == _b[i]) { i++; } return i; } /** * @notice Utility; converts an RLP-encoded node into our nice struct. * @param _raw RLP-encoded node to convert. * @return _node Node as a TrieNode struct. */ function _makeNode( bytes[] memory _raw ) private pure returns ( TrieNode memory _node ) { bytes memory encoded = Lib_RLPWriter.writeList(_raw); return TrieNode({ encoded: encoded, decoded: Lib_RLPReader.readList(encoded) }); } /** * @notice Utility; converts an RLP-decoded node into our nice struct. * @param _items RLP-decoded node to convert. * @return _node Node as a TrieNode struct. */ function _makeNode( Lib_RLPReader.RLPItem[] memory _items ) private pure returns ( TrieNode memory _node ) { bytes[] memory raw = new bytes[](_items.length); for (uint256 i = 0; i < _items.length; i++) { raw[i] = Lib_RLPReader.readRawBytes(_items[i]); } return _makeNode(raw); } /** * @notice Creates a new extension node. * @param _key Key for the extension node, unprefixed. * @param _value Value for the extension node. * @return _node New extension node with the given k/v pair. */ function _makeExtensionNode( bytes memory _key, bytes memory _value ) private pure returns ( TrieNode memory _node ) { bytes[] memory raw = new bytes[](2); bytes memory key = _addHexPrefix(_key, false); raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key)); raw[1] = Lib_RLPWriter.writeBytes(_value); return _makeNode(raw); } /** * Creates a new extension node with the same key but a different value. * @param _node Extension node to copy and modify. * @param _value New value for the extension node. * @return New node with the same key and different value. */ function _editExtensionNodeValue( TrieNode memory _node, bytes memory _value ) private pure returns ( TrieNode memory ) { bytes[] memory raw = new bytes[](2); bytes memory key = _addHexPrefix(_getNodeKey(_node), false); raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key)); if (_value.length < 32) { raw[1] = _value; } else { raw[1] = Lib_RLPWriter.writeBytes(_value); } return _makeNode(raw); } /** * @notice Creates a new leaf node. * @dev This function is essentially identical to `_makeExtensionNode`. * Although we could route both to a single method with a flag, it's * more gas efficient to keep them separate and duplicate the logic. * @param _key Key for the leaf node, unprefixed. * @param _value Value for the leaf node. * @return _node New leaf node with the given k/v pair. */ function _makeLeafNode( bytes memory _key, bytes memory _value ) private pure returns ( TrieNode memory _node ) { bytes[] memory raw = new bytes[](2); bytes memory key = _addHexPrefix(_key, true); raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key)); raw[1] = Lib_RLPWriter.writeBytes(_value); return _makeNode(raw); } /** * @notice Creates an empty branch node. * @return _node Empty branch node as a TrieNode struct. */ function _makeEmptyBranchNode() private pure returns ( TrieNode memory _node ) { bytes[] memory raw = new bytes[](BRANCH_NODE_LENGTH); for (uint256 i = 0; i < raw.length; i++) { raw[i] = RLP_NULL_BYTES; } return _makeNode(raw); } /** * @notice Modifies the value slot for a given branch. * @param _branch Branch node to modify. * @param _value Value to insert into the branch. * @return _updatedNode Modified branch node. */ function _editBranchValue( TrieNode memory _branch, bytes memory _value ) private pure returns ( TrieNode memory _updatedNode ) { bytes memory encoded = Lib_RLPWriter.writeBytes(_value); _branch.decoded[_branch.decoded.length - 1] = Lib_RLPReader.toRLPItem(encoded); return _makeNode(_branch.decoded); } /** * @notice Modifies a slot at an index for a given branch. * @param _branch Branch node to modify. * @param _index Slot index to modify. * @param _value Value to insert into the slot. * @return _updatedNode Modified branch node. */ function _editBranchIndex( TrieNode memory _branch, uint8 _index, bytes memory _value ) private pure returns ( TrieNode memory _updatedNode ) { bytes memory encoded = _value.length < 32 ? _value : Lib_RLPWriter.writeBytes(_value); _branch.decoded[_index] = Lib_RLPReader.toRLPItem(encoded); return _makeNode(_branch.decoded); } /** * @notice Utility; adds a prefix to a key. * @param _key Key to prefix. * @param _isLeaf Whether or not the key belongs to a leaf. * @return _prefixedKey Prefixed key. */ function _addHexPrefix( bytes memory _key, bool _isLeaf ) private pure returns ( bytes memory _prefixedKey ) { uint8 prefix = _isLeaf ? uint8(0x02) : uint8(0x00); uint8 offset = uint8(_key.length % 2); bytes memory prefixed = new bytes(2 - offset); prefixed[0] = bytes1(prefix + offset); return abi.encodePacked(prefixed, _key); } /** * @notice Utility; removes a prefix from a path. * @param _path Path to remove the prefix from. * @return _unprefixedKey Unprefixed key. */ function _removeHexPrefix( bytes memory _path ) private pure returns ( bytes memory _unprefixedKey ) { if (uint8(_path[0]) % 2 == 0) { return Lib_BytesUtils.slice(_path, 2); } else { return Lib_BytesUtils.slice(_path, 1); } } /** * @notice Utility; combines two node arrays. Array lengths are required * because the actual lengths may be longer than the filled lengths. * Array resizing is extremely costly and should be avoided. * @param _a First array to join. * @param _aLength Length of the first array. * @param _b Second array to join. * @param _bLength Length of the second array. * @return _joined Combined node array. */ function _joinNodeArrays( TrieNode[] memory _a, uint256 _aLength, TrieNode[] memory _b, uint256 _bLength ) private pure returns ( TrieNode[] memory _joined ) { TrieNode[] memory ret = new TrieNode[](_aLength + _bLength); // Copy elements from the first array. for (uint256 i = 0; i < _aLength; i++) { ret[i] = _a[i]; } // Copy elements from the second array. for (uint256 i = 0; i < _bLength; i++) { ret[i + _aLength] = _b[i]; } return ret; } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /* Interface Imports */ import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol"; import { iOVM_StateTransitionerFactory } from "../../iOVM/verification/iOVM_StateTransitionerFactory.sol"; import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol"; /* Contract Imports */ import { OVM_StateTransitioner } from "./OVM_StateTransitioner.sol"; /** * @title OVM_StateTransitionerFactory * @dev The State Transitioner Factory is used by the Fraud Verifier to create a new State * Transitioner during the initialization of a fraud proof. * * Compiler used: solc * Runtime target: EVM */ contract OVM_StateTransitionerFactory is iOVM_StateTransitionerFactory, Lib_AddressResolver { /*************** * Constructor * ***************/ constructor( address _libAddressManager ) Lib_AddressResolver(_libAddressManager) {} /******************** * Public Functions * ********************/ /** * Creates a new OVM_StateTransitioner * @param _libAddressManager Address of the Address Manager. * @param _stateTransitionIndex Index of the state transition being verified. * @param _preStateRoot State root before the transition was executed. * @param _transactionHash Hash of the executed transaction. * @return New OVM_StateTransitioner instance. */ function create( address _libAddressManager, uint256 _stateTransitionIndex, bytes32 _preStateRoot, bytes32 _transactionHash ) override public returns ( iOVM_StateTransitioner ) { require( msg.sender == resolve("OVM_FraudVerifier"), "Create can only be done by the OVM_FraudVerifier." ); return new OVM_StateTransitioner( _libAddressManager, _stateTransitionIndex, _preStateRoot, _transactionHash ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Contract Imports */ import { iOVM_StateTransitioner } from "./iOVM_StateTransitioner.sol"; /** * @title iOVM_StateTransitionerFactory */ interface iOVM_StateTransitionerFactory { /*************************************** * Public Functions: Contract Creation * ***************************************/ function create( address _proxyManager, uint256 _stateTransitionIndex, bytes32 _preStateRoot, bytes32 _transactionHash ) external returns ( iOVM_StateTransitioner _ovmStateTransitioner ); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /* Interface Imports */ import { iOVM_StateTransitioner } from "./iOVM_StateTransitioner.sol"; /** * @title iOVM_FraudVerifier */ interface iOVM_FraudVerifier { /********** * Events * **********/ event FraudProofInitialized( bytes32 _preStateRoot, uint256 _preStateRootIndex, bytes32 _transactionHash, address _who ); event FraudProofFinalized( bytes32 _preStateRoot, uint256 _preStateRootIndex, bytes32 _transactionHash, address _who ); /*************************************** * Public Functions: Transition Status * ***************************************/ function getStateTransitioner(bytes32 _preStateRoot, bytes32 _txHash) external view returns (iOVM_StateTransitioner _transitioner); /**************************************** * Public Functions: Fraud Verification * ****************************************/ function initializeFraudVerification( bytes32 _preStateRoot, Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof, Lib_OVMCodec.Transaction calldata _transaction, Lib_OVMCodec.TransactionChainElement calldata _txChainElement, Lib_OVMCodec.ChainBatchHeader calldata _transactionBatchHeader, Lib_OVMCodec.ChainInclusionProof calldata _transactionProof ) external; function finalizeFraudVerification( bytes32 _preStateRoot, Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof, bytes32 _txHash, bytes32 _postStateRoot, Lib_OVMCodec.ChainBatchHeader calldata _postStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof calldata _postStateRootProof ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /* Interface Imports */ import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol"; import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol"; import { iOVM_StateTransitionerFactory } from "../../iOVM/verification/iOVM_StateTransitionerFactory.sol"; import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol"; import { iOVM_StateCommitmentChain } from "../../iOVM/chain/iOVM_StateCommitmentChain.sol"; import { iOVM_CanonicalTransactionChain } from "../../iOVM/chain/iOVM_CanonicalTransactionChain.sol"; /* Contract Imports */ import { Abs_FraudContributor } from "./Abs_FraudContributor.sol"; /** * @title OVM_FraudVerifier * @dev The Fraud Verifier contract coordinates the entire fraud proof verification process. * If the fraud proof was successful it prunes any state batches from State Commitment Chain * which were published after the fraudulent state root. * * Compiler used: solc * Runtime target: EVM */ contract OVM_FraudVerifier is Lib_AddressResolver, Abs_FraudContributor, iOVM_FraudVerifier { /******************************************* * Contract Variables: Internal Accounting * *******************************************/ mapping (bytes32 => iOVM_StateTransitioner) internal transitioners; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager ) Lib_AddressResolver(_libAddressManager) {} /*************************************** * Public Functions: Transition Status * ***************************************/ /** * Retrieves the state transitioner for a given root. * @param _preStateRoot State root to query a transitioner for. * @return _transitioner Corresponding state transitioner contract. */ function getStateTransitioner( bytes32 _preStateRoot, bytes32 _txHash ) override public view returns ( iOVM_StateTransitioner _transitioner ) { return transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))]; } /**************************************** * Public Functions: Fraud Verification * ****************************************/ /** * Begins the fraud verification process. * @param _preStateRoot State root before the fraudulent transaction. * @param _preStateRootBatchHeader Batch header for the provided pre-state root. * @param _preStateRootProof Inclusion proof for the provided pre-state root. * @param _transaction OVM transaction claimed to be fraudulent. * @param _txChainElement OVM transaction chain element. * @param _transactionBatchHeader Batch header for the provided transaction. * @param _transactionProof Inclusion proof for the provided transaction. */ function initializeFraudVerification( bytes32 _preStateRoot, Lib_OVMCodec.ChainBatchHeader memory _preStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof memory _preStateRootProof, Lib_OVMCodec.Transaction memory _transaction, Lib_OVMCodec.TransactionChainElement memory _txChainElement, Lib_OVMCodec.ChainBatchHeader memory _transactionBatchHeader, Lib_OVMCodec.ChainInclusionProof memory _transactionProof ) override public contributesToFraudProof(_preStateRoot, Lib_OVMCodec.hashTransaction(_transaction)) { bytes32 _txHash = Lib_OVMCodec.hashTransaction(_transaction); if (_hasStateTransitioner(_preStateRoot, _txHash)) { return; } iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain(resolve("OVM_StateCommitmentChain")); iOVM_CanonicalTransactionChain ovmCanonicalTransactionChain = iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain")); require( ovmStateCommitmentChain.verifyStateCommitment( _preStateRoot, _preStateRootBatchHeader, _preStateRootProof ), "Invalid pre-state root inclusion proof." ); require( ovmCanonicalTransactionChain.verifyTransaction( _transaction, _txChainElement, _transactionBatchHeader, _transactionProof ), "Invalid transaction inclusion proof." ); require ( // solhint-disable-next-line max-line-length _preStateRootBatchHeader.prevTotalElements + _preStateRootProof.index + 1 == _transactionBatchHeader.prevTotalElements + _transactionProof.index, "Pre-state root global index must equal to the transaction root global index." ); _deployTransitioner(_preStateRoot, _txHash, _preStateRootProof.index); emit FraudProofInitialized( _preStateRoot, _preStateRootProof.index, _txHash, msg.sender ); } /** * Finalizes the fraud verification process. * @param _preStateRoot State root before the fraudulent transaction. * @param _preStateRootBatchHeader Batch header for the provided pre-state root. * @param _preStateRootProof Inclusion proof for the provided pre-state root. * @param _txHash The transaction for the state root * @param _postStateRoot State root after the fraudulent transaction. * @param _postStateRootBatchHeader Batch header for the provided post-state root. * @param _postStateRootProof Inclusion proof for the provided post-state root. */ function finalizeFraudVerification( bytes32 _preStateRoot, Lib_OVMCodec.ChainBatchHeader memory _preStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof memory _preStateRootProof, bytes32 _txHash, bytes32 _postStateRoot, Lib_OVMCodec.ChainBatchHeader memory _postStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof memory _postStateRootProof ) override public contributesToFraudProof(_preStateRoot, _txHash) { iOVM_StateTransitioner transitioner = getStateTransitioner(_preStateRoot, _txHash); iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain(resolve("OVM_StateCommitmentChain")); require( transitioner.isComplete() == true, "State transition process must be completed prior to finalization." ); require ( // solhint-disable-next-line max-line-length _postStateRootBatchHeader.prevTotalElements + _postStateRootProof.index == _preStateRootBatchHeader.prevTotalElements + _preStateRootProof.index + 1, "Post-state root global index must equal to the pre state root global index plus one." ); require( ovmStateCommitmentChain.verifyStateCommitment( _preStateRoot, _preStateRootBatchHeader, _preStateRootProof ), "Invalid pre-state root inclusion proof." ); require( ovmStateCommitmentChain.verifyStateCommitment( _postStateRoot, _postStateRootBatchHeader, _postStateRootProof ), "Invalid post-state root inclusion proof." ); // If the post state root did not match, then there was fraud and we should delete the batch require( _postStateRoot != transitioner.getPostStateRoot(), "State transition has not been proven fraudulent." ); _cancelStateTransition(_postStateRootBatchHeader, _preStateRoot); // TEMPORARY: Remove the transitioner; for minnet. transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))] = iOVM_StateTransitioner(0x0000000000000000000000000000000000000000); emit FraudProofFinalized( _preStateRoot, _preStateRootProof.index, _txHash, msg.sender ); } /************************************ * Internal Functions: Verification * ************************************/ /** * Checks whether a transitioner already exists for a given pre-state root. * @param _preStateRoot Pre-state root to check. * @return _exists Whether or not we already have a transitioner for the root. */ function _hasStateTransitioner( bytes32 _preStateRoot, bytes32 _txHash ) internal view returns ( bool _exists ) { return address(getStateTransitioner(_preStateRoot, _txHash)) != address(0); } /** * Deploys a new state transitioner. * @param _preStateRoot Pre-state root to initialize the transitioner with. * @param _txHash Hash of the transaction this transitioner will execute. * @param _stateTransitionIndex Index of the transaction in the chain. */ function _deployTransitioner( bytes32 _preStateRoot, bytes32 _txHash, uint256 _stateTransitionIndex ) internal { transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))] = iOVM_StateTransitionerFactory( resolve("OVM_StateTransitionerFactory") ).create( address(libAddressManager), _stateTransitionIndex, _preStateRoot, _txHash ); } /** * Removes a state transition from the state commitment chain. * @param _postStateRootBatchHeader Header for the post-state root. * @param _preStateRoot Pre-state root hash. */ function _cancelStateTransition( Lib_OVMCodec.ChainBatchHeader memory _postStateRootBatchHeader, bytes32 _preStateRoot ) internal { iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain(resolve("OVM_StateCommitmentChain")); iOVM_BondManager ovmBondManager = iOVM_BondManager(resolve("OVM_BondManager")); // Delete the state batch. ovmStateCommitmentChain.deleteStateBatch( _postStateRootBatchHeader ); // Get the timestamp and publisher for that block. (uint256 timestamp, address publisher) = abi.decode(_postStateRootBatchHeader.extraData, (uint256, address)); // Slash the bonds at the bond manager. ovmBondManager.finalize( _preStateRoot, publisher, timestamp ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /** * @title iOVM_StateCommitmentChain */ interface iOVM_StateCommitmentChain { /********** * Events * **********/ event StateBatchAppended( uint256 indexed _batchIndex, bytes32 _batchRoot, uint256 _batchSize, uint256 _prevTotalElements, bytes _extraData ); event StateBatchDeleted( uint256 indexed _batchIndex, bytes32 _batchRoot ); /******************** * Public Functions * ********************/ /** * Retrieves the total number of elements submitted. * @return _totalElements Total submitted elements. */ function getTotalElements() external view returns ( uint256 _totalElements ); /** * Retrieves the total number of batches submitted. * @return _totalBatches Total submitted batches. */ function getTotalBatches() external view returns ( uint256 _totalBatches ); /** * Retrieves the timestamp of the last batch submitted by the sequencer. * @return _lastSequencerTimestamp Last sequencer batch timestamp. */ function getLastSequencerTimestamp() external view returns ( uint256 _lastSequencerTimestamp ); /** * Appends a batch of state roots to the chain. * @param _batch Batch of state roots. * @param _shouldStartAtElement Index of the element at which this batch should start. */ function appendStateBatch( bytes32[] calldata _batch, uint256 _shouldStartAtElement ) external; /** * Deletes all state roots after (and including) a given batch. * @param _batchHeader Header of the batch to start deleting from. */ function deleteStateBatch( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) external; /** * Verifies a batch inclusion proof. * @param _element Hash of the element to verify a proof for. * @param _batchHeader Header of the batch in which the element was included. * @param _proof Merkle inclusion proof for the element. */ function verifyStateCommitment( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) external view returns ( bool _verified ); /** * Checks whether a given batch is still inside its fraud proof window. * @param _batchHeader Header of the batch to check. * @return _inside Whether or not the batch is inside the fraud proof window. */ function insideFraudProofWindow( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) external view returns ( bool _inside ); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /* Interface Imports */ import { iOVM_ChainStorageContainer } from "./iOVM_ChainStorageContainer.sol"; /** * @title iOVM_CanonicalTransactionChain */ interface iOVM_CanonicalTransactionChain { /********** * Events * **********/ event TransactionEnqueued( address _l1TxOrigin, address _target, uint256 _gasLimit, bytes _data, uint256 _queueIndex, uint256 _timestamp ); event QueueBatchAppended( uint256 _startingQueueIndex, uint256 _numQueueElements, uint256 _totalElements ); event SequencerBatchAppended( uint256 _startingQueueIndex, uint256 _numQueueElements, uint256 _totalElements ); event TransactionBatchAppended( uint256 indexed _batchIndex, bytes32 _batchRoot, uint256 _batchSize, uint256 _prevTotalElements, bytes _extraData ); /*********** * Structs * ***********/ struct BatchContext { uint256 numSequencedTransactions; uint256 numSubsequentQueueTransactions; uint256 timestamp; uint256 blockNumber; } /******************** * Public Functions * ********************/ /** * Accesses the batch storage container. * @return Reference to the batch storage container. */ function batches() external view returns ( iOVM_ChainStorageContainer ); /** * Accesses the queue storage container. * @return Reference to the queue storage container. */ function queue() external view returns ( iOVM_ChainStorageContainer ); /** * Retrieves the total number of elements submitted. * @return _totalElements Total submitted elements. */ function getTotalElements() external view returns ( uint256 _totalElements ); /** * Retrieves the total number of batches submitted. * @return _totalBatches Total submitted batches. */ function getTotalBatches() external view returns ( uint256 _totalBatches ); /** * Returns the index of the next element to be enqueued. * @return Index for the next queue element. */ function getNextQueueIndex() external view returns ( uint40 ); /** * 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 ) external view returns ( Lib_OVMCodec.QueueElement memory _element ); /** * Returns the timestamp of the last transaction. * @return Timestamp for the last transaction. */ function getLastTimestamp() external view returns ( uint40 ); /** * Returns the blocknumber of the last transaction. * @return Blocknumber for the last transaction. */ function getLastBlockNumber() external view returns ( uint40 ); /** * Get the number of queue elements which have not yet been included. * @return Number of pending queue elements. */ function getNumPendingQueueElements() external view returns ( uint40 ); /** * Retrieves the length of the queue, including * both pending and canonical transactions. * @return Length of the queue. */ function getQueueLength() external view returns ( uint40 ); /** * Adds a transaction to the queue. * @param _target Target contract to send the transaction to. * @param _gasLimit Gas limit for the given transaction. * @param _data Transaction data. */ function enqueue( address _target, uint256 _gasLimit, bytes memory _data ) external; /** * Appends a given number of queued transactions as a single batch. * @param _numQueuedTransactions Number of transactions to append. */ function appendQueueBatch( uint256 _numQueuedTransactions ) external; /** * 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( // uint40 _shouldStartAtElement, // uint24 _totalElementsToAppend, // BatchContext[] _contexts, // bytes[] _transactionDataFields ) external; /** * Verifies whether a transaction is included in the chain. * @param _transaction Transaction to verify. * @param _txChainElement Transaction chain element corresponding to the transaction. * @param _batchHeader Header of the batch the transaction was included in. * @param _inclusionProof Inclusion proof for the provided transaction chain element. * @return True if the transaction exists in the CTC, false if not. */ function verifyTransaction( Lib_OVMCodec.Transaction memory _transaction, Lib_OVMCodec.TransactionChainElement memory _txChainElement, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _inclusionProof ) external view returns ( bool ); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_ChainStorageContainer */ interface iOVM_ChainStorageContainer { /******************** * Public Functions * ********************/ /** * Sets the container's global metadata field. We're using `bytes27` here because we use five * bytes to maintain the length of the underlying data structure, meaning we have an extra * 27 bytes to store arbitrary data. * @param _globalMetadata New global metadata to set. */ function setGlobalMetadata( bytes27 _globalMetadata ) external; /** * Retrieves the container's global metadata field. * @return Container global metadata field. */ function getGlobalMetadata() external view returns ( bytes27 ); /** * Retrieves the number of objects stored in the container. * @return Number of objects in the container. */ function length() external view returns ( uint256 ); /** * Pushes an object into the container. * @param _object A 32 byte value to insert into the container. */ function push( bytes32 _object ) external; /** * Pushes an object into the container. Function allows setting the global metadata since * we'll need to touch the "length" storage slot anyway, which also contains the global * metadata (it's an optimization). * @param _object A 32 byte value to insert into the container. * @param _globalMetadata New global metadata for the container. */ function push( bytes32 _object, bytes27 _globalMetadata ) external; /** * Retrieves an object from the container. * @param _index Index of the particular object to access. * @return 32 byte object value. */ function get( uint256 _index ) external view returns ( bytes32 ); /** * Removes all objects after and including a given index. * @param _index Object index to delete from. */ function deleteElementsAfterInclusive( uint256 _index ) external; /** * Removes all objects after and including a given index. Also allows setting the global * metadata field. * @param _index Object index to delete from. * @param _globalMetadata New global metadata for the container. */ function deleteElementsAfterInclusive( uint256 _index, bytes27 _globalMetadata ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /* Interface Imports */ import { iOVM_BondManager, Errors, ERC20 } from "../../iOVM/verification/iOVM_BondManager.sol"; import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol"; /** * @title OVM_BondManager * @dev The Bond Manager contract handles deposits in the form of an ERC20 token from bonded * Proposers. It also handles the accounting of gas costs spent by a Verifier during the course of a * fraud proof. In the event of a successful fraud proof, the fraudulent Proposer's bond is slashed, * and the Verifier's gas costs are refunded. * * Compiler used: solc * Runtime target: EVM */ contract OVM_BondManager is iOVM_BondManager, Lib_AddressResolver { /**************************** * Constants and Parameters * ****************************/ /// The period to find the earliest fraud proof for a publisher uint256 public constant multiFraudProofPeriod = 7 days; /// The dispute period uint256 public constant disputePeriodSeconds = 7 days; /// The minimum collateral a sequencer must post uint256 public constant requiredCollateral = 1 ether; /******************************************* * Contract Variables: Contract References * *******************************************/ /// The bond token ERC20 immutable public token; /******************************************** * Contract Variables: Internal Accounting * *******************************************/ /// The bonds posted by each proposer mapping(address => Bond) public bonds; /// For each pre-state root, there's an array of witnessProviders that must be rewarded /// for posting witnesses mapping(bytes32 => Rewards) public witnessProviders; /*************** * Constructor * ***************/ /// Initializes with a ERC20 token to be used for the fidelity bonds /// and with the Address Manager constructor( ERC20 _token, address _libAddressManager ) Lib_AddressResolver(_libAddressManager) { token = _token; } /******************** * Public Functions * ********************/ /// Adds `who` to the list of witnessProviders for the provided `preStateRoot`. function recordGasSpent(bytes32 _preStateRoot, bytes32 _txHash, address who, uint256 gasSpent) override public { // The sender must be the transitioner that corresponds to the claimed pre-state root address transitioner = address(iOVM_FraudVerifier(resolve("OVM_FraudVerifier")) .getStateTransitioner(_preStateRoot, _txHash)); require(transitioner == msg.sender, Errors.ONLY_TRANSITIONER); witnessProviders[_preStateRoot].total += gasSpent; witnessProviders[_preStateRoot].gasSpent[who] += gasSpent; } /// Slashes + distributes rewards or frees up the sequencer's bond, only called by /// `FraudVerifier.finalizeFraudVerification` function finalize(bytes32 _preStateRoot, address publisher, uint256 timestamp) override public { require(msg.sender == resolve("OVM_FraudVerifier"), Errors.ONLY_FRAUD_VERIFIER); require(witnessProviders[_preStateRoot].canClaim == false, Errors.ALREADY_FINALIZED); // allow users to claim from that state root's // pool of collateral (effectively slashing the sequencer) witnessProviders[_preStateRoot].canClaim = true; Bond storage bond = bonds[publisher]; if (bond.firstDisputeAt == 0) { bond.firstDisputeAt = block.timestamp; bond.earliestDisputedStateRoot = _preStateRoot; bond.earliestTimestamp = timestamp; } else if ( // only update the disputed state root for the publisher if it's within // the dispute period _and_ if it's before the previous one block.timestamp < bond.firstDisputeAt + multiFraudProofPeriod && timestamp < bond.earliestTimestamp ) { bond.earliestDisputedStateRoot = _preStateRoot; bond.earliestTimestamp = timestamp; } // if the fraud proof's dispute period does not intersect with the // withdrawal's timestamp, then the user should not be slashed // e.g if a user at day 10 submits a withdrawal, and a fraud proof // from day 1 gets published, the user won't be slashed since day 8 (1d + 7d) // is before the user started their withdrawal. on the contrary, if the user // had started their withdrawal at, say, day 6, they would be slashed if ( bond.withdrawalTimestamp != 0 && uint256(bond.withdrawalTimestamp) > timestamp + disputePeriodSeconds && bond.state == State.WITHDRAWING ) { return; } // slash! bond.state = State.NOT_COLLATERALIZED; } /// Sequencers call this function to post collateral which will be used for /// the `appendBatch` call function deposit() override public { require( token.transferFrom(msg.sender, address(this), requiredCollateral), Errors.ERC20_ERR ); // This cannot overflow bonds[msg.sender].state = State.COLLATERALIZED; } /// Starts the withdrawal for a publisher function startWithdrawal() override public { Bond storage bond = bonds[msg.sender]; require(bond.withdrawalTimestamp == 0, Errors.WITHDRAWAL_PENDING); require(bond.state == State.COLLATERALIZED, Errors.WRONG_STATE); bond.state = State.WITHDRAWING; bond.withdrawalTimestamp = uint32(block.timestamp); } /// Finalizes a pending withdrawal from a publisher function finalizeWithdrawal() override public { Bond storage bond = bonds[msg.sender]; require( block.timestamp >= uint256(bond.withdrawalTimestamp) + disputePeriodSeconds, Errors.TOO_EARLY ); require(bond.state == State.WITHDRAWING, Errors.SLASHED); // refunds! bond.state = State.NOT_COLLATERALIZED; bond.withdrawalTimestamp = 0; require( token.transfer(msg.sender, requiredCollateral), Errors.ERC20_ERR ); } /// Claims the user's reward for the witnesses they provided for the earliest /// disputed state root of the designated publisher function claim(address who) override public { Bond storage bond = bonds[who]; require( block.timestamp >= bond.firstDisputeAt + multiFraudProofPeriod, Errors.WAIT_FOR_DISPUTES ); // reward the earliest state root for this publisher bytes32 _preStateRoot = bond.earliestDisputedStateRoot; Rewards storage rewards = witnessProviders[_preStateRoot]; // only allow claiming if fraud was proven in `finalize` require(rewards.canClaim, Errors.CANNOT_CLAIM); // proportional allocation - only reward 50% (rest gets locked in the // contract forever uint256 amount = (requiredCollateral * rewards.gasSpent[msg.sender]) / (2 * rewards.total); // reset the user's spent gas so they cannot double claim rewards.gasSpent[msg.sender] = 0; // transfer require(token.transfer(msg.sender, amount), Errors.ERC20_ERR); } /// Checks if the user is collateralized function isCollateralized(address who) override public view returns (bool) { return bonds[who].state == State.COLLATERALIZED; } /// Gets how many witnesses the user has provided for the state root function getGasSpent(bytes32 preStateRoot, address who) override public view returns (uint256) { return witnessProviders[preStateRoot].gasSpent[who]; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; import { OVM_BondManager } from "./../optimistic-ethereum/OVM/verification/OVM_BondManager.sol"; contract Mock_FraudVerifier { OVM_BondManager bondManager; mapping (bytes32 => address) transitioners; function setBondManager(OVM_BondManager _bondManager) public { bondManager = _bondManager; } function setStateTransitioner(bytes32 preStateRoot, bytes32 txHash, address addr) public { transitioners[keccak256(abi.encodePacked(preStateRoot, txHash))] = addr; } function getStateTransitioner( bytes32 _preStateRoot, bytes32 _txHash ) public view returns ( address ) { return transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))]; } function finalize(bytes32 _preStateRoot, address publisher, uint256 timestamp) public { bondManager.finalize(_preStateRoot, publisher, timestamp); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_MerkleTree } from "../../libraries/utils/Lib_MerkleTree.sol"; /* Interface Imports */ import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol"; import { iOVM_StateCommitmentChain } from "../../iOVM/chain/iOVM_StateCommitmentChain.sol"; import { iOVM_CanonicalTransactionChain } from "../../iOVM/chain/iOVM_CanonicalTransactionChain.sol"; import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol"; import { iOVM_ChainStorageContainer } from "../../iOVM/chain/iOVM_ChainStorageContainer.sol"; /* External Imports */ import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title OVM_StateCommitmentChain * @dev The State Commitment Chain (SCC) contract contains a list of proposed state roots which * Proposers assert to be a result of each transaction in the Canonical Transaction Chain (CTC). * Elements here have a 1:1 correspondence with transactions in the CTC, and should be the unique * state root calculated off-chain by applying the canonical transactions one by one. * * Compiler used: solc * Runtime target: EVM */ contract OVM_StateCommitmentChain is iOVM_StateCommitmentChain, Lib_AddressResolver { /************* * Constants * *************/ uint256 public FRAUD_PROOF_WINDOW; uint256 public SEQUENCER_PUBLISH_WINDOW; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager, uint256 _fraudProofWindow, uint256 _sequencerPublishWindow ) Lib_AddressResolver(_libAddressManager) { FRAUD_PROOF_WINDOW = _fraudProofWindow; SEQUENCER_PUBLISH_WINDOW = _sequencerPublishWindow; } /******************** * Public Functions * ********************/ /** * Accesses the batch storage container. * @return Reference to the batch storage container. */ function batches() public view returns ( iOVM_ChainStorageContainer ) { return iOVM_ChainStorageContainer( resolve("OVM_ChainStorageContainer-SCC-batches") ); } /** * @inheritdoc iOVM_StateCommitmentChain */ function getTotalElements() override public view returns ( uint256 _totalElements ) { (uint40 totalElements, ) = _getBatchExtraData(); return uint256(totalElements); } /** * @inheritdoc iOVM_StateCommitmentChain */ function getTotalBatches() override public view returns ( uint256 _totalBatches ) { return batches().length(); } /** * @inheritdoc iOVM_StateCommitmentChain */ function getLastSequencerTimestamp() override public view returns ( uint256 _lastSequencerTimestamp ) { (, uint40 lastSequencerTimestamp) = _getBatchExtraData(); return uint256(lastSequencerTimestamp); } /** * @inheritdoc iOVM_StateCommitmentChain */ function appendStateBatch( bytes32[] memory _batch, uint256 _shouldStartAtElement ) override public { // Fail fast in to make sure our batch roots aren't accidentally made fraudulent by the // publication of batches by some other user. require( _shouldStartAtElement == getTotalElements(), "Actual batch start index does not match expected start index." ); // Proposers must have previously staked at the BondManager require( iOVM_BondManager(resolve("OVM_BondManager")).isCollateralized(msg.sender), "Proposer does not have enough collateral posted" ); require( _batch.length > 0, "Cannot submit an empty state batch." ); require( getTotalElements() + _batch.length <= iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain")) .getTotalElements(), "Number of state roots cannot exceed the number of canonical transactions." ); // Pass the block's timestamp and the publisher of the data // to be used in the fraud proofs _appendBatch( _batch, abi.encode(block.timestamp, msg.sender) ); } /** * @inheritdoc iOVM_StateCommitmentChain */ function deleteStateBatch( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) override public { require( msg.sender == resolve("OVM_FraudVerifier"), "State batches can only be deleted by the OVM_FraudVerifier." ); require( _isValidBatchHeader(_batchHeader), "Invalid batch header." ); require( insideFraudProofWindow(_batchHeader), "State batches can only be deleted within the fraud proof window." ); _deleteBatch(_batchHeader); } /** * @inheritdoc iOVM_StateCommitmentChain */ function verifyStateCommitment( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) override public view returns ( bool ) { require( _isValidBatchHeader(_batchHeader), "Invalid batch header." ); require( Lib_MerkleTree.verify( _batchHeader.batchRoot, _element, _proof.index, _proof.siblings, _batchHeader.batchSize ), "Invalid inclusion proof." ); return true; } /** * @inheritdoc iOVM_StateCommitmentChain */ function insideFraudProofWindow( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) override public view returns ( bool _inside ) { (uint256 timestamp,) = abi.decode( _batchHeader.extraData, (uint256, address) ); require( timestamp != 0, "Batch header timestamp cannot be zero" ); return SafeMath.add(timestamp, FRAUD_PROOF_WINDOW) > block.timestamp; } /********************** * Internal Functions * **********************/ /** * Parses the batch context from the extra data. * @return Total number of elements submitted. * @return Timestamp of the last batch submitted by the sequencer. */ function _getBatchExtraData() internal view returns ( uint40, uint40 ) { bytes27 extraData = batches().getGlobalMetadata(); // solhint-disable max-line-length uint40 totalElements; uint40 lastSequencerTimestamp; assembly { extraData := shr(40, extraData) totalElements := and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF) lastSequencerTimestamp := shr(40, and(extraData, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000)) } // solhint-enable max-line-length return ( totalElements, lastSequencerTimestamp ); } /** * Encodes the batch context for the extra data. * @param _totalElements Total number of elements submitted. * @param _lastSequencerTimestamp Timestamp of the last batch submitted by the sequencer. * @return Encoded batch context. */ function _makeBatchExtraData( uint40 _totalElements, uint40 _lastSequencerTimestamp ) internal pure returns ( bytes27 ) { bytes27 extraData; assembly { extraData := _totalElements extraData := or(extraData, shl(40, _lastSequencerTimestamp)) extraData := shl(40, extraData) } return extraData; } /** * Appends a batch to the chain. * @param _batch Elements within the batch. * @param _extraData Any extra data to append to the batch. */ function _appendBatch( bytes32[] memory _batch, bytes memory _extraData ) internal { address sequencer = resolve("OVM_Proposer"); (uint40 totalElements, uint40 lastSequencerTimestamp) = _getBatchExtraData(); if (msg.sender == sequencer) { lastSequencerTimestamp = uint40(block.timestamp); } else { // We keep track of the last batch submitted by the sequencer so there's a window in // which only the sequencer can publish state roots. A window like this just reduces // the chance of "system breaking" state roots being published while we're still in // testing mode. This window should be removed or significantly reduced in the future. require( lastSequencerTimestamp + SEQUENCER_PUBLISH_WINDOW < block.timestamp, "Cannot publish state roots within the sequencer publication window." ); } // For efficiency reasons getMerkleRoot modifies the `_batch` argument in place // while calculating the root hash therefore any arguments passed to it must not // be used again afterwards Lib_OVMCodec.ChainBatchHeader memory batchHeader = Lib_OVMCodec.ChainBatchHeader({ batchIndex: getTotalBatches(), batchRoot: Lib_MerkleTree.getMerkleRoot(_batch), batchSize: _batch.length, prevTotalElements: totalElements, extraData: _extraData }); emit StateBatchAppended( batchHeader.batchIndex, batchHeader.batchRoot, batchHeader.batchSize, batchHeader.prevTotalElements, batchHeader.extraData ); batches().push( Lib_OVMCodec.hashBatchHeader(batchHeader), _makeBatchExtraData( uint40(batchHeader.prevTotalElements + batchHeader.batchSize), lastSequencerTimestamp ) ); } /** * Removes a batch and all subsequent batches from the chain. * @param _batchHeader Header of the batch to remove. */ function _deleteBatch( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal { require( _batchHeader.batchIndex < batches().length(), "Invalid batch index." ); require( _isValidBatchHeader(_batchHeader), "Invalid batch header." ); batches().deleteElementsAfterInclusive( _batchHeader.batchIndex, _makeBatchExtraData( uint40(_batchHeader.prevTotalElements), 0 ) ); emit StateBatchDeleted( _batchHeader.batchIndex, _batchHeader.batchRoot ); } /** * Checks that a batch header matches the stored hash for the given index. * @param _batchHeader Batch header to validate. * @return Whether or not the header matches the stored one. */ function _isValidBatchHeader( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal view returns ( bool ) { return Lib_OVMCodec.hashBatchHeader(_batchHeader) == batches().get(_batchHeader.batchIndex); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_MerkleTree * @author River Keefer */ library Lib_MerkleTree { /********************** * Internal Functions * **********************/ /** * Calculates a merkle root for a list of 32-byte leaf hashes. WARNING: If the number * of leaves passed in is not a power of two, it pads out the tree with zero hashes. * If you do not know the original length of elements for the tree you are verifying, then * this may allow empty leaves past _elements.length to pass a verification check down the line. * Note that the _elements argument is modified, therefore it must not be used again afterwards * @param _elements Array of hashes from which to generate a merkle root. * @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above). */ function getMerkleRoot( bytes32[] memory _elements ) internal pure returns ( bytes32 ) { require( _elements.length > 0, "Lib_MerkleTree: Must provide at least one leaf hash." ); if (_elements.length == 1) { return _elements[0]; } uint256[16] memory defaults = [ 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563, 0x633dc4d7da7256660a892f8f1604a44b5432649cc8ec5cb3ced4c4e6ac94dd1d, 0x890740a8eb06ce9be422cb8da5cdafc2b58c0a5e24036c578de2a433c828ff7d, 0x3b8ec09e026fdc305365dfc94e189a81b38c7597b3d941c279f042e8206e0bd8, 0xecd50eee38e386bd62be9bedb990706951b65fe053bd9d8a521af753d139e2da, 0xdefff6d330bb5403f63b14f33b578274160de3a50df4efecf0e0db73bcdd3da5, 0x617bdd11f7c0a11f49db22f629387a12da7596f9d1704d7465177c63d88ec7d7, 0x292c23a9aa1d8bea7e2435e555a4a60e379a5a35f3f452bae60121073fb6eead, 0xe1cea92ed99acdcb045a6726b2f87107e8a61620a232cf4d7d5b5766b3952e10, 0x7ad66c0a68c72cb89e4fb4303841966e4062a76ab97451e3b9fb526a5ceb7f82, 0xe026cc5a4aed3c22a58cbd3d2ac754c9352c5436f638042dca99034e83636516, 0x3d04cffd8b46a874edf5cfae63077de85f849a660426697b06a829c70dd1409c, 0xad676aa337a485e4728a0b240d92b3ef7b3c372d06d189322bfd5f61f1e7203e, 0xa2fca4a49658f9fab7aa63289c91b7c7b6c832a6d0e69334ff5b0a3483d09dab, 0x4ebfd9cd7bca2505f7bef59cc1c12ecc708fff26ae4af19abe852afe9e20c862, 0x2def10d13dd169f550f578bda343d9717a138562e0093b380a1120789d53cf10 ]; // Reserve memory space for our hashes. bytes memory buf = new bytes(64); // We'll need to keep track of left and right siblings. bytes32 leftSibling; bytes32 rightSibling; // Number of non-empty nodes at the current depth. uint256 rowSize = _elements.length; // Current depth, counting from 0 at the leaves uint256 depth = 0; // Common sub-expressions uint256 halfRowSize; // rowSize / 2 bool rowSizeIsOdd; // rowSize % 2 == 1 while (rowSize > 1) { halfRowSize = rowSize / 2; rowSizeIsOdd = rowSize % 2 == 1; for (uint256 i = 0; i < halfRowSize; i++) { leftSibling = _elements[(2 * i) ]; rightSibling = _elements[(2 * i) + 1]; assembly { mstore(add(buf, 32), leftSibling ) mstore(add(buf, 64), rightSibling) } _elements[i] = keccak256(buf); } if (rowSizeIsOdd) { leftSibling = _elements[rowSize - 1]; rightSibling = bytes32(defaults[depth]); assembly { mstore(add(buf, 32), leftSibling) mstore(add(buf, 64), rightSibling) } _elements[halfRowSize] = keccak256(buf); } rowSize = halfRowSize + (rowSizeIsOdd ? 1 : 0); depth++; } return _elements[0]; } /** * Verifies a merkle branch for the given leaf hash. Assumes the original length * of leaves generated is a known, correct input, and does not return true for indices * extending past that index (even if _siblings would be otherwise valid.) * @param _root The Merkle root to verify against. * @param _leaf The leaf hash to verify inclusion of. * @param _index The index in the tree of this leaf. * @param _siblings Array of sibline nodes in the inclusion proof, starting from depth 0 * (bottom of the tree). * @param _totalLeaves The total number of leaves originally passed into. * @return Whether or not the merkle branch and leaf passes verification. */ function verify( bytes32 _root, bytes32 _leaf, uint256 _index, bytes32[] memory _siblings, uint256 _totalLeaves ) internal pure returns ( bool ) { require( _totalLeaves > 0, "Lib_MerkleTree: Total leaves must be greater than zero." ); require( _index < _totalLeaves, "Lib_MerkleTree: Index out of bounds." ); require( _siblings.length == _ceilLog2(_totalLeaves), "Lib_MerkleTree: Total siblings does not correctly correspond to total leaves." ); bytes32 computedRoot = _leaf; for (uint256 i = 0; i < _siblings.length; i++) { if ((_index & 1) == 1) { computedRoot = keccak256( abi.encodePacked( _siblings[i], computedRoot ) ); } else { computedRoot = keccak256( abi.encodePacked( computedRoot, _siblings[i] ) ); } _index >>= 1; } return _root == computedRoot; } /********************* * Private Functions * *********************/ /** * Calculates the integer ceiling of the log base 2 of an input. * @param _in Unsigned input to calculate the log. * @return ceil(log_base_2(_in)) */ function _ceilLog2( uint256 _in ) private pure returns ( uint256 ) { require( _in > 0, "Lib_MerkleTree: Cannot compute ceil(log_2) of 0." ); if (_in == 1) { return 0; } // Find the highest set bit (will be floor(log_2)). // Borrowed with <3 from https://github.com/ethereum/solidity-examples uint256 val = _in; uint256 highest = 0; for (uint256 i = 128; i >= 1; i >>= 1) { if (val & (uint(1) << i) - 1 << i != 0) { highest += i; val >>= i; } } // Increment by one if this is not a perfect logarithm. if ((uint(1) << highest) != _in) { highest += 1; } return highest; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_Buffer } from "../../libraries/utils/Lib_Buffer.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /* Interface Imports */ import { iOVM_ChainStorageContainer } from "../../iOVM/chain/iOVM_ChainStorageContainer.sol"; /** * @title OVM_ChainStorageContainer * @dev The Chain Storage Container provides its owner contract with read, write and delete * functionality. This provides gas efficiency gains by enabling it to overwrite storage slots which * can no longer be used in a fraud proof due to the fraud window having passed, and the associated * chain state or transactions being finalized. * Three distinct Chain Storage Containers will be deployed on Layer 1: * 1. Stores transaction batches for the Canonical Transaction Chain * 2. Stores queued transactions for the Canonical Transaction Chain * 3. Stores chain state batches for the State Commitment Chain * * Compiler used: solc * Runtime target: EVM */ contract OVM_ChainStorageContainer is iOVM_ChainStorageContainer, Lib_AddressResolver { /************* * Libraries * *************/ using Lib_Buffer for Lib_Buffer.Buffer; /************* * Variables * *************/ string public owner; Lib_Buffer.Buffer internal buffer; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. * @param _owner Name of the contract that owns this container (will be resolved later). */ constructor( address _libAddressManager, string memory _owner ) Lib_AddressResolver(_libAddressManager) { owner = _owner; } /********************** * Function Modifiers * **********************/ modifier onlyOwner() { require( msg.sender == resolve(owner), "OVM_ChainStorageContainer: Function can only be called by the owner." ); _; } /******************** * Public Functions * ********************/ /** * @inheritdoc iOVM_ChainStorageContainer */ function setGlobalMetadata( bytes27 _globalMetadata ) override public onlyOwner { return buffer.setExtraData(_globalMetadata); } /** * @inheritdoc iOVM_ChainStorageContainer */ function getGlobalMetadata() override public view returns ( bytes27 ) { return buffer.getExtraData(); } /** * @inheritdoc iOVM_ChainStorageContainer */ function length() override public view returns ( uint256 ) { return uint256(buffer.getLength()); } /** * @inheritdoc iOVM_ChainStorageContainer */ function push( bytes32 _object ) override public onlyOwner { buffer.push(_object); } /** * @inheritdoc iOVM_ChainStorageContainer */ function push( bytes32 _object, bytes27 _globalMetadata ) override public onlyOwner { buffer.push(_object, _globalMetadata); } /** * @inheritdoc iOVM_ChainStorageContainer */ function get( uint256 _index ) override public view returns ( bytes32 ) { return buffer.get(uint40(_index)); } /** * @inheritdoc iOVM_ChainStorageContainer */ function deleteElementsAfterInclusive( uint256 _index ) override public onlyOwner { buffer.deleteElementsAfterInclusive( uint40(_index) ); } /** * @inheritdoc iOVM_ChainStorageContainer */ function deleteElementsAfterInclusive( uint256 _index, bytes27 _globalMetadata ) override public onlyOwner { buffer.deleteElementsAfterInclusive( uint40(_index), _globalMetadata ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_Buffer * @dev This library implements a bytes32 storage array with some additional gas-optimized * functionality. In particular, it encodes its length as a uint40, and tightly packs this with an * overwritable "extra data" field so we can store more information with a single SSTORE. */ library Lib_Buffer { /************* * Libraries * *************/ using Lib_Buffer for Buffer; /*********** * Structs * ***********/ struct Buffer { bytes32 context; mapping (uint256 => bytes32) buf; } struct BufferContext { // Stores the length of the array. Uint40 is way more elements than we'll ever reasonably // need in an array and we get an extra 27 bytes of extra data to play with. uint40 length; // Arbitrary extra data that can be modified whenever the length is updated. Useful for // squeezing out some gas optimizations. bytes27 extraData; } /********************** * Internal Functions * **********************/ /** * Pushes a single element to the buffer. * @param _self Buffer to access. * @param _value Value to push to the buffer. * @param _extraData Global extra data. */ function push( Buffer storage _self, bytes32 _value, bytes27 _extraData ) internal { BufferContext memory ctx = _self.getContext(); _self.buf[ctx.length] = _value; // Bump the global index and insert our extra data, then save the context. ctx.length++; ctx.extraData = _extraData; _self.setContext(ctx); } /** * Pushes a single element to the buffer. * @param _self Buffer to access. * @param _value Value to push to the buffer. */ function push( Buffer storage _self, bytes32 _value ) internal { BufferContext memory ctx = _self.getContext(); _self.push( _value, ctx.extraData ); } /** * Retrieves an element from the buffer. * @param _self Buffer to access. * @param _index Element index to retrieve. * @return Value of the element at the given index. */ function get( Buffer storage _self, uint256 _index ) internal view returns ( bytes32 ) { BufferContext memory ctx = _self.getContext(); require( _index < ctx.length, "Index out of bounds." ); return _self.buf[_index]; } /** * Deletes all elements after (and including) a given index. * @param _self Buffer to access. * @param _index Index of the element to delete from (inclusive). * @param _extraData Optional global extra data. */ function deleteElementsAfterInclusive( Buffer storage _self, uint40 _index, bytes27 _extraData ) internal { BufferContext memory ctx = _self.getContext(); require( _index < ctx.length, "Index out of bounds." ); // Set our length and extra data, save the context. ctx.length = _index; ctx.extraData = _extraData; _self.setContext(ctx); } /** * Deletes all elements after (and including) a given index. * @param _self Buffer to access. * @param _index Index of the element to delete from (inclusive). */ function deleteElementsAfterInclusive( Buffer storage _self, uint40 _index ) internal { BufferContext memory ctx = _self.getContext(); _self.deleteElementsAfterInclusive( _index, ctx.extraData ); } /** * Retrieves the current global index. * @param _self Buffer to access. * @return Current global index. */ function getLength( Buffer storage _self ) internal view returns ( uint40 ) { BufferContext memory ctx = _self.getContext(); return ctx.length; } /** * Changes current global extra data. * @param _self Buffer to access. * @param _extraData New global extra data. */ function setExtraData( Buffer storage _self, bytes27 _extraData ) internal { BufferContext memory ctx = _self.getContext(); ctx.extraData = _extraData; _self.setContext(ctx); } /** * Retrieves the current global extra data. * @param _self Buffer to access. * @return Current global extra data. */ function getExtraData( Buffer storage _self ) internal view returns ( bytes27 ) { BufferContext memory ctx = _self.getContext(); return ctx.extraData; } /** * Sets the current buffer context. * @param _self Buffer to access. * @param _ctx Current buffer context. */ function setContext( Buffer storage _self, BufferContext memory _ctx ) internal { bytes32 context; uint40 length = _ctx.length; bytes27 extraData = _ctx.extraData; assembly { context := length context := or(context, extraData) } if (_self.context != context) { _self.context = context; } } /** * Retrieves the current buffer context. * @param _self Buffer to access. * @return Current buffer context. */ function getContext( Buffer storage _self ) internal view returns ( BufferContext memory ) { bytes32 context = _self.context; uint40 length; bytes27 extraData; assembly { // solhint-disable-next-line max-line-length length := and(context, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF) // solhint-disable-next-line max-line-length extraData := and(context, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000) } return BufferContext({ length: length, extraData: extraData }); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_Buffer } from "../../optimistic-ethereum/libraries/utils/Lib_Buffer.sol"; /** * @title TestLib_Buffer */ contract TestLib_Buffer { using Lib_Buffer for Lib_Buffer.Buffer; Lib_Buffer.Buffer internal buf; function push( bytes32 _value, bytes27 _extraData ) public { buf.push( _value, _extraData ); } function get( uint256 _index ) public view returns ( bytes32 ) { return buf.get(_index); } function deleteElementsAfterInclusive( uint40 _index ) public { return buf.deleteElementsAfterInclusive( _index ); } function deleteElementsAfterInclusive( uint40 _index, bytes27 _extraData ) public { return buf.deleteElementsAfterInclusive( _index, _extraData ); } function getLength() public view returns ( uint40 ) { return buf.getLength(); } function setExtraData( bytes27 _extraData ) public { return buf.setExtraData( _extraData ); } function getExtraData() public view returns ( bytes27 ) { return buf.getExtraData(); } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_MerkleTree } from "../../libraries/utils/Lib_MerkleTree.sol"; /* Interface Imports */ import { iOVM_CanonicalTransactionChain } from "../../iOVM/chain/iOVM_CanonicalTransactionChain.sol"; import { iOVM_ChainStorageContainer } from "../../iOVM/chain/iOVM_ChainStorageContainer.sol"; /* Contract Imports */ import { OVM_ExecutionManager } from "../execution/OVM_ExecutionManager.sol"; /* External Imports */ import { Math } from "@openzeppelin/contracts/math/Math.sol"; /** * @title OVM_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. * If the Sequencer does not include an enqueued transaction within the 'force inclusion period', * then any account may force it to be included by calling appendQueueBatch(). * * Compiler used: solc * Runtime target: EVM */ contract OVM_CanonicalTransactionChain is iOVM_CanonicalTransactionChain, Lib_AddressResolver { /************* * Constants * *************/ // L2 tx gas-related uint256 constant public MIN_ROLLUP_TX_GAS = 100000; uint256 constant public MAX_ROLLUP_TX_SIZE = 50000; uint256 constant public L2_GAS_DISCOUNT_DIVISOR = 32; // Encoding-related (all in bytes) uint256 constant internal BATCH_CONTEXT_SIZE = 16; uint256 constant internal BATCH_CONTEXT_LENGTH_POS = 12; uint256 constant internal BATCH_CONTEXT_START_POS = 15; uint256 constant internal TX_DATA_HEADER_SIZE = 3; uint256 constant internal BYTES_TILL_TX_DATA = 65; /************* * Variables * *************/ uint256 public forceInclusionPeriodSeconds; uint256 public forceInclusionPeriodBlocks; uint256 public maxTransactionGasLimit; /*************** * Constructor * ***************/ constructor( address _libAddressManager, uint256 _forceInclusionPeriodSeconds, uint256 _forceInclusionPeriodBlocks, uint256 _maxTransactionGasLimit ) Lib_AddressResolver(_libAddressManager) { forceInclusionPeriodSeconds = _forceInclusionPeriodSeconds; forceInclusionPeriodBlocks = _forceInclusionPeriodBlocks; maxTransactionGasLimit = _maxTransactionGasLimit; } /******************** * Public Functions * ********************/ /** * Accesses the batch storage container. * @return Reference to the batch storage container. */ function batches() override public view returns ( iOVM_ChainStorageContainer ) { return iOVM_ChainStorageContainer( resolve("OVM_ChainStorageContainer-CTC-batches") ); } /** * Accesses the queue storage container. * @return Reference to the queue storage container. */ function queue() override public view returns ( iOVM_ChainStorageContainer ) { return iOVM_ChainStorageContainer( resolve("OVM_ChainStorageContainer-CTC-queue") ); } /** * Retrieves the total number of elements submitted. * @return _totalElements Total submitted elements. */ function getTotalElements() override 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() override 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() override public view returns ( uint40 ) { (,uint40 nextQueueIndex,,) = _getBatchExtraData(); return nextQueueIndex; } /** * Returns the timestamp of the last transaction. * @return Timestamp for the last transaction. */ function getLastTimestamp() override public view returns ( uint40 ) { (,,uint40 lastTimestamp,) = _getBatchExtraData(); return lastTimestamp; } /** * Returns the blocknumber of the last transaction. * @return Blocknumber for the last transaction. */ function getLastBlockNumber() override 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 ) override public view returns ( Lib_OVMCodec.QueueElement memory _element ) { return _getQueueElement( _index, queue() ); } /** * Get the number of queue elements which have not yet been included. * @return Number of pending queue elements. */ function getNumPendingQueueElements() override public view returns ( uint40 ) { return getQueueLength() - getNextQueueIndex(); } /** * Retrieves the length of the queue, including * both pending and canonical transactions. * @return Length of the queue. */ function getQueueLength() override public view returns ( uint40 ) { return _getQueueLength( queue() ); } /** * 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 ) override public { 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." ); // We need to consume some amount of L1 gas in order to rate limit transactions going into // L2. However, L2 is cheaper than L1 so we only need to burn some small proportion of the // provided L1 gas. uint256 gasToConsume = _gasLimit/L2_GAS_DISCOUNT_DIVISOR; uint256 startingGas = gasleft(); // Although this check is not necessary (burn below will run out of gas if not true), it // gives the user an explicit reason as to why the enqueue attempt failed. require( startingGas > gasToConsume, "Insufficient gas for L2 rate limiting burn." ); // Here we do some "dumb" work in order to burn gas, although we should probably replace // this with something like minting gas token later on. uint256 i; while(startingGas - gasleft() < gasToConsume) { i++; } bytes32 transactionHash = keccak256( abi.encode( msg.sender, _target, _gasLimit, _data ) ); bytes32 timestampAndBlockNumber; assembly { timestampAndBlockNumber := timestamp() timestampAndBlockNumber := or(timestampAndBlockNumber, shl(40, number())) } iOVM_ChainStorageContainer queueRef = queue(); queueRef.push(transactionHash); queueRef.push(timestampAndBlockNumber); // 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 = queueRef.length() / 2 - 1; emit TransactionEnqueued( msg.sender, _target, _gasLimit, _data, queueIndex, block.timestamp ); } /** * Appends a given number of queued transactions as a single batch. * param _numQueuedTransactions Number of transactions to append. */ function appendQueueBatch( uint256 // _numQueuedTransactions ) override public pure { // TEMPORARY: Disable `appendQueueBatch` for minnet revert("appendQueueBatch is currently disabled."); // solhint-disable max-line-length // _numQueuedTransactions = Math.min(_numQueuedTransactions, getNumPendingQueueElements()); // require( // _numQueuedTransactions > 0, // "Must append more than zero transactions." // ); // bytes32[] memory leaves = new bytes32[](_numQueuedTransactions); // uint40 nextQueueIndex = getNextQueueIndex(); // for (uint256 i = 0; i < _numQueuedTransactions; i++) { // if (msg.sender != resolve("OVM_Sequencer")) { // Lib_OVMCodec.QueueElement memory el = getQueueElement(nextQueueIndex); // require( // el.timestamp + forceInclusionPeriodSeconds < block.timestamp, // "Queue transactions cannot be submitted during the sequencer inclusion period." // ); // } // leaves[i] = _getQueueLeafHash(nextQueueIndex); // nextQueueIndex++; // } // Lib_OVMCodec.QueueElement memory lastElement = getQueueElement(nextQueueIndex - 1); // _appendBatch( // Lib_MerkleTree.getMerkleRoot(leaves), // _numQueuedTransactions, // _numQueuedTransactions, // lastElement.timestamp, // lastElement.blockNumber // ); // emit QueueBatchAppended( // nextQueueIndex - _numQueuedTransactions, // _numQueuedTransactions, // getTotalElements() // ); // solhint-enable max-line-length } /** * 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() override public { 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." ); 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." ); // Take a reference to the queue and its length so we don't have to keep resolving it. // Length isn't going to change during the course of execution, so it's fine to simply // resolve this once at the start. Saves gas. iOVM_ChainStorageContainer queueRef = queue(); uint40 queueLength = _getQueueLength(queueRef); // Reserve some memory to save gas on hashing later on. This is a relatively safe estimate // for the average transaction size that will prevent having to resize this chunk of memory // later on. Saves gas. bytes memory hashMemory = new bytes((msg.data.length / totalElementsToAppend) * 2); // Initialize the array of canonical chain leaves that we will append. bytes32[] memory leaves = new bytes32[](totalElementsToAppend); // Each leaf index corresponds to a tx, either sequenced or enqueued. uint32 leafIndex = 0; // Counter for number of sequencer transactions appended so far. uint32 numSequencerTransactions = 0; // We will sequentially append leaves which are pointers to the queue. // The initial queue index is what is currently in storage. uint40 nextQueueIndex = getNextQueueIndex(); BatchContext memory curContext; for (uint32 i = 0; i < numContexts; i++) { BatchContext memory nextContext = _getBatchContext(i); if (i == 0) { // Execute a special check for the first batch. _validateFirstBatchContext(nextContext); } // Execute this check on every single batch, including the first one. _validateNextBatchContext( curContext, nextContext, nextQueueIndex, queueRef ); // Now we can update our current context. curContext = nextContext; // Process sequencer transactions first. for (uint32 j = 0; j < curContext.numSequencedTransactions; j++) { uint256 txDataLength; assembly { txDataLength := shr(232, calldataload(nextTransactionPtr)) } require( txDataLength <= MAX_ROLLUP_TX_SIZE, "Transaction data size exceeds maximum for rollup transaction." ); leaves[leafIndex] = _getSequencerLeafHash( curContext, nextTransactionPtr, txDataLength, hashMemory ); nextTransactionPtr += uint40(TX_DATA_HEADER_SIZE + txDataLength); numSequencerTransactions++; leafIndex++; } // Now process any subsequent queue transactions. for (uint32 j = 0; j < curContext.numSubsequentQueueTransactions; j++) { require( nextQueueIndex < queueLength, "Not enough queued transactions to append." ); leaves[leafIndex] = _getQueueLeafHash(nextQueueIndex); nextQueueIndex++; leafIndex++; } } _validateFinalBatchContext( curContext, nextQueueIndex, queueLength, queueRef ); require( msg.data.length == nextTransactionPtr, "Not all sequencer transactions were processed." ); require( leafIndex == totalElementsToAppend, "Actual transaction index does not match expected total elements to append." ); // 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 = _getQueueElement( nextQueueIndex - 1, queueRef ); 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 _appendBatch( Lib_MerkleTree.getMerkleRoot(leaves), totalElementsToAppend, numQueuedTransactions, blockTimestamp, blockNumber ); emit SequencerBatchAppended( nextQueueIndex - numQueuedTransactions, numQueuedTransactions, getTotalElements() ); } /** * Verifies whether a transaction is included in the chain. * @param _transaction Transaction to verify. * @param _txChainElement Transaction chain element corresponding to the transaction. * @param _batchHeader Header of the batch the transaction was included in. * @param _inclusionProof Inclusion proof for the provided transaction chain element. * @return True if the transaction exists in the CTC, false if not. */ function verifyTransaction( Lib_OVMCodec.Transaction memory _transaction, Lib_OVMCodec.TransactionChainElement memory _txChainElement, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _inclusionProof ) override public view returns ( bool ) { if (_txChainElement.isSequenced == true) { return _verifySequencerTransaction( _transaction, _txChainElement, _batchHeader, _inclusionProof ); } else { return _verifyQueueTransaction( _transaction, _txChainElement.queueIndex, _batchHeader, _inclusionProof ); } } /********************** * 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 _nextQueueIndex 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 _nextQueueIndex, uint40 _timestamp, uint40 _blockNumber ) internal pure returns ( bytes27 ) { bytes27 extraData; assembly { extraData := _totalElements extraData := or(extraData, shl(40, _nextQueueIndex)) extraData := or(extraData, shl(80, _timestamp)) extraData := or(extraData, shl(120, _blockNumber)) extraData := shl(40, extraData) } return extraData; } /** * Retrieves the hash of a queue element. * @param _index Index of the queue element to retrieve a hash for. * @return Hash of the queue element. */ function _getQueueLeafHash( uint256 _index ) internal pure returns ( bytes32 ) { return _hashTransactionChainElement( Lib_OVMCodec.TransactionChainElement({ isSequenced: false, queueIndex: _index, timestamp: 0, blockNumber: 0, txData: hex"" }) ); } /** * 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, iOVM_ChainStorageContainer _queueRef ) internal view returns ( Lib_OVMCodec.QueueElement memory _element ) { // The underlying queue data structure stores 2 elements // per insertion, so to get the actual desired queue index // we need to multiply by 2. uint40 trueIndex = uint40(_index * 2); bytes32 transactionHash = _queueRef.get(trueIndex); bytes32 timestampAndBlockNumber = _queueRef.get(trueIndex + 1); uint40 elementTimestamp; uint40 elementBlockNumber; // solhint-disable max-line-length assembly { elementTimestamp := and(timestampAndBlockNumber, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF) elementBlockNumber := shr(40, and(timestampAndBlockNumber, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000)) } // solhint-enable max-line-length return Lib_OVMCodec.QueueElement({ transactionHash: transactionHash, timestamp: elementTimestamp, blockNumber: elementBlockNumber }); } /** * Retrieves the length of the queue. * @return Length of the queue. */ function _getQueueLength( iOVM_ChainStorageContainer _queueRef ) internal view returns ( uint40 ) { // The underlying queue data structure stores 2 elements // per insertion, so to get the real queue length we need // to divide by 2. return uint40(_queueRef.length() / 2); } /** * Retrieves the hash of a sequencer element. * @param _context Batch context for the given element. * @param _nextTransactionPtr Pointer to the next transaction in the calldata. * @param _txDataLength Length of the transaction item. * @return Hash of the sequencer element. */ function _getSequencerLeafHash( BatchContext memory _context, uint256 _nextTransactionPtr, uint256 _txDataLength, bytes memory _hashMemory ) internal pure returns ( bytes32 ) { // Only allocate more memory if we didn't reserve enough to begin with. if (BYTES_TILL_TX_DATA + _txDataLength > _hashMemory.length) { _hashMemory = new bytes(BYTES_TILL_TX_DATA + _txDataLength); } uint256 ctxTimestamp = _context.timestamp; uint256 ctxBlockNumber = _context.blockNumber; bytes32 leafHash; assembly { let chainElementStart := add(_hashMemory, 0x20) // Set the first byte equal to `1` to indicate this is a sequencer chain element. // This distinguishes sequencer ChainElements from queue ChainElements because // all queue ChainElements are ABI encoded and the first byte of ABI encoded // elements is always zero mstore8(chainElementStart, 1) mstore(add(chainElementStart, 1), ctxTimestamp) mstore(add(chainElementStart, 33), ctxBlockNumber) // solhint-disable-next-line max-line-length calldatacopy(add(chainElementStart, BYTES_TILL_TX_DATA), add(_nextTransactionPtr, 3), _txDataLength) leafHash := keccak256(chainElementStart, add(BYTES_TILL_TX_DATA, _txDataLength)) } return leafHash; } /** * Retrieves the hash of a sequencer element. * @param _txChainElement The chain element which is hashed to calculate the leaf. * @return Hash of the sequencer element. */ function _getSequencerLeafHash( Lib_OVMCodec.TransactionChainElement memory _txChainElement ) internal view returns( bytes32 ) { bytes memory txData = _txChainElement.txData; uint256 txDataLength = _txChainElement.txData.length; bytes memory chainElement = new bytes(BYTES_TILL_TX_DATA + txDataLength); uint256 ctxTimestamp = _txChainElement.timestamp; uint256 ctxBlockNumber = _txChainElement.blockNumber; bytes32 leafHash; assembly { let chainElementStart := add(chainElement, 0x20) // Set the first byte equal to `1` to indicate this is a sequencer chain element. // This distinguishes sequencer ChainElements from queue ChainElements because // all queue ChainElements are ABI encoded and the first byte of ABI encoded // elements is always zero mstore8(chainElementStart, 1) mstore(add(chainElementStart, 1), ctxTimestamp) mstore(add(chainElementStart, 33), ctxBlockNumber) // solhint-disable-next-line max-line-length pop(staticcall(gas(), 0x04, add(txData, 0x20), txDataLength, add(chainElementStart, BYTES_TILL_TX_DATA), txDataLength)) leafHash := keccak256(chainElementStart, add(BYTES_TILL_TX_DATA, txDataLength)) } return leafHash; } /** * 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 { iOVM_ChainStorageContainer 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( 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); } /** * Checks that the first batch context in a sequencer submission is valid * @param _firstContext The batch context to validate. */ function _validateFirstBatchContext( BatchContext memory _firstContext ) internal view { // If there are existing elements, this batch must have the same context // or a later timestamp and block number. if (getTotalElements() > 0) { (,, uint40 lastTimestamp, uint40 lastBlockNumber) = _getBatchExtraData(); require( _firstContext.blockNumber >= lastBlockNumber, "Context block number is lower than last submitted." ); require( _firstContext.timestamp >= lastTimestamp, "Context timestamp is lower than last submitted." ); } // Sequencer cannot submit contexts which are more than the force inclusion period old. require( _firstContext.timestamp + forceInclusionPeriodSeconds >= block.timestamp, "Context timestamp too far in the past." ); require( _firstContext.blockNumber + forceInclusionPeriodBlocks >= block.number, "Context block number too far in the past." ); } /** * Checks that a given batch context has a time context which is below a given que element * @param _context The batch context to validate has values lower. * @param _queueIndex Index of the queue element we are validating came later than the context. * @param _queueRef The storage container for the queue. */ function _validateContextBeforeEnqueue( BatchContext memory _context, uint40 _queueIndex, iOVM_ChainStorageContainer _queueRef ) internal view { Lib_OVMCodec.QueueElement memory nextQueueElement = _getQueueElement( _queueIndex, _queueRef ); // If the force inclusion period has passed for an enqueued transaction, it MUST be the // next chain element. require( block.timestamp < nextQueueElement.timestamp + forceInclusionPeriodSeconds, // solhint-disable-next-line max-line-length "Previously enqueued batches have expired and must be appended before a new sequencer batch." ); // Just like sequencer transaction times must be increasing relative to each other, // We also require that they be increasing relative to any interspersed queue elements. require( _context.timestamp <= nextQueueElement.timestamp, "Sequencer transaction timestamp exceeds that of next queue element." ); require( _context.blockNumber <= nextQueueElement.blockNumber, "Sequencer transaction blockNumber exceeds that of next queue element." ); } /** * Checks that a given batch context is valid based on its previous context, and the next queue * elemtent. * @param _prevContext The previously validated batch context. * @param _nextContext The batch context to validate with this call. * @param _nextQueueIndex Index of the next queue element to process for the _nextContext's * subsequentQueueElements. * @param _queueRef The storage container for the queue. */ function _validateNextBatchContext( BatchContext memory _prevContext, BatchContext memory _nextContext, uint40 _nextQueueIndex, iOVM_ChainStorageContainer _queueRef ) internal view { // All sequencer transactions' times must be greater than or equal to the previous ones. require( _nextContext.timestamp >= _prevContext.timestamp, "Context timestamp values must monotonically increase." ); require( _nextContext.blockNumber >= _prevContext.blockNumber, "Context blockNumber values must monotonically increase." ); // If there is going to be a queue element pulled in from this context: if (_nextContext.numSubsequentQueueTransactions > 0) { _validateContextBeforeEnqueue( _nextContext, _nextQueueIndex, _queueRef ); } } /** * Checks that the final batch context in a sequencer submission is valid. * @param _finalContext The batch context to validate. * @param _queueLength The length of the queue at the start of the batchAppend call. * @param _nextQueueIndex The next element in the queue that will be pulled into the CTC. * @param _queueRef The storage container for the queue. */ function _validateFinalBatchContext( BatchContext memory _finalContext, uint40 _nextQueueIndex, uint40 _queueLength, iOVM_ChainStorageContainer _queueRef ) internal view { // If the queue is not now empty, check the mononoticity of whatever the next batch that // will come in is. if (_queueLength - _nextQueueIndex > 0 && _finalContext.numSubsequentQueueTransactions == 0) { _validateContextBeforeEnqueue( _finalContext, _nextQueueIndex, _queueRef ); } // Batches cannot be added from the future, or subsequent enqueue() contexts would violate // monotonicity. require(_finalContext.timestamp <= block.timestamp, "Context timestamp is from the future."); require(_finalContext.blockNumber <= block.number, "Context block number is from the future."); } /** * Hashes a transaction chain element. * @param _element Chain element to hash. * @return Hash of the chain element. */ function _hashTransactionChainElement( Lib_OVMCodec.TransactionChainElement memory _element ) internal pure returns ( bytes32 ) { return keccak256( abi.encode( _element.isSequenced, _element.queueIndex, _element.timestamp, _element.blockNumber, _element.txData ) ); } /** * Verifies a sequencer transaction, returning true if it was indeed included in the CTC * @param _transaction The transaction we are verifying inclusion of. * @param _txChainElement The chain element that the transaction is claimed to be a part of. * @param _batchHeader Header of the batch the transaction was included in. * @param _inclusionProof An inclusion proof into the CTC at a particular index. * @return True if the transaction was included in the specified location, else false. */ function _verifySequencerTransaction( Lib_OVMCodec.Transaction memory _transaction, Lib_OVMCodec.TransactionChainElement memory _txChainElement, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _inclusionProof ) internal view returns ( bool ) { OVM_ExecutionManager ovmExecutionManager = OVM_ExecutionManager(resolve("OVM_ExecutionManager")); uint256 gasLimit = ovmExecutionManager.getMaxTransactionGasLimit(); bytes32 leafHash = _getSequencerLeafHash(_txChainElement); require( _verifyElement( leafHash, _batchHeader, _inclusionProof ), "Invalid Sequencer transaction inclusion proof." ); require( _transaction.blockNumber == _txChainElement.blockNumber && _transaction.timestamp == _txChainElement.timestamp && _transaction.entrypoint == resolve("OVM_DecompressionPrecompileAddress") && _transaction.gasLimit == gasLimit && _transaction.l1TxOrigin == address(0) && _transaction.l1QueueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE && keccak256(_transaction.data) == keccak256(_txChainElement.txData), "Invalid Sequencer transaction." ); return true; } /** * Verifies a queue transaction, returning true if it was indeed included in the CTC * @param _transaction The transaction we are verifying inclusion of. * @param _queueIndex The queueIndex of the queued transaction. * @param _batchHeader Header of the batch the transaction was included in. * @param _inclusionProof An inclusion proof into the CTC at a particular index (should point to * queue tx). * @return True if the transaction was included in the specified location, else false. */ function _verifyQueueTransaction( Lib_OVMCodec.Transaction memory _transaction, uint256 _queueIndex, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _inclusionProof ) internal view returns ( bool ) { bytes32 leafHash = _getQueueLeafHash(_queueIndex); require( _verifyElement( leafHash, _batchHeader, _inclusionProof ), "Invalid Queue transaction inclusion proof." ); bytes32 transactionHash = keccak256( abi.encode( _transaction.l1TxOrigin, _transaction.entrypoint, _transaction.gasLimit, _transaction.data ) ); Lib_OVMCodec.QueueElement memory el = getQueueElement(_queueIndex); require( el.transactionHash == transactionHash && el.timestamp == _transaction.timestamp && el.blockNumber == _transaction.blockNumber, "Invalid Queue transaction." ); return true; } /** * Verifies a batch inclusion proof. * @param _element Hash of the element to verify a proof for. * @param _batchHeader Header of the batch in which the element was included. * @param _proof Merkle inclusion proof for the element. */ function _verifyElement( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) internal view returns ( bool ) { require( Lib_OVMCodec.hashBatchHeader(_batchHeader) == batches().get(uint32(_batchHeader.batchIndex)), "Invalid batch header." ); require( Lib_MerkleTree.verify( _batchHeader.batchRoot, _element, _proof.index, _proof.siblings, _batchHeader.batchSize ), "Invalid inclusion proof." ); return true; } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol"; import { Lib_EthUtils } from "../../libraries/utils/Lib_EthUtils.sol"; import { Lib_ErrorUtils } from "../../libraries/utils/Lib_ErrorUtils.sol"; import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; /* Interface Imports */ import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol"; import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol"; import { iOVM_SafetyChecker } from "../../iOVM/execution/iOVM_SafetyChecker.sol"; /* Contract Imports */ import { OVM_DeployerWhitelist } from "../predeploys/OVM_DeployerWhitelist.sol"; /* External Imports */ import { Math } from "@openzeppelin/contracts/math/Math.sol"; /** * @title OVM_ExecutionManager * @dev The Execution Manager (EM) is the core of our OVM implementation, and provides a sandboxed * environment allowing us to execute OVM transactions deterministically on either Layer 1 or * Layer 2. * The EM's run() function is the first function called during the execution of any * transaction on L2. * For each context-dependent EVM operation the EM has a function which implements a corresponding * OVM operation, which will read state from the State Manager contract. * The EM relies on the Safety Checker to verify that code deployed to Layer 2 does not contain any * context-dependent operations. * * Compiler used: solc * Runtime target: EVM */ contract OVM_ExecutionManager is iOVM_ExecutionManager, Lib_AddressResolver { /******************************** * External Contract References * ********************************/ iOVM_SafetyChecker internal ovmSafetyChecker; iOVM_StateManager internal ovmStateManager; /******************************* * Execution Context Variables * *******************************/ GasMeterConfig internal gasMeterConfig; GlobalContext internal globalContext; TransactionContext internal transactionContext; MessageContext internal messageContext; TransactionRecord internal transactionRecord; MessageRecord internal messageRecord; /************************** * Gas Metering Constants * **************************/ address constant GAS_METADATA_ADDRESS = 0x06a506A506a506A506a506a506A506A506A506A5; uint256 constant NUISANCE_GAS_SLOAD = 20000; uint256 constant NUISANCE_GAS_SSTORE = 20000; uint256 constant MIN_NUISANCE_GAS_PER_CONTRACT = 30000; uint256 constant NUISANCE_GAS_PER_CONTRACT_BYTE = 100; uint256 constant MIN_GAS_FOR_INVALID_STATE_ACCESS = 30000; /************************** * Native Value Constants * **************************/ // Public so we can access and make assertions in integration tests. uint256 public constant CALL_WITH_VALUE_INTRINSIC_GAS = 90000; /************************** * Default Context Values * **************************/ uint256 constant DEFAULT_UINT256 = 0xdefa017defa017defa017defa017defa017defa017defa017defa017defa017d; address constant DEFAULT_ADDRESS = 0xdEfa017defA017DeFA017DEfa017DeFA017DeFa0; /************************************* * Container Contract Address Prefix * *************************************/ /** * @dev The Execution Manager and State Manager each have this 30 byte prefix, * and are uncallable. */ address constant CONTAINER_CONTRACT_PREFIX = 0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager, GasMeterConfig memory _gasMeterConfig, GlobalContext memory _globalContext ) Lib_AddressResolver(_libAddressManager) { ovmSafetyChecker = iOVM_SafetyChecker(resolve("OVM_SafetyChecker")); gasMeterConfig = _gasMeterConfig; globalContext = _globalContext; _resetContext(); } /********************** * Function Modifiers * **********************/ /** * Applies dynamically-sized refund to a transaction to account for the difference in execution * between L1 and L2, so that the overall cost of the ovmOPCODE is fixed. * @param _cost Desired gas cost for the function after the refund. */ modifier netGasCost( uint256 _cost ) { uint256 gasProvided = gasleft(); _; uint256 gasUsed = gasProvided - gasleft(); // We want to refund everything *except* the specified cost. if (_cost < gasUsed) { transactionRecord.ovmGasRefund += gasUsed - _cost; } } /** * Applies a fixed-size gas refund to a transaction to account for the difference in execution * between L1 and L2, so that the overall cost of an ovmOPCODE can be lowered. * @param _discount Amount of gas cost to refund for the ovmOPCODE. */ modifier fixedGasDiscount( uint256 _discount ) { uint256 gasProvided = gasleft(); _; uint256 gasUsed = gasProvided - gasleft(); // We want to refund the specified _discount, unless this risks underflow. if (_discount < gasUsed) { transactionRecord.ovmGasRefund += _discount; } else { // refund all we can without risking underflow. transactionRecord.ovmGasRefund += gasUsed; } } /** * Makes sure we're not inside a static context. */ modifier notStatic() { if (messageContext.isStatic == true) { _revertWithFlag(RevertFlag.STATIC_VIOLATION); } _; } /************************************ * Transaction Execution Entrypoint * ************************************/ /** * Starts the execution of a transaction via the OVM_ExecutionManager. * @param _transaction Transaction data to be executed. * @param _ovmStateManager iOVM_StateManager implementation providing account state. */ function run( Lib_OVMCodec.Transaction memory _transaction, address _ovmStateManager ) override external returns ( bytes memory ) { // Make sure that run() is not re-enterable. This condition should always be satisfied // Once run has been called once, due to the behavior of _isValidInput(). if (transactionContext.ovmNUMBER != DEFAULT_UINT256) { return bytes(""); } // Store our OVM_StateManager instance (significantly easier than attempting to pass the // address around in calldata). ovmStateManager = iOVM_StateManager(_ovmStateManager); // Make sure this function can't be called by anyone except the owner of the // OVM_StateManager (expected to be an OVM_StateTransitioner). We can revert here because // this would make the `run` itself invalid. require( // This method may return false during fraud proofs, but always returns true in // L2 nodes' State Manager precompile. ovmStateManager.isAuthenticated(msg.sender), "Only authenticated addresses in ovmStateManager can call this function" ); // Initialize the execution context, must be initialized before we perform any gas metering // or we'll throw a nuisance gas error. _initContext(_transaction); // TEMPORARY: Gas metering is disabled for minnet. // // Check whether we need to start a new epoch, do so if necessary. // _checkNeedsNewEpoch(_transaction.timestamp); // Make sure the transaction's gas limit is valid. We don't revert here because we reserve // reverts for INVALID_STATE_ACCESS. if (_isValidInput(_transaction) == false) { _resetContext(); return bytes(""); } // TEMPORARY: Gas metering is disabled for minnet. // // Check gas right before the call to get total gas consumed by OVM transaction. // uint256 gasProvided = gasleft(); // Run the transaction, make sure to meter the gas usage. (, bytes memory returndata) = ovmCALL( _transaction.gasLimit - gasMeterConfig.minTransactionGasLimit, _transaction.entrypoint, 0, _transaction.data ); // TEMPORARY: Gas metering is disabled for minnet. // // Update the cumulative gas based on the amount of gas used. // uint256 gasUsed = gasProvided - gasleft(); // _updateCumulativeGas(gasUsed, _transaction.l1QueueOrigin); // Wipe the execution context. _resetContext(); return returndata; } /****************************** * Opcodes: Execution Context * ******************************/ /** * @notice Overrides CALLER. * @return _CALLER Address of the CALLER within the current message context. */ function ovmCALLER() override external view returns ( address _CALLER ) { return messageContext.ovmCALLER; } /** * @notice Overrides ADDRESS. * @return _ADDRESS Active ADDRESS within the current message context. */ function ovmADDRESS() override public view returns ( address _ADDRESS ) { return messageContext.ovmADDRESS; } /** * @notice Overrides CALLVALUE. * @return _CALLVALUE Value sent along with the call according to the current message context. */ function ovmCALLVALUE() override public view returns ( uint256 _CALLVALUE ) { return messageContext.ovmCALLVALUE; } /** * @notice Overrides TIMESTAMP. * @return _TIMESTAMP Value of the TIMESTAMP within the transaction context. */ function ovmTIMESTAMP() override external view returns ( uint256 _TIMESTAMP ) { return transactionContext.ovmTIMESTAMP; } /** * @notice Overrides NUMBER. * @return _NUMBER Value of the NUMBER within the transaction context. */ function ovmNUMBER() override external view returns ( uint256 _NUMBER ) { return transactionContext.ovmNUMBER; } /** * @notice Overrides GASLIMIT. * @return _GASLIMIT Value of the block's GASLIMIT within the transaction context. */ function ovmGASLIMIT() override external view returns ( uint256 _GASLIMIT ) { return transactionContext.ovmGASLIMIT; } /** * @notice Overrides CHAINID. * @return _CHAINID Value of the chain's CHAINID within the global context. */ function ovmCHAINID() override external view returns ( uint256 _CHAINID ) { return globalContext.ovmCHAINID; } /********************************* * Opcodes: L2 Execution Context * *********************************/ /** * @notice Specifies from which source (Sequencer or Queue) this transaction originated from. * @return _queueOrigin Enum indicating the ovmL1QUEUEORIGIN within the current message context. */ function ovmL1QUEUEORIGIN() override external view returns ( Lib_OVMCodec.QueueOrigin _queueOrigin ) { return transactionContext.ovmL1QUEUEORIGIN; } /** * @notice Specifies which L1 account, if any, sent this transaction by calling enqueue(). * @return _l1TxOrigin Address of the account which sent the tx into L2 from L1. */ function ovmL1TXORIGIN() override external view returns ( address _l1TxOrigin ) { return transactionContext.ovmL1TXORIGIN; } /******************** * Opcodes: Halting * ********************/ /** * @notice Overrides REVERT. * @param _data Bytes data to pass along with the REVERT. */ function ovmREVERT( bytes memory _data ) override public { _revertWithFlag(RevertFlag.INTENTIONAL_REVERT, _data); } /****************************** * Opcodes: Contract Creation * ******************************/ /** * @notice Overrides CREATE. * @param _bytecode Code to be used to CREATE a new contract. * @return Address of the created contract. * @return Revert data, if and only if the creation threw an exception. */ function ovmCREATE( bytes memory _bytecode ) override public notStatic fixedGasDiscount(40000) returns ( address, bytes memory ) { // Creator is always the current ADDRESS. address creator = ovmADDRESS(); // Check that the deployer is whitelisted, or // that arbitrary contract deployment has been enabled. _checkDeployerAllowed(creator); // Generate the correct CREATE address. address contractAddress = Lib_EthUtils.getAddressForCREATE( creator, _getAccountNonce(creator) ); return _createContract( contractAddress, _bytecode, MessageType.ovmCREATE ); } /** * @notice Overrides CREATE2. * @param _bytecode Code to be used to CREATE2 a new contract. * @param _salt Value used to determine the contract's address. * @return Address of the created contract. * @return Revert data, if and only if the creation threw an exception. */ function ovmCREATE2( bytes memory _bytecode, bytes32 _salt ) override external notStatic fixedGasDiscount(40000) returns ( address, bytes memory ) { // Creator is always the current ADDRESS. address creator = ovmADDRESS(); // Check that the deployer is whitelisted, or // that arbitrary contract deployment has been enabled. _checkDeployerAllowed(creator); // Generate the correct CREATE2 address. address contractAddress = Lib_EthUtils.getAddressForCREATE2( creator, _bytecode, _salt ); return _createContract( contractAddress, _bytecode, MessageType.ovmCREATE2 ); } /******************************* * Account Abstraction Opcodes * ******************************/ /** * Retrieves the nonce of the current ovmADDRESS. * @return _nonce Nonce of the current contract. */ function ovmGETNONCE() override external returns ( uint256 _nonce ) { return _getAccountNonce(ovmADDRESS()); } /** * Bumps the nonce of the current ovmADDRESS by one. */ function ovmINCREMENTNONCE() override external notStatic { address account = ovmADDRESS(); uint256 nonce = _getAccountNonce(account); // Prevent overflow. if (nonce + 1 > nonce) { _setAccountNonce(account, nonce + 1); } } /** * Creates a new EOA contract account, for account abstraction. * @dev Essentially functions like ovmCREATE or ovmCREATE2, but we can bypass a lot of checks * because the contract we're creating is trusted (no need to do safety checking or to * handle unexpected reverts). Doesn't need to return an address because the address is * assumed to be the user's actual address. * @param _messageHash Hash of a message signed by some user, for verification. * @param _v Signature `v` parameter. * @param _r Signature `r` parameter. * @param _s Signature `s` parameter. */ function ovmCREATEEOA( bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s ) override public notStatic { // Recover the EOA address from the message hash and signature parameters. Since we do the // hashing in advance, we don't have handle different message hashing schemes. Even if this // function were to return the wrong address (rather than explicitly returning the zero // address), the rest of the transaction would simply fail (since there's no EOA account to // actually execute the transaction). address eoa = ecrecover( _messageHash, _v + 27, _r, _s ); // Invalid signature is a case we proactively handle with a revert. We could alternatively // have this function return a `success` boolean, but this is just easier. if (eoa == address(0)) { ovmREVERT(bytes("Signature provided for EOA contract creation is invalid.")); } // If the user already has an EOA account, then there's no need to perform this operation. if (_hasEmptyAccount(eoa) == false) { return; } // We always need to initialize the contract with the default account values. _initPendingAccount(eoa); // Temporarily set the current address so it's easier to access on L2. address prevADDRESS = messageContext.ovmADDRESS; messageContext.ovmADDRESS = eoa; // Creates a duplicate of the OVM_ProxyEOA located at 0x42....09. Uses the following // "magic" prefix to deploy an exact copy of the code: // PUSH1 0x0D # size of this prefix in bytes // CODESIZE // SUB # subtract prefix size from codesize // DUP1 // PUSH1 0x0D // PUSH1 0x00 // CODECOPY # copy everything after prefix into memory at pos 0 // PUSH1 0x00 // RETURN # return the copied code address proxyEOA = Lib_EthUtils.createContract(abi.encodePacked( hex"600D380380600D6000396000f3", ovmEXTCODECOPY( Lib_PredeployAddresses.PROXY_EOA, 0, ovmEXTCODESIZE(Lib_PredeployAddresses.PROXY_EOA) ) )); // Reset the address now that we're done deploying. messageContext.ovmADDRESS = prevADDRESS; // Commit the account with its final values. _commitPendingAccount( eoa, address(proxyEOA), keccak256(Lib_EthUtils.getCode(address(proxyEOA))) ); _setAccountNonce(eoa, 0); } /********************************* * Opcodes: Contract Interaction * *********************************/ /** * @notice Overrides CALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _value ETH value to pass with the call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmCALL( uint256 _gasLimit, address _address, uint256 _value, bytes memory _calldata ) override public fixedGasDiscount(100000) returns ( bool _success, bytes memory _returndata ) { // CALL updates the CALLER and ADDRESS. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _address; nextMessageContext.ovmCALLVALUE = _value; return _callContract( nextMessageContext, _gasLimit, _address, _calldata, MessageType.ovmCALL ); } /** * @notice Overrides STATICCALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmSTATICCALL( uint256 _gasLimit, address _address, bytes memory _calldata ) override public fixedGasDiscount(80000) returns ( bool _success, bytes memory _returndata ) { // STATICCALL updates the CALLER, updates the ADDRESS, and runs in a static, // valueless context. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _address; nextMessageContext.isStatic = true; nextMessageContext.ovmCALLVALUE = 0; return _callContract( nextMessageContext, _gasLimit, _address, _calldata, MessageType.ovmSTATICCALL ); } /** * @notice Overrides DELEGATECALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmDELEGATECALL( uint256 _gasLimit, address _address, bytes memory _calldata ) override public fixedGasDiscount(40000) returns ( bool _success, bytes memory _returndata ) { // DELEGATECALL does not change anything about the message context. MessageContext memory nextMessageContext = messageContext; return _callContract( nextMessageContext, _gasLimit, _address, _calldata, MessageType.ovmDELEGATECALL ); } /** * @notice Legacy ovmCALL function which did not support ETH value; this maintains backwards * compatibility. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmCALL( uint256 _gasLimit, address _address, bytes memory _calldata ) override public returns( bool _success, bytes memory _returndata ) { // Legacy ovmCALL assumed always-0 value. return ovmCALL( _gasLimit, _address, 0, _calldata ); } /************************************ * Opcodes: Contract Storage Access * ************************************/ /** * @notice Overrides SLOAD. * @param _key 32 byte key of the storage slot to load. * @return _value 32 byte value of the requested storage slot. */ function ovmSLOAD( bytes32 _key ) override external netGasCost(40000) returns ( bytes32 _value ) { // We always SLOAD from the storage of ADDRESS. address contractAddress = ovmADDRESS(); return _getContractStorage( contractAddress, _key ); } /** * @notice Overrides SSTORE. * @param _key 32 byte key of the storage slot to set. * @param _value 32 byte value for the storage slot. */ function ovmSSTORE( bytes32 _key, bytes32 _value ) override external notStatic netGasCost(60000) { // We always SSTORE to the storage of ADDRESS. address contractAddress = ovmADDRESS(); _putContractStorage( contractAddress, _key, _value ); } /********************************* * Opcodes: Contract Code Access * *********************************/ /** * @notice Overrides EXTCODECOPY. * @param _contract Address of the contract to copy code from. * @param _offset Offset in bytes from the start of contract code to copy beyond. * @param _length Total number of bytes to copy from the contract's code. * @return _code Bytes of code copied from the requested contract. */ function ovmEXTCODECOPY( address _contract, uint256 _offset, uint256 _length ) override public returns ( bytes memory _code ) { return Lib_EthUtils.getCode( _getAccountEthAddress(_contract), _offset, _length ); } /** * @notice Overrides EXTCODESIZE. * @param _contract Address of the contract to query the size of. * @return _EXTCODESIZE Size of the requested contract in bytes. */ function ovmEXTCODESIZE( address _contract ) override public returns ( uint256 _EXTCODESIZE ) { return Lib_EthUtils.getCodeSize( _getAccountEthAddress(_contract) ); } /** * @notice Overrides EXTCODEHASH. * @param _contract Address of the contract to query the hash of. * @return _EXTCODEHASH Hash of the requested contract. */ function ovmEXTCODEHASH( address _contract ) override external returns ( bytes32 _EXTCODEHASH ) { return Lib_EthUtils.getCodeHash( _getAccountEthAddress(_contract) ); } /*************************************** * Public Functions: ETH Value Opcodes * ***************************************/ /** * @notice Overrides BALANCE. * NOTE: In the future, this could be optimized to directly invoke EM._getContractStorage(...). * @param _contract Address of the contract to query the OVM_ETH balance of. * @return _BALANCE OVM_ETH balance of the requested contract. */ function ovmBALANCE( address _contract ) override public returns ( uint256 _BALANCE ) { // Easiest way to get the balance is query OVM_ETH as normal. bytes memory balanceOfCalldata = abi.encodeWithSignature( "balanceOf(address)", _contract ); // Static call because this should be a read-only query. (bool success, bytes memory returndata) = ovmSTATICCALL( gasleft(), Lib_PredeployAddresses.OVM_ETH, balanceOfCalldata ); // All balanceOf queries should successfully return a uint, otherwise this must be an OOG. if (!success || returndata.length != 32) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } // Return the decoded balance. return abi.decode(returndata, (uint256)); } /** * @notice Overrides SELFBALANCE. * @return _BALANCE OVM_ETH balance of the requesting contract. */ function ovmSELFBALANCE() override external returns ( uint256 _BALANCE ) { return ovmBALANCE(ovmADDRESS()); } /*************************************** * Public Functions: Execution Context * ***************************************/ function getMaxTransactionGasLimit() external view override returns ( uint256 _maxTransactionGasLimit ) { return gasMeterConfig.maxTransactionGasLimit; } /******************************************** * Public Functions: Deployment Whitelisting * ********************************************/ /** * Checks whether the given address is on the whitelist to ovmCREATE/ovmCREATE2, * and reverts if not. * @param _deployerAddress Address attempting to deploy a contract. */ function _checkDeployerAllowed( address _deployerAddress ) internal { // From an OVM semantics perspective, this will appear identical to // the deployer ovmCALLing the whitelist. This is fine--in a sense, we are forcing them to. (bool success, bytes memory data) = ovmSTATICCALL( gasleft(), Lib_PredeployAddresses.DEPLOYER_WHITELIST, abi.encodeWithSelector( OVM_DeployerWhitelist.isDeployerAllowed.selector, _deployerAddress ) ); bool isAllowed = abi.decode(data, (bool)); if (!isAllowed || !success) { _revertWithFlag(RevertFlag.CREATOR_NOT_ALLOWED); } } /******************************************** * Internal Functions: Contract Interaction * ********************************************/ /** * Creates a new contract and associates it with some contract address. * @param _contractAddress Address to associate the created contract with. * @param _bytecode Bytecode to be used to create the contract. * @return Final OVM contract address. * @return Revertdata, if and only if the creation threw an exception. */ function _createContract( address _contractAddress, bytes memory _bytecode, MessageType _messageType ) internal returns ( address, bytes memory ) { // We always update the nonce of the creating account, even if the creation fails. _setAccountNonce(ovmADDRESS(), _getAccountNonce(ovmADDRESS()) + 1); // We're stepping into a CREATE or CREATE2, so we need to update ADDRESS to point // to the contract's associated address and CALLER to point to the previous ADDRESS. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = messageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _contractAddress; // Run the common logic which occurs between call-type and create-type messages, // passing in the creation bytecode and `true` to trigger create-specific logic. (bool success, bytes memory data) = _handleExternalMessage( nextMessageContext, gasleft(), _contractAddress, _bytecode, _messageType ); // Yellow paper requires that address returned is zero if the contract deployment fails. return ( success ? _contractAddress : address(0), data ); } /** * Calls the deployed contract associated with a given address. * @param _nextMessageContext Message context to be used for the call. * @param _gasLimit Amount of gas to be passed into this call. * @param _contract OVM address to be called. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function _callContract( MessageContext memory _nextMessageContext, uint256 _gasLimit, address _contract, bytes memory _calldata, MessageType _messageType ) internal returns ( bool _success, bytes memory _returndata ) { // We reserve addresses of the form 0xdeaddeaddead...NNNN for the container contracts in L2 // geth. So, we block calls to these addresses since they are not safe to run as an OVM // contract itself. if ( (uint256(_contract) & uint256(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000)) == uint256(CONTAINER_CONTRACT_PREFIX) ) { // solhint-disable-next-line max-line-length // EVM does not return data in the success case, see: https://github.com/ethereum/go-ethereum/blob/aae7660410f0ef90279e14afaaf2f429fdc2a186/core/vm/instructions.go#L600-L604 return (true, hex''); } // Both 0x0000... and the EVM precompiles have the same address on L1 and L2 --> // no trie lookup needed. address codeContractAddress = uint(_contract) < 100 ? _contract : _getAccountEthAddress(_contract); return _handleExternalMessage( _nextMessageContext, _gasLimit, codeContractAddress, _calldata, _messageType ); } /** * Handles all interactions which involve the execution manager calling out to untrusted code * (both calls and creates). Ensures that OVM-related measures are enforced, including L2 gas * refunds, nuisance gas, and flagged reversions. * * @param _nextMessageContext Message context to be used for the external message. * @param _gasLimit Amount of gas to be passed into this message. NOTE: this argument is * overwritten in some cases to avoid stack-too-deep. * @param _contract OVM address being called or deployed to * @param _data Data for the message (either calldata or creation code) * @param _messageType What type of ovmOPCODE this message corresponds to. * @return Whether or not the message (either a call or deployment) succeeded. * @return Data returned by the message. */ function _handleExternalMessage( MessageContext memory _nextMessageContext, // NOTE: this argument is overwritten in some cases to avoid stack-too-deep. uint256 _gasLimit, address _contract, bytes memory _data, MessageType _messageType ) internal returns ( bool, bytes memory ) { uint256 messageValue = _nextMessageContext.ovmCALLVALUE; // If there is value in this message, we need to transfer the ETH over before switching // contexts. if ( messageValue > 0 && _isValueType(_messageType) ) { // Handle out-of-intrinsic gas consistent with EVM behavior -- the subcall "appears to // revert" if we don't have enough gas to transfer the ETH. // Similar to dynamic gas cost of value exceeding gas here: // solhint-disable-next-line max-line-length // https://github.com/ethereum/go-ethereum/blob/c503f98f6d5e80e079c1d8a3601d188af2a899da/core/vm/interpreter.go#L268-L273 if (gasleft() < CALL_WITH_VALUE_INTRINSIC_GAS) { return (false, hex""); } // If there *is* enough gas to transfer ETH, then we need to make sure this amount of // gas is reserved (i.e. not given to the _contract.call below) to guarantee that // _handleExternalMessage can't run out of gas. In particular, in the event that // the call fails, we will need to transfer the ETH back to the sender. // Taking the lesser of _gasLimit and gasleft() - CALL_WITH_VALUE_INTRINSIC_GAS // guarantees that the second _attemptForcedEthTransfer below, if needed, always has // enough gas to succeed. _gasLimit = Math.min( _gasLimit, gasleft() - CALL_WITH_VALUE_INTRINSIC_GAS // Cannot overflow due to the above check. ); // Now transfer the value of the call. // The target is interpreted to be the next message's ovmADDRESS account. bool transferredOvmEth = _attemptForcedEthTransfer( _nextMessageContext.ovmADDRESS, messageValue ); // If the ETH transfer fails (should only be possible in the case of insufficient // balance), then treat this as a revert. This mirrors EVM behavior, see // solhint-disable-next-line max-line-length // https://github.com/ethereum/go-ethereum/blob/2dee31930c9977af2a9fcb518fb9838aa609a7cf/core/vm/evm.go#L298 if (!transferredOvmEth) { return (false, hex""); } } // We need to switch over to our next message context for the duration of this call. MessageContext memory prevMessageContext = messageContext; _switchMessageContext(prevMessageContext, _nextMessageContext); // Nuisance gas is a system used to bound the ability for an attacker to make fraud proofs // expensive by touching a lot of different accounts or storage slots. Since most contracts // only use a few storage slots during any given transaction, this shouldn't be a limiting // factor. uint256 prevNuisanceGasLeft = messageRecord.nuisanceGasLeft; uint256 nuisanceGasLimit = _getNuisanceGasLimit(_gasLimit); messageRecord.nuisanceGasLeft = nuisanceGasLimit; // Make the call and make sure to pass in the gas limit. Another instance of hidden // complexity. `_contract` is guaranteed to be a safe contract, meaning its return/revert // behavior can be controlled. In particular, we enforce that flags are passed through // revert data as to retrieve execution metadata that would normally be reverted out of // existence. bool success; bytes memory returndata; if (_isCreateType(_messageType)) { // safeCREATE() is a function which replicates a CREATE message, but uses return values // Which match that of CALL (i.e. bool, bytes). This allows many security checks to be // to be shared between untrusted call and create call frames. (success, returndata) = address(this).call{gas: _gasLimit}( abi.encodeWithSelector( this.safeCREATE.selector, _data, _contract ) ); } else { (success, returndata) = _contract.call{gas: _gasLimit}(_data); } // If the message threw an exception, its value should be returned back to the sender. // So, we force it back, BEFORE returning the messageContext to the previous addresses. // This operation is part of the reason we "reserved the intrinsic gas" above. if ( messageValue > 0 && _isValueType(_messageType) && !success ) { bool transferredOvmEth = _attemptForcedEthTransfer( prevMessageContext.ovmADDRESS, messageValue ); // Since we transferred it in above and the call reverted, the transfer back should // always pass. This code path should NEVER be triggered since we sent `messageValue` // worth of OVM_ETH into the target and reserved sufficient gas to execute the transfer, // but in case there is some edge case which has been missed, we revert the entire frame // (and its parent) to make sure the ETH gets sent back. if (!transferredOvmEth) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } } // Switch back to the original message context now that we're out of the call and all // OVM_ETH is in the right place. _switchMessageContext(_nextMessageContext, prevMessageContext); // Assuming there were no reverts, the message record should be accurate here. We'll update // this value in the case of a revert. uint256 nuisanceGasLeft = messageRecord.nuisanceGasLeft; // Reverts at this point are completely OK, but we need to make a few updates based on the // information passed through the revert. if (success == false) { ( RevertFlag flag, uint256 nuisanceGasLeftPostRevert, uint256 ovmGasRefund, bytes memory returndataFromFlag ) = _decodeRevertData(returndata); // INVALID_STATE_ACCESS is the only flag that triggers an immediate abort of the // parent EVM message. This behavior is necessary because INVALID_STATE_ACCESS must // halt any further transaction execution that could impact the execution result. if (flag == RevertFlag.INVALID_STATE_ACCESS) { _revertWithFlag(flag); } // INTENTIONAL_REVERT, UNSAFE_BYTECODE, STATIC_VIOLATION, and CREATOR_NOT_ALLOWED aren't // dependent on the input state, so we can just handle them like standard reverts. // Our only change here is to record the gas refund reported by the call (enforced by // safety checking). if ( flag == RevertFlag.INTENTIONAL_REVERT || flag == RevertFlag.UNSAFE_BYTECODE || flag == RevertFlag.STATIC_VIOLATION || flag == RevertFlag.CREATOR_NOT_ALLOWED ) { transactionRecord.ovmGasRefund = ovmGasRefund; } // INTENTIONAL_REVERT needs to pass up the user-provided return data encoded into the // flag, *not* the full encoded flag. Additionally, we surface custom error messages // to developers in the case of unsafe creations for improved devex. // All other revert types return no data. if ( flag == RevertFlag.INTENTIONAL_REVERT || flag == RevertFlag.UNSAFE_BYTECODE ) { returndata = returndataFromFlag; } else { returndata = hex''; } // Reverts mean we need to use up whatever "nuisance gas" was used by the call. // EXCEEDS_NUISANCE_GAS explicitly reduces the remaining nuisance gas for this message // to zero. OUT_OF_GAS is a "pseudo" flag given that messages return no data when they // run out of gas, so we have to treat this like EXCEEDS_NUISANCE_GAS. All other flags // will simply pass up the remaining nuisance gas. nuisanceGasLeft = nuisanceGasLeftPostRevert; } // We need to reset the nuisance gas back to its original value minus the amount used here. messageRecord.nuisanceGasLeft = prevNuisanceGasLeft - (nuisanceGasLimit - nuisanceGasLeft); return ( success, returndata ); } /** * Handles the creation-specific safety measures required for OVM contract deployment. * This function sanitizes the return types for creation messages to match calls (bool, bytes), * by being an external function which the EM can call, that mimics the success/fail case of the * CREATE. * This allows for consistent handling of both types of messages in _handleExternalMessage(). * Having this step occur as a separate call frame also allows us to easily revert the * contract deployment in the event that the code is unsafe. * * @param _creationCode Code to pass into CREATE for deployment. * @param _address OVM address being deployed to. */ function safeCREATE( bytes memory _creationCode, address _address ) external { // The only way this should callable is from within _createContract(), // and it should DEFINITELY not be callable by a non-EM code contract. if (msg.sender != address(this)) { return; } // Check that there is not already code at this address. if (_hasEmptyAccount(_address) == false) { // Note: in the EVM, this case burns all allotted gas. For improved // developer experience, we do return the remaining gas. _revertWithFlag( RevertFlag.CREATE_COLLISION ); } // Check the creation bytecode against the OVM_SafetyChecker. if (ovmSafetyChecker.isBytecodeSafe(_creationCode) == false) { // Note: in the EVM, this case burns all allotted gas. For improved // developer experience, we do return the remaining gas. _revertWithFlag( RevertFlag.UNSAFE_BYTECODE, // solhint-disable-next-line max-line-length Lib_ErrorUtils.encodeRevertString("Contract creation code contains unsafe opcodes. Did you use the right compiler or pass an unsafe constructor argument?") ); } // We always need to initialize the contract with the default account values. _initPendingAccount(_address); // Actually execute the EVM create message. // NOTE: The inline assembly below means we can NOT make any evm calls between here and then address ethAddress = Lib_EthUtils.createContract(_creationCode); if (ethAddress == address(0)) { // If the creation fails, the EVM lets us grab its revert data. This may contain a // revert flag to be used above in _handleExternalMessage, so we pass the revert data // back up unmodified. assembly { returndatacopy(0,0,returndatasize()) revert(0, returndatasize()) } } // Again simply checking that the deployed code is safe too. Contracts can generate // arbitrary deployment code, so there's no easy way to analyze this beforehand. bytes memory deployedCode = Lib_EthUtils.getCode(ethAddress); if (ovmSafetyChecker.isBytecodeSafe(deployedCode) == false) { _revertWithFlag( RevertFlag.UNSAFE_BYTECODE, // solhint-disable-next-line max-line-length Lib_ErrorUtils.encodeRevertString("Constructor attempted to deploy unsafe bytecode.") ); } // Contract creation didn't need to be reverted and the bytecode is safe. We finish up by // associating the desired address with the newly created contract's code hash and address. _commitPendingAccount( _address, ethAddress, Lib_EthUtils.getCodeHash(ethAddress) ); } /****************************************** * Internal Functions: Value Manipulation * ******************************************/ /** * Invokes an ovmCALL to OVM_ETH.transfer on behalf of the current ovmADDRESS, allowing us to * force movement of OVM_ETH in correspondence with ETH's native value functionality. * WARNING: this will send on behalf of whatever the messageContext.ovmADDRESS is in storage * at the time of the call. * NOTE: In the future, this could be optimized to directly invoke EM._setContractStorage(...). * @param _to Amount of OVM_ETH to be sent. * @param _value Amount of OVM_ETH to send. * @return _success Whether or not the transfer worked. */ function _attemptForcedEthTransfer( address _to, uint256 _value ) internal returns( bool _success ) { bytes memory transferCalldata = abi.encodeWithSignature( "transfer(address,uint256)", _to, _value ); // OVM_ETH inherits from the UniswapV2ERC20 standard. In this implementation, its return // type is a boolean. However, the implementation always returns true if it does not revert // Thus, success of the call frame is sufficient to infer success of the transfer itself. (bool success, ) = ovmCALL( gasleft(), Lib_PredeployAddresses.OVM_ETH, 0, transferCalldata ); return success; } /****************************************** * Internal Functions: State Manipulation * ******************************************/ /** * Checks whether an account exists within the OVM_StateManager. * @param _address Address of the account to check. * @return _exists Whether or not the account exists. */ function _hasAccount( address _address ) internal returns ( bool _exists ) { _checkAccountLoad(_address); return ovmStateManager.hasAccount(_address); } /** * Checks whether a known empty account exists within the OVM_StateManager. * @param _address Address of the account to check. * @return _exists Whether or not the account empty exists. */ function _hasEmptyAccount( address _address ) internal returns ( bool _exists ) { _checkAccountLoad(_address); return ovmStateManager.hasEmptyAccount(_address); } /** * Sets the nonce of an account. * @param _address Address of the account to modify. * @param _nonce New account nonce. */ function _setAccountNonce( address _address, uint256 _nonce ) internal { _checkAccountChange(_address); ovmStateManager.setAccountNonce(_address, _nonce); } /** * Gets the nonce of an account. * @param _address Address of the account to access. * @return _nonce Nonce of the account. */ function _getAccountNonce( address _address ) internal returns ( uint256 _nonce ) { _checkAccountLoad(_address); return ovmStateManager.getAccountNonce(_address); } /** * Retrieves the Ethereum address of an account. * @param _address Address of the account to access. * @return _ethAddress Corresponding Ethereum address. */ function _getAccountEthAddress( address _address ) internal returns ( address _ethAddress ) { _checkAccountLoad(_address); return ovmStateManager.getAccountEthAddress(_address); } /** * Creates the default account object for the given address. * @param _address Address of the account create. */ function _initPendingAccount( address _address ) internal { // Although it seems like `_checkAccountChange` would be more appropriate here, we don't // actually consider an account "changed" until it's inserted into the state (in this case // by `_commitPendingAccount`). _checkAccountLoad(_address); ovmStateManager.initPendingAccount(_address); } /** * Stores additional relevant data for a new account, thereby "committing" it to the state. * This function is only called during `ovmCREATE` and `ovmCREATE2` after a successful contract * creation. * @param _address Address of the account to commit. * @param _ethAddress Address of the associated deployed contract. * @param _codeHash Hash of the code stored at the address. */ function _commitPendingAccount( address _address, address _ethAddress, bytes32 _codeHash ) internal { _checkAccountChange(_address); ovmStateManager.commitPendingAccount( _address, _ethAddress, _codeHash ); } /** * Retrieves the value of a storage slot. * @param _contract Address of the contract to query. * @param _key 32 byte key of the storage slot. * @return _value 32 byte storage slot value. */ function _getContractStorage( address _contract, bytes32 _key ) internal returns ( bytes32 _value ) { _checkContractStorageLoad(_contract, _key); return ovmStateManager.getContractStorage(_contract, _key); } /** * Sets the value of a storage slot. * @param _contract Address of the contract to modify. * @param _key 32 byte key of the storage slot. * @param _value 32 byte storage slot value. */ function _putContractStorage( address _contract, bytes32 _key, bytes32 _value ) internal { // We don't set storage if the value didn't change. Although this acts as a convenient // optimization, it's also necessary to avoid the case in which a contract with no storage // attempts to store the value "0" at any key. Putting this value (and therefore requiring // that the value be committed into the storage trie after execution) would incorrectly // modify the storage root. if (_getContractStorage(_contract, _key) == _value) { return; } _checkContractStorageChange(_contract, _key); ovmStateManager.putContractStorage(_contract, _key, _value); } /** * Validation whenever a contract needs to be loaded. Checks that the account exists, charges * nuisance gas if the account hasn't been loaded before. * @param _address Address of the account to load. */ function _checkAccountLoad( address _address ) internal { // See `_checkContractStorageLoad` for more information. if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } // See `_checkContractStorageLoad` for more information. if (ovmStateManager.hasAccount(_address) == false) { _revertWithFlag(RevertFlag.INVALID_STATE_ACCESS); } // Check whether the account has been loaded before and mark it as loaded if not. We need // this because "nuisance gas" only applies to the first time that an account is loaded. ( bool _wasAccountAlreadyLoaded ) = ovmStateManager.testAndSetAccountLoaded(_address); // If we hadn't already loaded the account, then we'll need to charge "nuisance gas" based // on the size of the contract code. if (_wasAccountAlreadyLoaded == false) { _useNuisanceGas( (Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address)) * NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT ); } } /** * Validation whenever a contract needs to be changed. Checks that the account exists, charges * nuisance gas if the account hasn't been changed before. * @param _address Address of the account to change. */ function _checkAccountChange( address _address ) internal { // Start by checking for a load as we only want to charge nuisance gas proportional to // contract size once. _checkAccountLoad(_address); // Check whether the account has been changed before and mark it as changed if not. We need // this because "nuisance gas" only applies to the first time that an account is changed. ( bool _wasAccountAlreadyChanged ) = ovmStateManager.testAndSetAccountChanged(_address); // If we hadn't already loaded the account, then we'll need to charge "nuisance gas" based // on the size of the contract code. if (_wasAccountAlreadyChanged == false) { ovmStateManager.incrementTotalUncommittedAccounts(); _useNuisanceGas( (Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address)) * NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT ); } } /** * Validation whenever a slot needs to be loaded. Checks that the account exists, charges * nuisance gas if the slot hasn't been loaded before. * @param _contract Address of the account to load from. * @param _key 32 byte key to load. */ function _checkContractStorageLoad( address _contract, bytes32 _key ) internal { // Another case of hidden complexity. If we didn't enforce this requirement, then a // contract could pass in just enough gas to cause the INVALID_STATE_ACCESS check to fail // on L1 but not on L2. A contract could use this behavior to prevent the // OVM_ExecutionManager from detecting an invalid state access. Reverting with OUT_OF_GAS // allows us to also charge for the full message nuisance gas, because you deserve that for // trying to break the contract in this way. if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } // We need to make sure that the transaction isn't trying to access storage that hasn't // been provided to the OVM_StateManager. We'll immediately abort if this is the case. // We know that we have enough gas to do this check because of the above test. if (ovmStateManager.hasContractStorage(_contract, _key) == false) { _revertWithFlag(RevertFlag.INVALID_STATE_ACCESS); } // Check whether the slot has been loaded before and mark it as loaded if not. We need // this because "nuisance gas" only applies to the first time that a slot is loaded. ( bool _wasContractStorageAlreadyLoaded ) = ovmStateManager.testAndSetContractStorageLoaded(_contract, _key); // If we hadn't already loaded the account, then we'll need to charge some fixed amount of // "nuisance gas". if (_wasContractStorageAlreadyLoaded == false) { _useNuisanceGas(NUISANCE_GAS_SLOAD); } } /** * Validation whenever a slot needs to be changed. Checks that the account exists, charges * nuisance gas if the slot hasn't been changed before. * @param _contract Address of the account to change. * @param _key 32 byte key to change. */ function _checkContractStorageChange( address _contract, bytes32 _key ) internal { // Start by checking for load to make sure we have the storage slot and that we charge the // "nuisance gas" necessary to prove the storage slot state. _checkContractStorageLoad(_contract, _key); // Check whether the slot has been changed before and mark it as changed if not. We need // this because "nuisance gas" only applies to the first time that a slot is changed. ( bool _wasContractStorageAlreadyChanged ) = ovmStateManager.testAndSetContractStorageChanged(_contract, _key); // If we hadn't already changed the account, then we'll need to charge some fixed amount of // "nuisance gas". if (_wasContractStorageAlreadyChanged == false) { // Changing a storage slot means that we're also going to have to change the // corresponding account, so do an account change check. _checkAccountChange(_contract); ovmStateManager.incrementTotalUncommittedContractStorage(); _useNuisanceGas(NUISANCE_GAS_SSTORE); } } /************************************ * Internal Functions: Revert Logic * ************************************/ /** * Simple encoding for revert data. * @param _flag Flag to revert with. * @param _data Additional user-provided revert data. * @return _revertdata Encoded revert data. */ function _encodeRevertData( RevertFlag _flag, bytes memory _data ) internal view returns ( bytes memory _revertdata ) { // Out of gas and create exceptions will fundamentally return no data, so simulating it // shouldn't either. if ( _flag == RevertFlag.OUT_OF_GAS ) { return bytes(""); } // INVALID_STATE_ACCESS doesn't need to return any data other than the flag. if (_flag == RevertFlag.INVALID_STATE_ACCESS) { return abi.encode( _flag, 0, 0, bytes("") ); } // Just ABI encode the rest of the parameters. return abi.encode( _flag, messageRecord.nuisanceGasLeft, transactionRecord.ovmGasRefund, _data ); } /** * Simple decoding for revert data. * @param _revertdata Revert data to decode. * @return _flag Flag used to revert. * @return _nuisanceGasLeft Amount of nuisance gas unused by the message. * @return _ovmGasRefund Amount of gas refunded during the message. * @return _data Additional user-provided revert data. */ function _decodeRevertData( bytes memory _revertdata ) internal pure returns ( RevertFlag _flag, uint256 _nuisanceGasLeft, uint256 _ovmGasRefund, bytes memory _data ) { // A length of zero means the call ran out of gas, just return empty data. if (_revertdata.length == 0) { return ( RevertFlag.OUT_OF_GAS, 0, 0, bytes("") ); } // ABI decode the incoming data. return abi.decode(_revertdata, (RevertFlag, uint256, uint256, bytes)); } /** * Causes a message to revert or abort. * @param _flag Flag to revert with. * @param _data Additional user-provided data. */ function _revertWithFlag( RevertFlag _flag, bytes memory _data ) internal view { bytes memory revertdata = _encodeRevertData( _flag, _data ); assembly { revert(add(revertdata, 0x20), mload(revertdata)) } } /** * Causes a message to revert or abort. * @param _flag Flag to revert with. */ function _revertWithFlag( RevertFlag _flag ) internal { _revertWithFlag(_flag, bytes("")); } /****************************************** * Internal Functions: Nuisance Gas Logic * ******************************************/ /** * Computes the nuisance gas limit from the gas limit. * @dev This function is currently using a naive implementation whereby the nuisance gas limit * is set to exactly equal the lesser of the gas limit or remaining gas. It's likely that * this implementation is perfectly fine, but we may change this formula later. * @param _gasLimit Gas limit to compute from. * @return _nuisanceGasLimit Computed nuisance gas limit. */ function _getNuisanceGasLimit( uint256 _gasLimit ) internal view returns ( uint256 _nuisanceGasLimit ) { return _gasLimit < gasleft() ? _gasLimit : gasleft(); } /** * Uses a certain amount of nuisance gas. * @param _amount Amount of nuisance gas to use. */ function _useNuisanceGas( uint256 _amount ) internal { // Essentially the same as a standard OUT_OF_GAS, except we also retain a record of the gas // refund to be given at the end of the transaction. if (messageRecord.nuisanceGasLeft < _amount) { _revertWithFlag(RevertFlag.EXCEEDS_NUISANCE_GAS); } messageRecord.nuisanceGasLeft -= _amount; } /************************************ * Internal Functions: Gas Metering * ************************************/ /** * Checks whether a transaction needs to start a new epoch and does so if necessary. * @param _timestamp Transaction timestamp. */ function _checkNeedsNewEpoch( uint256 _timestamp ) internal { if ( _timestamp >= ( _getGasMetadata(GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP) + gasMeterConfig.secondsPerEpoch ) ) { _putGasMetadata( GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP, _timestamp ); _putGasMetadata( GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS, _getGasMetadata( GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS ) ); _putGasMetadata( GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS, _getGasMetadata( GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS ) ); } } /** * Validates the input values of a transaction. * @return _valid Whether or not the transaction data is valid. */ function _isValidInput( Lib_OVMCodec.Transaction memory _transaction ) view internal returns ( bool ) { // Prevent reentrancy to run(): // This check prevents calling run with the default ovmNumber. // Combined with the first check in run(): // if (transactionContext.ovmNUMBER != DEFAULT_UINT256) { return; } // It should be impossible to re-enter since run() returns before any other call frames are // created. Since this value is already being written to storage, we save much gas compared // to using the standard nonReentrant pattern. if (_transaction.blockNumber == DEFAULT_UINT256) { return false; } if (_isValidGasLimit(_transaction.gasLimit, _transaction.l1QueueOrigin) == false) { return false; } return true; } /** * Validates the gas limit for a given transaction. * @param _gasLimit Gas limit provided by the transaction. * param _queueOrigin Queue from which the transaction originated. * @return _valid Whether or not the gas limit is valid. */ function _isValidGasLimit( uint256 _gasLimit, Lib_OVMCodec.QueueOrigin // _queueOrigin ) view internal returns ( bool _valid ) { // Always have to be below the maximum gas limit. if (_gasLimit > gasMeterConfig.maxTransactionGasLimit) { return false; } // Always have to be above the minimum gas limit. if (_gasLimit < gasMeterConfig.minTransactionGasLimit) { return false; } // TEMPORARY: Gas metering is disabled for minnet. return true; // GasMetadataKey cumulativeGasKey; // GasMetadataKey prevEpochGasKey; // if (_queueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE) { // cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS; // prevEpochGasKey = GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS; // } else { // cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS; // prevEpochGasKey = GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS; // } // return ( // ( // _getGasMetadata(cumulativeGasKey) // - _getGasMetadata(prevEpochGasKey) // + _gasLimit // ) < gasMeterConfig.maxGasPerQueuePerEpoch // ); } /** * Updates the cumulative gas after a transaction. * @param _gasUsed Gas used by the transaction. * @param _queueOrigin Queue from which the transaction originated. */ function _updateCumulativeGas( uint256 _gasUsed, Lib_OVMCodec.QueueOrigin _queueOrigin ) internal { GasMetadataKey cumulativeGasKey; if (_queueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE) { cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS; } else { cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS; } _putGasMetadata( cumulativeGasKey, ( _getGasMetadata(cumulativeGasKey) + gasMeterConfig.minTransactionGasLimit + _gasUsed - transactionRecord.ovmGasRefund ) ); } /** * Retrieves the value of a gas metadata key. * @param _key Gas metadata key to retrieve. * @return _value Value stored at the given key. */ function _getGasMetadata( GasMetadataKey _key ) internal returns ( uint256 _value ) { return uint256(_getContractStorage( GAS_METADATA_ADDRESS, bytes32(uint256(_key)) )); } /** * Sets the value of a gas metadata key. * @param _key Gas metadata key to set. * @param _value Value to store at the given key. */ function _putGasMetadata( GasMetadataKey _key, uint256 _value ) internal { _putContractStorage( GAS_METADATA_ADDRESS, bytes32(uint256(_key)), bytes32(uint256(_value)) ); } /***************************************** * Internal Functions: Execution Context * *****************************************/ /** * Swaps over to a new message context. * @param _prevMessageContext Context we're switching from. * @param _nextMessageContext Context we're switching to. */ function _switchMessageContext( MessageContext memory _prevMessageContext, MessageContext memory _nextMessageContext ) internal { // These conditionals allow us to avoid unneccessary SSTOREs. However, they do mean that // the current storage value for the messageContext MUST equal the _prevMessageContext // argument, or an SSTORE might be erroneously skipped. if (_prevMessageContext.ovmCALLER != _nextMessageContext.ovmCALLER) { messageContext.ovmCALLER = _nextMessageContext.ovmCALLER; } if (_prevMessageContext.ovmADDRESS != _nextMessageContext.ovmADDRESS) { messageContext.ovmADDRESS = _nextMessageContext.ovmADDRESS; } if (_prevMessageContext.isStatic != _nextMessageContext.isStatic) { messageContext.isStatic = _nextMessageContext.isStatic; } if (_prevMessageContext.ovmCALLVALUE != _nextMessageContext.ovmCALLVALUE) { messageContext.ovmCALLVALUE = _nextMessageContext.ovmCALLVALUE; } } /** * Initializes the execution context. * @param _transaction OVM transaction being executed. */ function _initContext( Lib_OVMCodec.Transaction memory _transaction ) internal { transactionContext.ovmTIMESTAMP = _transaction.timestamp; transactionContext.ovmNUMBER = _transaction.blockNumber; transactionContext.ovmTXGASLIMIT = _transaction.gasLimit; transactionContext.ovmL1QUEUEORIGIN = _transaction.l1QueueOrigin; transactionContext.ovmL1TXORIGIN = _transaction.l1TxOrigin; transactionContext.ovmGASLIMIT = gasMeterConfig.maxGasPerQueuePerEpoch; messageRecord.nuisanceGasLeft = _getNuisanceGasLimit(_transaction.gasLimit); } /** * Resets the transaction and message context. */ function _resetContext() internal { transactionContext.ovmL1TXORIGIN = DEFAULT_ADDRESS; transactionContext.ovmTIMESTAMP = DEFAULT_UINT256; transactionContext.ovmNUMBER = DEFAULT_UINT256; transactionContext.ovmGASLIMIT = DEFAULT_UINT256; transactionContext.ovmTXGASLIMIT = DEFAULT_UINT256; transactionContext.ovmL1QUEUEORIGIN = Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE; transactionRecord.ovmGasRefund = DEFAULT_UINT256; messageContext.ovmCALLER = DEFAULT_ADDRESS; messageContext.ovmADDRESS = DEFAULT_ADDRESS; messageContext.isStatic = false; messageRecord.nuisanceGasLeft = DEFAULT_UINT256; // Reset the ovmStateManager. ovmStateManager = iOVM_StateManager(address(0)); } /****************************************** * Internal Functions: Message Typechecks * ******************************************/ /** * Returns whether or not the given message type is a CREATE-type. * @param _messageType the message type in question. */ function _isCreateType( MessageType _messageType ) internal pure returns( bool ) { return ( _messageType == MessageType.ovmCREATE || _messageType == MessageType.ovmCREATE2 ); } /** * Returns whether or not the given message type (potentially) requires the transfer of ETH * value along with the message. * @param _messageType the message type in question. */ function _isValueType( MessageType _messageType ) internal pure returns( bool ) { // ovmSTATICCALL and ovmDELEGATECALL types do not accept or transfer value. return ( _messageType == MessageType.ovmCALL || _messageType == MessageType.ovmCREATE || _messageType == MessageType.ovmCREATE2 ); } /***************************** * L2-only Helper Functions * *****************************/ /** * Unreachable helper function for simulating eth_calls with an OVM message context. * This function will throw an exception in all cases other than when used as a custom * entrypoint in L2 Geth to simulate eth_call. * @param _transaction the message transaction to simulate. * @param _from the OVM account the simulated call should be from. * @param _value the amount of ETH value to send. * @param _ovmStateManager the address of the OVM_StateManager precompile in the L2 state. */ function simulateMessage( Lib_OVMCodec.Transaction memory _transaction, address _from, uint256 _value, iOVM_StateManager _ovmStateManager ) external returns ( bytes memory ) { // Prevent this call from having any effect unless in a custom-set VM frame require(msg.sender == address(0)); // Initialize the EM's internal state, ignoring nuisance gas. ovmStateManager = _ovmStateManager; _initContext(_transaction); messageRecord.nuisanceGasLeft = uint(-1); // Set the ovmADDRESS to the _from so that the subsequent call frame "comes from" them. messageContext.ovmADDRESS = _from; // Execute the desired message. bool isCreate = _transaction.entrypoint == address(0); if (isCreate) { (address created, bytes memory revertData) = ovmCREATE(_transaction.data); if (created == address(0)) { return abi.encode(false, revertData); } else { // The eth_call RPC endpoint for to = undefined will return the deployed bytecode // in the success case, differing from standard create messages. return abi.encode(true, Lib_EthUtils.getCode(created)); } } else { (bool success, bytes memory returndata) = ovmCALL( _transaction.gasLimit, _transaction.entrypoint, _value, _transaction.data ); return abi.encode(success, returndata); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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.5.0 <0.8.0; /** * @title iOVM_SafetyChecker */ interface iOVM_SafetyChecker { /******************** * Public Functions * ********************/ function isBytecodeSafe(bytes calldata _bytecode) external pure returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_DeployerWhitelist } from "../../iOVM/predeploys/iOVM_DeployerWhitelist.sol"; /** * @title OVM_DeployerWhitelist * @dev The Deployer Whitelist is a temporary predeploy used to provide additional safety during the * initial phases of our mainnet roll out. It is owned by the Optimism team, and defines accounts * which are allowed to deploy contracts on Layer2. The Execution Manager will only allow an * ovmCREATE or ovmCREATE2 operation to proceed if the deployer's address whitelisted. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_DeployerWhitelist is iOVM_DeployerWhitelist { /********************** * Contract Constants * **********************/ bool public initialized; bool public allowArbitraryDeployment; address override public owner; mapping (address => bool) public whitelist; /********************** * Function Modifiers * **********************/ /** * Blocks functions to anyone except the contract owner. */ modifier onlyOwner() { require( msg.sender == owner, "Function can only be called by the owner of this contract." ); _; } /******************** * Public Functions * ********************/ /** * Initializes the whitelist. * @param _owner Address of the owner for this contract. * @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment. */ function initialize( address _owner, bool _allowArbitraryDeployment ) override external { if (initialized == true) { return; } initialized = true; allowArbitraryDeployment = _allowArbitraryDeployment; owner = _owner; } /** * Adds or removes an address from the deployment whitelist. * @param _deployer Address to update permissions for. * @param _isWhitelisted Whether or not the address is whitelisted. */ function setWhitelistedDeployer( address _deployer, bool _isWhitelisted ) override external onlyOwner { whitelist[_deployer] = _isWhitelisted; } /** * Updates the owner of this contract. * @param _owner Address of the new owner. */ function setOwner( address _owner ) override public onlyOwner { owner = _owner; } /** * Updates the arbitrary deployment flag. * @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment. */ function setAllowArbitraryDeployment( bool _allowArbitraryDeployment ) override public onlyOwner { allowArbitraryDeployment = _allowArbitraryDeployment; } /** * Permanently enables arbitrary contract deployment and deletes the owner. */ function enableArbitraryContractDeployment() override external onlyOwner { setAllowArbitraryDeployment(true); setOwner(address(0)); } /** * Checks whether an address is allowed to deploy contracts. * @param _deployer Address to check. * @return _allowed Whether or not the address can deploy contracts. */ function isDeployerAllowed( address _deployer ) override external returns ( bool ) { return ( initialized == false || allowArbitraryDeployment == true || whitelist[_deployer] ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_DeployerWhitelist */ interface iOVM_DeployerWhitelist { /******************** * Public Functions * ********************/ function initialize(address _owner, bool _allowArbitraryDeployment) external; function owner() external returns (address _owner); function setWhitelistedDeployer(address _deployer, bool _isWhitelisted) external; function setOwner(address _newOwner) external; function setAllowArbitraryDeployment(bool _allowArbitraryDeployment) external; function enableArbitraryContractDeployment() external; function isDeployerAllowed(address _deployer) external returns (bool _allowed); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_SafetyChecker } from "../../iOVM/execution/iOVM_SafetyChecker.sol"; /** * @title OVM_SafetyChecker * @dev The Safety Checker verifies that contracts deployed on L2 do not contain any * "unsafe" operations. An operation is considered unsafe if it would access state variables which * are specific to the environment (ie. L1 or L2) in which it is executed, as this could be used * to "escape the sandbox" of the OVM, resulting in non-deterministic fraud proofs. * That is, an attacker would be able to "prove fraud" on an honestly applied transaction. * Note that a "safe" contract requires opcodes to appear in a particular pattern; * omission of "unsafe" opcodes is necessary, but not sufficient. * * Compiler used: solc * Runtime target: EVM */ contract OVM_SafetyChecker is iOVM_SafetyChecker { /******************** * Public Functions * ********************/ /** * Returns whether or not all of the provided bytecode is safe. * @param _bytecode The bytecode to safety check. * @return `true` if the bytecode is safe, `false` otherwise. */ function isBytecodeSafe( bytes memory _bytecode ) override external pure returns ( bool ) { // autogenerated by gen_safety_checker_constants.py // number of bytes to skip for each opcode uint256[8] memory opcodeSkippableBytes = [ uint256(0x0001010101010101010101010000000001010101010101010101010101010000), uint256(0x0100000000000000000000000000000000000000010101010101000000010100), uint256(0x0000000000000000000000000000000001010101000000010101010100000000), uint256(0x0203040500000000000000000000000000000000000000000000000000000000), uint256(0x0101010101010101010101010101010101010101010101010101010101010101), uint256(0x0101010101000000000000000000000000000000000000000000000000000000), uint256(0x0000000000000000000000000000000000000000000000000000000000000000), uint256(0x0000000000000000000000000000000000000000000000000000000000000000) ]; // Mask to gate opcode specific cases // solhint-disable-next-line max-line-length uint256 opcodeGateMask = ~uint256(0xffffffffffffffffffffffe000000000fffffffff070ffff9c0ffffec000f001); // Halting opcodes // solhint-disable-next-line max-line-length uint256 opcodeHaltingMask = ~uint256(0x4008000000000000000000000000000000000000004000000000000000000001); // PUSH opcodes uint256 opcodePushMask = ~uint256(0xffffffff000000000000000000000000); uint256 codeLength; uint256 _pc; assembly { _pc := add(_bytecode, 0x20) } codeLength = _pc + _bytecode.length; do { // current opcode: 0x00...0xff uint256 opNum; /* solhint-disable max-line-length */ // inline assembly removes the extra add + bounds check assembly { let word := mload(_pc) //load the next 32 bytes at pc into word // Look up number of bytes to skip from opcodeSkippableBytes and then update indexInWord // E.g. the 02030405 in opcodeSkippableBytes is the number of bytes to skip for PUSH1->4 // We repeat this 6 times, thus we can only skip bytes for up to PUSH4 ((1+4) * 6 = 30 < 32). // If we see an opcode that is listed as 0 skippable bytes e.g. PUSH5, // then we will get stuck on that indexInWord and then opNum will be set to the PUSH5 opcode. let indexInWord := byte(0, mload(add(opcodeSkippableBytes, byte(0, word)))) indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word))))) indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word))))) indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word))))) indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word))))) indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word))))) _pc := add(_pc, indexInWord) opNum := byte(indexInWord, word) } /* solhint-enable max-line-length */ // + push opcodes // + stop opcodes [STOP(0x00),JUMP(0x56),RETURN(0xf3),INVALID(0xfe)] // + caller opcode CALLER(0x33) // + blacklisted opcodes uint256 opBit = 1 << opNum; if (opBit & opcodeGateMask == 0) { if (opBit & opcodePushMask == 0) { // all pushes are valid opcodes // subsequent bytes are not opcodes. Skip them. _pc += (opNum - 0x5e); // PUSH1 is 0x60, so opNum-0x5f = PUSHed bytes and we // +1 to skip the _pc++; line below in order to save gas ((-0x5f + 1) = -0x5e) continue; } else if (opBit & opcodeHaltingMask == 0) { // STOP or JUMP or RETURN or INVALID (Note: REVERT is blacklisted, so not // included here) // We are now inside unreachable code until we hit a JUMPDEST! do { _pc++; assembly { opNum := byte(0, mload(_pc)) } // encountered a JUMPDEST if (opNum == 0x5b) break; // skip PUSHed bytes // opNum-0x5f = PUSHed bytes (PUSH1 is 0x60) if ((1 << opNum) & opcodePushMask == 0) _pc += (opNum - 0x5f); } while (_pc < codeLength); // opNum is 0x5b, so we don't continue here since the pc++ is fine } else if (opNum == 0x33) { // Caller opcode uint256 firstOps; // next 32 bytes of bytecode uint256 secondOps; // following 32 bytes of bytecode assembly { firstOps := mload(_pc) // 37 bytes total, 5 left over --> 32 - 5 bytes = 27 bytes = 216 bits secondOps := shr(216, mload(add(_pc, 0x20))) } // Call identity precompile // CALLER POP PUSH1 0x00 PUSH1 0x04 GAS CALL // 32 - 8 bytes = 24 bytes = 192 if ((firstOps >> 192) == 0x3350600060045af1) { _pc += 8; // Call EM and abort execution if instructed // CALLER PUSH1 0x00 SWAP1 GAS CALL PC PUSH1 0x0E ADD JUMPI RETURNDATASIZE // PUSH1 0x00 DUP1 RETURNDATACOPY RETURNDATASIZE PUSH1 0x00 REVERT JUMPDEST // RETURNDATASIZE PUSH1 0x01 EQ ISZERO PC PUSH1 0x0a ADD JUMPI PUSH1 0x01 PUSH1 // 0x00 RETURN JUMPDEST // solhint-disable-next-line max-line-length } else if (firstOps == 0x336000905af158600e01573d6000803e3d6000fd5b3d6001141558600a015760 && secondOps == 0x016000f35b) { _pc += 37; } else { return false; } continue; } else { // encountered a non-whitelisted opcode! return false; } } _pc++; } while (_pc < codeLength); return true; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol"; import { iOVM_StateManagerFactory } from "../../iOVM/execution/iOVM_StateManagerFactory.sol"; /* Contract Imports */ import { OVM_StateManager } from "./OVM_StateManager.sol"; /** * @title OVM_StateManagerFactory * @dev The State Manager Factory is called by a State Transitioner's init code, to create a new * State Manager for use in the Fraud Verification process. * * Compiler used: solc * Runtime target: EVM */ contract OVM_StateManagerFactory is iOVM_StateManagerFactory { /******************** * Public Functions * ********************/ /** * Creates a new OVM_StateManager * @param _owner Owner of the created contract. * @return New OVM_StateManager instance. */ function create( address _owner ) override public returns ( iOVM_StateManager ) { return new OVM_StateManager(_owner); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /* Interface Imports */ import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol"; /** * @title OVM_StateManager * @dev The State Manager contract holds all storage values for contracts in the OVM. It can only be * written to by the Execution Manager and State Transitioner. It runs on L1 during the setup and * execution of a fraud proof. * The same logic runs on L2, but has been implemented as a precompile in the L2 go-ethereum client * (see https://github.com/ethereum-optimism/go-ethereum/blob/master/core/vm/ovm_state_manager.go). * * Compiler used: solc * Runtime target: EVM */ contract OVM_StateManager is iOVM_StateManager { /************* * Constants * *************/ bytes32 constant internal EMPTY_ACCOUNT_STORAGE_ROOT = 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421; bytes32 constant internal EMPTY_ACCOUNT_CODE_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; bytes32 constant internal STORAGE_XOR_VALUE = 0xFEEDFACECAFEBEEFFEEDFACECAFEBEEFFEEDFACECAFEBEEFFEEDFACECAFEBEEF; /************* * Variables * *************/ address override public owner; address override public ovmExecutionManager; mapping (address => Lib_OVMCodec.Account) internal accounts; mapping (address => mapping (bytes32 => bytes32)) internal contractStorage; mapping (address => mapping (bytes32 => bool)) internal verifiedContractStorage; mapping (bytes32 => ItemState) internal itemStates; uint256 internal totalUncommittedAccounts; uint256 internal totalUncommittedContractStorage; /*************** * Constructor * ***************/ /** * @param _owner Address of the owner of this contract. */ constructor( address _owner ) { owner = _owner; } /********************** * Function Modifiers * **********************/ /** * Simple authentication, this contract should only be accessible to the owner * (which is expected to be the State Transitioner during `PRE_EXECUTION` * or the OVM_ExecutionManager during transaction execution. */ modifier authenticated() { // owner is the State Transitioner require( msg.sender == owner || msg.sender == ovmExecutionManager, "Function can only be called by authenticated addresses" ); _; } /******************** * Public Functions * ********************/ /** * Checks whether a given address is allowed to modify this contract. * @param _address Address to check. * @return Whether or not the address can modify this contract. */ function isAuthenticated( address _address ) override public view returns ( bool ) { return (_address == owner || _address == ovmExecutionManager); } /** * Sets the address of the OVM_ExecutionManager. * @param _ovmExecutionManager Address of the OVM_ExecutionManager. */ function setExecutionManager( address _ovmExecutionManager ) override public authenticated { ovmExecutionManager = _ovmExecutionManager; } /** * Inserts an account into the state. * @param _address Address of the account to insert. * @param _account Account to insert for the given address. */ function putAccount( address _address, Lib_OVMCodec.Account memory _account ) override public authenticated { accounts[_address] = _account; } /** * Marks an account as empty. * @param _address Address of the account to mark. */ function putEmptyAccount( address _address ) override public authenticated { Lib_OVMCodec.Account storage account = accounts[_address]; account.storageRoot = EMPTY_ACCOUNT_STORAGE_ROOT; account.codeHash = EMPTY_ACCOUNT_CODE_HASH; } /** * Retrieves an account from the state. * @param _address Address of the account to retrieve. * @return Account for the given address. */ function getAccount( address _address ) override public view returns ( Lib_OVMCodec.Account memory ) { return accounts[_address]; } /** * Checks whether the state has a given account. * @param _address Address of the account to check. * @return Whether or not the state has the account. */ function hasAccount( address _address ) override public view returns ( bool ) { return accounts[_address].codeHash != bytes32(0); } /** * Checks whether the state has a given known empty account. * @param _address Address of the account to check. * @return Whether or not the state has the empty account. */ function hasEmptyAccount( address _address ) override public view returns ( bool ) { return ( accounts[_address].codeHash == EMPTY_ACCOUNT_CODE_HASH && accounts[_address].nonce == 0 ); } /** * Sets the nonce of an account. * @param _address Address of the account to modify. * @param _nonce New account nonce. */ function setAccountNonce( address _address, uint256 _nonce ) override public authenticated { accounts[_address].nonce = _nonce; } /** * Gets the nonce of an account. * @param _address Address of the account to access. * @return Nonce of the account. */ function getAccountNonce( address _address ) override public view returns ( uint256 ) { return accounts[_address].nonce; } /** * Retrieves the Ethereum address of an account. * @param _address Address of the account to access. * @return Corresponding Ethereum address. */ function getAccountEthAddress( address _address ) override public view returns ( address ) { return accounts[_address].ethAddress; } /** * Retrieves the storage root of an account. * @param _address Address of the account to access. * @return Corresponding storage root. */ function getAccountStorageRoot( address _address ) override public view returns ( bytes32 ) { return accounts[_address].storageRoot; } /** * Initializes a pending account (during CREATE or CREATE2) with the default values. * @param _address Address of the account to initialize. */ function initPendingAccount( address _address ) override public authenticated { Lib_OVMCodec.Account storage account = accounts[_address]; account.nonce = 1; account.storageRoot = EMPTY_ACCOUNT_STORAGE_ROOT; account.codeHash = EMPTY_ACCOUNT_CODE_HASH; account.isFresh = true; } /** * Finalizes the creation of a pending account (during CREATE or CREATE2). * @param _address Address of the account to finalize. * @param _ethAddress Address of the account's associated contract on Ethereum. * @param _codeHash Hash of the account's code. */ function commitPendingAccount( address _address, address _ethAddress, bytes32 _codeHash ) override public authenticated { Lib_OVMCodec.Account storage account = accounts[_address]; account.ethAddress = _ethAddress; account.codeHash = _codeHash; } /** * Checks whether an account has already been retrieved, and marks it as retrieved if not. * @param _address Address of the account to check. * @return Whether or not the account was already loaded. */ function testAndSetAccountLoaded( address _address ) override public authenticated returns ( bool ) { return _testAndSetItemState( _getItemHash(_address), ItemState.ITEM_LOADED ); } /** * Checks whether an account has already been modified, and marks it as modified if not. * @param _address Address of the account to check. * @return Whether or not the account was already modified. */ function testAndSetAccountChanged( address _address ) override public authenticated returns ( bool ) { return _testAndSetItemState( _getItemHash(_address), ItemState.ITEM_CHANGED ); } /** * Attempts to mark an account as committed. * @param _address Address of the account to commit. * @return Whether or not the account was committed. */ function commitAccount( address _address ) override public authenticated returns ( bool ) { bytes32 item = _getItemHash(_address); if (itemStates[item] != ItemState.ITEM_CHANGED) { return false; } itemStates[item] = ItemState.ITEM_COMMITTED; totalUncommittedAccounts -= 1; return true; } /** * Increments the total number of uncommitted accounts. */ function incrementTotalUncommittedAccounts() override public authenticated { totalUncommittedAccounts += 1; } /** * Gets the total number of uncommitted accounts. * @return Total uncommitted accounts. */ function getTotalUncommittedAccounts() override public view returns ( uint256 ) { return totalUncommittedAccounts; } /** * Checks whether a given account was changed during execution. * @param _address Address to check. * @return Whether or not the account was changed. */ function wasAccountChanged( address _address ) override public view returns ( bool ) { bytes32 item = _getItemHash(_address); return itemStates[item] >= ItemState.ITEM_CHANGED; } /** * Checks whether a given account was committed after execution. * @param _address Address to check. * @return Whether or not the account was committed. */ function wasAccountCommitted( address _address ) override public view returns ( bool ) { bytes32 item = _getItemHash(_address); return itemStates[item] >= ItemState.ITEM_COMMITTED; } /************************************ * Public Functions: Storage Access * ************************************/ /** * Changes a contract storage slot value. * @param _contract Address of the contract to modify. * @param _key 32 byte storage slot key. * @param _value 32 byte storage slot value. */ function putContractStorage( address _contract, bytes32 _key, bytes32 _value ) override public authenticated { // A hilarious optimization. `SSTORE`ing a value of `bytes32(0)` is common enough that it's // worth populating this with a non-zero value in advance (during the fraud proof // initialization phase) to cut the execution-time cost down to 5000 gas. contractStorage[_contract][_key] = _value ^ STORAGE_XOR_VALUE; // Only used when initially populating the contract storage. OVM_ExecutionManager will // perform a `hasContractStorage` INVALID_STATE_ACCESS check before putting any contract // storage because writing to zero when the actual value is nonzero causes a gas // discrepancy. Could be moved into a new `putVerifiedContractStorage` function, or // something along those lines. if (verifiedContractStorage[_contract][_key] == false) { verifiedContractStorage[_contract][_key] = true; } } /** * Retrieves a contract storage slot value. * @param _contract Address of the contract to access. * @param _key 32 byte storage slot key. * @return 32 byte storage slot value. */ function getContractStorage( address _contract, bytes32 _key ) override public view returns ( bytes32 ) { // Storage XOR system doesn't work for newly created contracts that haven't set this // storage slot value yet. if ( verifiedContractStorage[_contract][_key] == false && accounts[_contract].isFresh ) { return bytes32(0); } // See `putContractStorage` for more information about the XOR here. return contractStorage[_contract][_key] ^ STORAGE_XOR_VALUE; } /** * Checks whether a contract storage slot exists in the state. * @param _contract Address of the contract to access. * @param _key 32 byte storage slot key. * @return Whether or not the key was set in the state. */ function hasContractStorage( address _contract, bytes32 _key ) override public view returns ( bool ) { return verifiedContractStorage[_contract][_key] || accounts[_contract].isFresh; } /** * Checks whether a storage slot has already been retrieved, and marks it as retrieved if not. * @param _contract Address of the contract to check. * @param _key 32 byte storage slot key. * @return Whether or not the slot was already loaded. */ function testAndSetContractStorageLoaded( address _contract, bytes32 _key ) override public authenticated returns ( bool ) { return _testAndSetItemState( _getItemHash(_contract, _key), ItemState.ITEM_LOADED ); } /** * Checks whether a storage slot has already been modified, and marks it as modified if not. * @param _contract Address of the contract to check. * @param _key 32 byte storage slot key. * @return Whether or not the slot was already modified. */ function testAndSetContractStorageChanged( address _contract, bytes32 _key ) override public authenticated returns ( bool ) { return _testAndSetItemState( _getItemHash(_contract, _key), ItemState.ITEM_CHANGED ); } /** * Attempts to mark a storage slot as committed. * @param _contract Address of the account to commit. * @param _key 32 byte slot key to commit. * @return Whether or not the slot was committed. */ function commitContractStorage( address _contract, bytes32 _key ) override public authenticated returns ( bool ) { bytes32 item = _getItemHash(_contract, _key); if (itemStates[item] != ItemState.ITEM_CHANGED) { return false; } itemStates[item] = ItemState.ITEM_COMMITTED; totalUncommittedContractStorage -= 1; return true; } /** * Increments the total number of uncommitted storage slots. */ function incrementTotalUncommittedContractStorage() override public authenticated { totalUncommittedContractStorage += 1; } /** * Gets the total number of uncommitted storage slots. * @return Total uncommitted storage slots. */ function getTotalUncommittedContractStorage() override public view returns ( uint256 ) { return totalUncommittedContractStorage; } /** * Checks whether a given storage slot was changed during execution. * @param _contract Address to check. * @param _key Key of the storage slot to check. * @return Whether or not the storage slot was changed. */ function wasContractStorageChanged( address _contract, bytes32 _key ) override public view returns ( bool ) { bytes32 item = _getItemHash(_contract, _key); return itemStates[item] >= ItemState.ITEM_CHANGED; } /** * Checks whether a given storage slot was committed after execution. * @param _contract Address to check. * @param _key Key of the storage slot to check. * @return Whether or not the storage slot was committed. */ function wasContractStorageCommitted( address _contract, bytes32 _key ) override public view returns ( bool ) { bytes32 item = _getItemHash(_contract, _key); return itemStates[item] >= ItemState.ITEM_COMMITTED; } /********************** * Internal Functions * **********************/ /** * Generates a unique hash for an address. * @param _address Address to generate a hash for. * @return Unique hash for the given address. */ function _getItemHash( address _address ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_address)); } /** * Generates a unique hash for an address/key pair. * @param _contract Address to generate a hash for. * @param _key Key to generate a hash for. * @return Unique hash for the given pair. */ function _getItemHash( address _contract, bytes32 _key ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked( _contract, _key )); } /** * Checks whether an item is in a particular state (ITEM_LOADED or ITEM_CHANGED) and sets the * item to the provided state if not. * @param _item 32 byte item ID to check. * @param _minItemState Minimum state that must be satisfied by the item. * @return Whether or not the item was already in the state. */ function _testAndSetItemState( bytes32 _item, ItemState _minItemState ) internal returns ( bool ) { bool wasItemState = itemStates[_item] >= _minItemState; if (wasItemState == false) { itemStates[_item] = _minItemState; } return wasItemState; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../optimistic-ethereum/libraries/codec/Lib_OVMCodec.sol"; /** * @title TestLib_OVMCodec */ contract TestLib_OVMCodec { function encodeTransaction( Lib_OVMCodec.Transaction memory _transaction ) public pure returns ( bytes memory _encoded ) { return Lib_OVMCodec.encodeTransaction(_transaction); } function hashTransaction( Lib_OVMCodec.Transaction memory _transaction ) public pure returns ( bytes32 _hash ) { return Lib_OVMCodec.hashTransaction(_transaction); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_OVMCodec } from "../../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressManager } from "../../../libraries/resolver/Lib_AddressManager.sol"; import { Lib_SecureMerkleTrie } from "../../../libraries/trie/Lib_SecureMerkleTrie.sol"; import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol"; import { Lib_CrossDomainUtils } from "../../../libraries/bridge/Lib_CrossDomainUtils.sol"; /* Interface Imports */ import { iOVM_L1CrossDomainMessenger } from "../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol"; import { iOVM_CanonicalTransactionChain } from "../../../iOVM/chain/iOVM_CanonicalTransactionChain.sol"; import { iOVM_StateCommitmentChain } from "../../../iOVM/chain/iOVM_StateCommitmentChain.sol"; /* External Imports */ import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { PausableUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; /** * @title OVM_L1CrossDomainMessenger * @dev The L1 Cross Domain Messenger contract sends messages from L1 to L2, and relays messages * from L2 onto L1. In the event that a message sent from L1 to L2 is rejected for exceeding the L2 * epoch gas limit, it can be resubmitted via this contract's replay function. * * Compiler used: solc * Runtime target: EVM */ contract OVM_L1CrossDomainMessenger is iOVM_L1CrossDomainMessenger, Lib_AddressResolver, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { /********** * Events * **********/ event MessageBlocked( bytes32 indexed _xDomainCalldataHash ); event MessageAllowed( bytes32 indexed _xDomainCalldataHash ); /************* * Constants * *************/ // The default x-domain message sender being set to a non-zero value makes // deployment a bit more expensive, but in exchange the refund on every call to // `relayMessage` by the L1 and L2 messengers will be higher. address internal constant DEFAULT_XDOMAIN_SENDER = 0x000000000000000000000000000000000000dEaD; /********************** * Contract Variables * **********************/ mapping (bytes32 => bool) public blockedMessages; mapping (bytes32 => bool) public relayedMessages; mapping (bytes32 => bool) public successfulMessages; address internal xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; /*************** * Constructor * ***************/ /** * This contract is intended to be behind a delegate proxy. * We pass the zero address to the address resolver just to satisfy the constructor. * We still need to set this value in initialize(). */ constructor() Lib_AddressResolver(address(0)) {} /********************** * Function Modifiers * **********************/ /** * Modifier to enforce that, if configured, only the OVM_L2MessageRelayer contract may * successfully call a method. */ modifier onlyRelayer() { address relayer = resolve("OVM_L2MessageRelayer"); if (relayer != address(0)) { require( msg.sender == relayer, "Only OVM_L2MessageRelayer can relay L2-to-L1 messages." ); } _; } /******************** * Public Functions * ********************/ /** * @param _libAddressManager Address of the Address Manager. */ function initialize( address _libAddressManager ) public initializer { require( address(libAddressManager) == address(0), "L1CrossDomainMessenger already intialized." ); libAddressManager = Lib_AddressManager(_libAddressManager); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Initialize upgradable OZ contracts __Context_init_unchained(); // Context is a dependency for both Ownable and Pausable __Ownable_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); } /** * Pause relaying. */ function pause() external onlyOwner { _pause(); } /** * Block a message. * @param _xDomainCalldataHash Hash of the message to block. */ function blockMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = true; emit MessageBlocked(_xDomainCalldataHash); } /** * Allow a message. * @param _xDomainCalldataHash Hash of the message to block. */ function allowMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = false; emit MessageAllowed(_xDomainCalldataHash); } function xDomainMessageSender() public override view returns ( address ) { require(xDomainMsgSender != DEFAULT_XDOMAIN_SENDER, "xDomainMessageSender is not set"); return xDomainMsgSender; } /** * Sends a cross domain message to the target messenger. * @param _target Target contract address. * @param _message Message to send to the target. * @param _gasLimit Gas limit for the provided message. */ function sendMessage( address _target, bytes memory _message, uint32 _gasLimit ) override public { address ovmCanonicalTransactionChain = resolve("OVM_CanonicalTransactionChain"); // Use the CTC queue length as nonce uint40 nonce = iOVM_CanonicalTransactionChain(ovmCanonicalTransactionChain).getQueueLength(); bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata( _target, msg.sender, _message, nonce ); address l2CrossDomainMessenger = resolve("OVM_L2CrossDomainMessenger"); _sendXDomainMessage( ovmCanonicalTransactionChain, l2CrossDomainMessenger, xDomainCalldata, _gasLimit ); emit SentMessage(xDomainCalldata); } /** * Relays a cross domain message to a contract. * @inheritdoc iOVM_L1CrossDomainMessenger */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) override public nonReentrant onlyRelayer whenNotPaused { bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata( _target, _sender, _message, _messageNonce ); require( _verifyXDomainMessage( xDomainCalldata, _proof ) == true, "Provided message could not be verified." ); bytes32 xDomainCalldataHash = keccak256(xDomainCalldata); require( successfulMessages[xDomainCalldataHash] == false, "Provided message has already been received." ); require( blockedMessages[xDomainCalldataHash] == false, "Provided message has been blocked." ); require( _target != resolve("OVM_CanonicalTransactionChain"), "Cannot send L2->L1 messages to L1 system contracts." ); xDomainMsgSender = _sender; (bool success, ) = _target.call(_message); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Mark the message as received if the call was successful. Ensures that a message can be // relayed multiple times in the case that the call reverted. if (success == true) { successfulMessages[xDomainCalldataHash] = true; emit RelayedMessage(xDomainCalldataHash); } else { emit FailedRelayedMessage(xDomainCalldataHash); } // Store an identifier that can be used to prove that the given message was relayed by some // user. Gives us an easy way to pay relayers for their work. bytes32 relayId = keccak256( abi.encodePacked( xDomainCalldata, msg.sender, block.number ) ); relayedMessages[relayId] = true; } /** * Replays a cross domain message to the target messenger. * @inheritdoc iOVM_L1CrossDomainMessenger */ function replayMessage( address _target, address _sender, bytes memory _message, uint256 _queueIndex, uint32 _gasLimit ) override public { // Verify that the message is in the queue: address canonicalTransactionChain = resolve("OVM_CanonicalTransactionChain"); Lib_OVMCodec.QueueElement memory element = iOVM_CanonicalTransactionChain(canonicalTransactionChain).getQueueElement(_queueIndex); address l2CrossDomainMessenger = resolve("OVM_L2CrossDomainMessenger"); // Compute the transactionHash bytes32 transactionHash = keccak256( abi.encode( address(this), l2CrossDomainMessenger, _gasLimit, _message ) ); require( transactionHash == element.transactionHash, "Provided message has not been enqueued." ); bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata( _target, _sender, _message, _queueIndex ); _sendXDomainMessage( canonicalTransactionChain, l2CrossDomainMessenger, xDomainCalldata, _gasLimit ); } /********************** * Internal Functions * **********************/ /** * Verifies that the given message is valid. * @param _xDomainCalldata Calldata to verify. * @param _proof Inclusion proof for the message. * @return Whether or not the provided message is valid. */ function _verifyXDomainMessage( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { return ( _verifyStateRootProof(_proof) && _verifyStorageProof(_xDomainCalldata, _proof) ); } /** * Verifies that the state root within an inclusion proof is valid. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStateRootProof( L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain( resolve("OVM_StateCommitmentChain") ); return ( ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false && ovmStateCommitmentChain.verifyStateCommitment( _proof.stateRoot, _proof.stateRootBatchHeader, _proof.stateRootProof ) ); } /** * Verifies that the storage proof within an inclusion proof is valid. * @param _xDomainCalldata Encoded message calldata. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStorageProof( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { bytes32 storageKey = keccak256( abi.encodePacked( keccak256( abi.encodePacked( _xDomainCalldata, resolve("OVM_L2CrossDomainMessenger") ) ), uint256(0) ) ); ( bool exists, bytes memory encodedMessagePassingAccount ) = Lib_SecureMerkleTrie.get( abi.encodePacked(Lib_PredeployAddresses.L2_TO_L1_MESSAGE_PASSER), _proof.stateTrieWitness, _proof.stateRoot ); require( exists == true, "Message passing predeploy has not been initialized or invalid proof provided." ); Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount( encodedMessagePassingAccount ); return Lib_SecureMerkleTrie.verifyInclusionProof( abi.encodePacked(storageKey), abi.encodePacked(uint8(1)), _proof.storageTrieWitness, account.storageRoot ); } /** * Sends a cross domain message. * @param _canonicalTransactionChain Address of the OVM_CanonicalTransactionChain instance. * @param _l2CrossDomainMessenger Address of the OVM_L2CrossDomainMessenger instance. * @param _message Message to send. * @param _gasLimit OVM gas limit for the message. */ function _sendXDomainMessage( address _canonicalTransactionChain, address _l2CrossDomainMessenger, bytes memory _message, uint256 _gasLimit ) internal { iOVM_CanonicalTransactionChain(_canonicalTransactionChain).enqueue( _l2CrossDomainMessenger, _gasLimit, _message ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; /** * @title Lib_CrossDomainUtils */ library Lib_CrossDomainUtils { /** * Generates the correct cross domain calldata for a message. * @param _target Target contract address. * @param _sender Message sender address. * @param _message Message to send to the target. * @param _messageNonce Nonce for the provided message. * @return ABI encoded cross domain calldata. */ function encodeXDomainCalldata( address _target, address _sender, bytes memory _message, uint256 _messageNonce ) internal pure returns ( bytes memory ) { return abi.encodeWithSignature( "relayMessage(address,address,bytes,uint256)", _target, _sender, _message, _messageNonce ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../../libraries/codec/Lib_OVMCodec.sol"; /* Interface Imports */ import { iOVM_CrossDomainMessenger } from "./iOVM_CrossDomainMessenger.sol"; /** * @title iOVM_L1CrossDomainMessenger */ interface iOVM_L1CrossDomainMessenger is iOVM_CrossDomainMessenger { /******************* * Data Structures * *******************/ struct L2MessageInclusionProof { bytes32 stateRoot; Lib_OVMCodec.ChainBatchHeader stateRootBatchHeader; Lib_OVMCodec.ChainInclusionProof stateRootProof; bytes stateTrieWitness; bytes storageTrieWitness; } /******************** * Public Functions * ********************/ /** * Relays a cross domain message to a contract. * @param _target Target contract address. * @param _sender Message sender address. * @param _message Message to send to the target. * @param _messageNonce Nonce for the provided message. * @param _proof Inclusion proof for the given message. */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) external; /** * Replays a cross domain message to the target messenger. * @param _target Target contract address. * @param _sender Original sender address. * @param _message Message to send to the target. * @param _queueIndex CTC Queue index for the message to replay. * @param _gasLimit Gas limit for the provided message. */ function replayMessage( address _target, address _sender, bytes memory _message, uint256 _queueIndex, uint32 _gasLimit ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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.6.0 <0.8.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.6.0 <0.8.0; import "../proxy/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // 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 // 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.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_L1CrossDomainMessenger } from "../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol"; import { iOVM_L1MultiMessageRelayer } from "../../../iOVM/bridge/messaging/iOVM_L1MultiMessageRelayer.sol"; /* Library Imports */ import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol"; /** * @title OVM_L1MultiMessageRelayer * @dev The L1 Multi-Message Relayer contract is a gas efficiency optimization which enables the * relayer to submit multiple messages in a single transaction to be relayed by the L1 Cross Domain * Message Sender. * * Compiler used: solc * Runtime target: EVM */ contract OVM_L1MultiMessageRelayer is iOVM_L1MultiMessageRelayer, Lib_AddressResolver { /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager ) Lib_AddressResolver(_libAddressManager) {} /********************** * Function Modifiers * **********************/ modifier onlyBatchRelayer() { require( msg.sender == resolve("OVM_L2BatchMessageRelayer"), // solhint-disable-next-line max-line-length "OVM_L1MultiMessageRelayer: Function can only be called by the OVM_L2BatchMessageRelayer" ); _; } /******************** * Public Functions * ********************/ /** * @notice Forwards multiple cross domain messages to the L1 Cross Domain Messenger for relaying * @param _messages An array of L2 to L1 messages */ function batchRelayMessages( L2ToL1Message[] calldata _messages ) override external onlyBatchRelayer { iOVM_L1CrossDomainMessenger messenger = iOVM_L1CrossDomainMessenger( resolve("Proxy__OVM_L1CrossDomainMessenger") ); for (uint256 i = 0; i < _messages.length; i++) { L2ToL1Message memory message = _messages[i]; messenger.relayMessage( message.target, message.sender, message.message, message.messageNonce, message.proof ); } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_L1CrossDomainMessenger } from "../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol"; interface iOVM_L1MultiMessageRelayer { struct L2ToL1Message { address target; address sender; bytes message; uint256 messageNonce; iOVM_L1CrossDomainMessenger.L2MessageInclusionProof proof; } function batchRelayMessages(L2ToL1Message[] calldata _messages) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_CrossDomainUtils } from "../../../libraries/bridge/Lib_CrossDomainUtils.sol"; /* Interface Imports */ import { iOVM_L2CrossDomainMessenger } from "../../../iOVM/bridge/messaging/iOVM_L2CrossDomainMessenger.sol"; import { iOVM_L1MessageSender } from "../../../iOVM/predeploys/iOVM_L1MessageSender.sol"; import { iOVM_L2ToL1MessagePasser } from "../../../iOVM/predeploys/iOVM_L2ToL1MessagePasser.sol"; /* External Imports */ import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; /* External Imports */ import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; /** * @title OVM_L2CrossDomainMessenger * @dev The L2 Cross Domain Messenger contract sends messages from L2 to L1, and is the entry point * for L2 messages sent via the L1 Cross Domain Messenger. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_L2CrossDomainMessenger is iOVM_L2CrossDomainMessenger, Lib_AddressResolver, ReentrancyGuard { /************* * Constants * *************/ // The default x-domain message sender being set to a non-zero value makes // deployment a bit more expensive, but in exchange the refund on every call to // `relayMessage` by the L1 and L2 messengers will be higher. address internal constant DEFAULT_XDOMAIN_SENDER = 0x000000000000000000000000000000000000dEaD; /************* * Variables * *************/ mapping (bytes32 => bool) public relayedMessages; mapping (bytes32 => bool) public successfulMessages; mapping (bytes32 => bool) public sentMessages; uint256 public messageNonce; address internal xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor(address _libAddressManager) Lib_AddressResolver(_libAddressManager) ReentrancyGuard() {} /******************** * Public Functions * ********************/ function xDomainMessageSender() public override view returns ( address ) { require(xDomainMsgSender != DEFAULT_XDOMAIN_SENDER, "xDomainMessageSender is not set"); return xDomainMsgSender; } /** * Sends a cross domain message to the target messenger. * @param _target Target contract address. * @param _message Message to send to the target. * @param _gasLimit Gas limit for the provided message. */ function sendMessage( address _target, bytes memory _message, uint32 _gasLimit ) override public { bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata( _target, msg.sender, _message, messageNonce ); messageNonce += 1; sentMessages[keccak256(xDomainCalldata)] = true; _sendXDomainMessage(xDomainCalldata, _gasLimit); emit SentMessage(xDomainCalldata); } /** * Relays a cross domain message to a contract. * @inheritdoc iOVM_L2CrossDomainMessenger */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce ) override nonReentrant public { require( _verifyXDomainMessage() == true, "Provided message could not be verified." ); bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata( _target, _sender, _message, _messageNonce ); bytes32 xDomainCalldataHash = keccak256(xDomainCalldata); require( successfulMessages[xDomainCalldataHash] == false, "Provided message has already been received." ); // Prevent calls to OVM_L2ToL1MessagePasser, which would enable // an attacker to maliciously craft the _message to spoof // a call from any L2 account. if(_target == resolve("OVM_L2ToL1MessagePasser")){ // Write to the successfulMessages mapping and return immediately. successfulMessages[xDomainCalldataHash] = true; return; } xDomainMsgSender = _sender; (bool success, ) = _target.call(_message); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Mark the message as received if the call was successful. Ensures that a message can be // relayed multiple times in the case that the call reverted. if (success == true) { successfulMessages[xDomainCalldataHash] = true; emit RelayedMessage(xDomainCalldataHash); } else { emit FailedRelayedMessage(xDomainCalldataHash); } // Store an identifier that can be used to prove that the given message was relayed by some // user. Gives us an easy way to pay relayers for their work. bytes32 relayId = keccak256( abi.encodePacked( xDomainCalldata, msg.sender, block.number ) ); relayedMessages[relayId] = true; } /********************** * Internal Functions * **********************/ /** * Verifies that a received cross domain message is valid. * @return _valid Whether or not the message is valid. */ function _verifyXDomainMessage() view internal returns ( bool _valid ) { return ( iOVM_L1MessageSender( resolve("OVM_L1MessageSender") ).getL1MessageSender() == resolve("OVM_L1CrossDomainMessenger") ); } /** * Sends a cross domain message. * @param _message Message to send. * param _gasLimit Gas limit for the provided message. */ function _sendXDomainMessage( bytes memory _message, uint256 // _gasLimit ) internal { iOVM_L2ToL1MessagePasser(resolve("OVM_L2ToL1MessagePasser")).passMessageToL1(_message); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_CrossDomainMessenger } from "./iOVM_CrossDomainMessenger.sol"; /** * @title iOVM_L2CrossDomainMessenger */ interface iOVM_L2CrossDomainMessenger is iOVM_CrossDomainMessenger { /******************** * Public Functions * ********************/ /** * Relays a cross domain message to a contract. * @param _target Target contract address. * @param _sender Message sender address. * @param _message Message to send to the target. * @param _messageNonce Nonce for the provided message. */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_L1MessageSender */ interface iOVM_L1MessageSender { /******************** * Public Functions * ********************/ function getL1MessageSender() external view returns (address _l1MessageSender); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_L2ToL1MessagePasser */ interface iOVM_L2ToL1MessagePasser { /********** * Events * **********/ event L2ToL1Message( uint256 _nonce, address _sender, bytes _data ); /******************** * Public Functions * ********************/ function passMessageToL1(bytes calldata _message) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_L2ToL1MessagePasser } from "../../iOVM/predeploys/iOVM_L2ToL1MessagePasser.sol"; /** * @title OVM_L2ToL1MessagePasser * @dev The L2 to L1 Message Passer is a utility contract which facilitate an L1 proof of the * of a message on L2. The L1 Cross Domain Messenger performs this proof in its * _verifyStorageProof function, which verifies the existence of the transaction hash in this * contract's `sentMessages` mapping. * * Compiler used: solc * Runtime target: EVM */ contract OVM_L2ToL1MessagePasser is iOVM_L2ToL1MessagePasser { /********************** * Contract Variables * **********************/ mapping (bytes32 => bool) public sentMessages; /******************** * Public Functions * ********************/ /** * Passes a message to L1. * @param _message Message to pass to L1. */ function passMessageToL1( bytes memory _message ) override public { // Note: although this function is public, only messages sent from the // OVM_L2CrossDomainMessenger will be relayed by the OVM_L1CrossDomainMessenger. // This is enforced by a check in OVM_L1CrossDomainMessenger._verifyStorageProof(). sentMessages[keccak256( abi.encodePacked( _message, msg.sender ) )] = true; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_L1MessageSender } from "../../iOVM/predeploys/iOVM_L1MessageSender.sol"; import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol"; /** * @title OVM_L1MessageSender * @dev The L1MessageSender is a predeploy contract running on L2. During the execution of cross * domain transaction from L1 to L2, it returns the address of the L1 account (either an EOA or * contract) which sent the message to L2 via the Canonical Transaction Chain's `enqueue()` * function. * * This contract exclusively serves as a getter for the ovmL1TXORIGIN operation. This is necessary * because there is no corresponding operation in the EVM which the the optimistic solidity compiler * can be replaced with a call to the ExecutionManager's ovmL1TXORIGIN() function. * * * Compiler used: solc * Runtime target: OVM */ contract OVM_L1MessageSender is iOVM_L1MessageSender { /******************** * Public Functions * ********************/ /** * @return _l1MessageSender L1 message sender address (msg.sender). */ function getL1MessageSender() override public view returns ( address _l1MessageSender ) { // Note that on L2 msg.sender (ie. evmCALLER) will always be the Execution Manager return iOVM_ExecutionManager(msg.sender).ovmL1TXORIGIN(); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPReader } from "../../optimistic-ethereum/libraries/rlp/Lib_RLPReader.sol"; /** * @title TestLib_RLPReader */ contract TestLib_RLPReader { function readList( bytes memory _in ) public pure returns ( bytes[] memory ) { Lib_RLPReader.RLPItem[] memory decoded = Lib_RLPReader.readList(_in); bytes[] memory out = new bytes[](decoded.length); for (uint256 i = 0; i < out.length; i++) { out[i] = Lib_RLPReader.readRawBytes(decoded[i]); } return out; } function readString( bytes memory _in ) public pure returns ( string memory ) { return Lib_RLPReader.readString(_in); } function readBytes( bytes memory _in ) public pure returns ( bytes memory ) { return Lib_RLPReader.readBytes(_in); } function readBytes32( bytes memory _in ) public pure returns ( bytes32 ) { return Lib_RLPReader.readBytes32(_in); } function readUint256( bytes memory _in ) public pure returns ( uint256 ) { return Lib_RLPReader.readUint256(_in); } function readBool( bytes memory _in ) public pure returns ( bool ) { return Lib_RLPReader.readBool(_in); } function readAddress( bytes memory _in ) public pure returns ( address ) { return Lib_RLPReader.readAddress(_in); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_MerkleTrie } from "../../optimistic-ethereum/libraries/trie/Lib_MerkleTrie.sol"; /** * @title TestLib_MerkleTrie */ contract TestLib_MerkleTrie { function verifyInclusionProof( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) public pure returns ( bool ) { return Lib_MerkleTrie.verifyInclusionProof( _key, _value, _proof, _root ); } function update( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) public pure returns ( bytes32 ) { return Lib_MerkleTrie.update( _key, _value, _proof, _root ); } function get( bytes memory _key, bytes memory _proof, bytes32 _root ) public pure returns ( bool, bytes memory ) { return Lib_MerkleTrie.get( _key, _proof, _root ); } function getSingleNodeRootHash( bytes memory _key, bytes memory _value ) public pure returns ( bytes32 ) { return Lib_MerkleTrie.getSingleNodeRootHash( _key, _value ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_SecureMerkleTrie } from "../../optimistic-ethereum/libraries/trie/Lib_SecureMerkleTrie.sol"; /** * @title TestLib_SecureMerkleTrie */ contract TestLib_SecureMerkleTrie { function verifyInclusionProof( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) public pure returns ( bool ) { return Lib_SecureMerkleTrie.verifyInclusionProof( _key, _value, _proof, _root ); } function update( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) public pure returns ( bytes32 ) { return Lib_SecureMerkleTrie.update( _key, _value, _proof, _root ); } function get( bytes memory _key, bytes memory _proof, bytes32 _root ) public pure returns ( bool, bytes memory ) { return Lib_SecureMerkleTrie.get( _key, _proof, _root ); } function getSingleNodeRootHash( bytes memory _key, bytes memory _value ) public pure returns ( bytes32 ) { return Lib_SecureMerkleTrie.getSingleNodeRootHash( _key, _value ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_AddressManager } from "./Lib_AddressManager.sol"; /** * @title Lib_ResolvedDelegateProxy */ contract Lib_ResolvedDelegateProxy { /************* * Variables * *************/ // Using mappings to store fields to avoid overwriting storage slots in the // implementation contract. For example, instead of storing these fields at // storage slot `0` & `1`, they are stored at `keccak256(key + slot)`. // See: https://solidity.readthedocs.io/en/v0.7.0/internals/layout_in_storage.html // NOTE: Do not use this code in your own contract system. // There is a known flaw in this contract, and we will remove it from the repository // in the near future. Due to the very limited way that we are using it, this flaw is // not an issue in our system. mapping (address => string) private implementationName; mapping (address => Lib_AddressManager) private addressManager; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Lib_AddressManager. * @param _implementationName implementationName of the contract to proxy to. */ constructor( address _libAddressManager, string memory _implementationName ) { addressManager[address(this)] = Lib_AddressManager(_libAddressManager); implementationName[address(this)] = _implementationName; } /********************* * Fallback Function * *********************/ fallback() external payable { address target = addressManager[address(this)].getAddress( (implementationName[address(this)]) ); require( target != address(0), "Target address must be initialized." ); (bool success, bytes memory returndata) = target.delegatecall(msg.data); if (success == true) { assembly { return(add(returndata, 0x20), mload(returndata)) } } else { assembly { revert(add(returndata, 0x20), mload(returndata)) } } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* External Imports */ import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title OVM_GasPriceOracle * @dev This contract exposes the current l2 gas price, a measure of how congested the network * currently is. This measure is used by the Sequencer to determine what fee to charge for * transactions. When the system is more congested, the l2 gas price will increase and fees * will also increase as a result. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_GasPriceOracle is Ownable { /************* * Variables * *************/ // Current l2 gas price uint256 public gasPrice; /*************** * Constructor * ***************/ /** * @param _owner Address that will initially own this contract. */ constructor( address _owner, uint256 _initialGasPrice ) Ownable() { setGasPrice(_initialGasPrice); transferOwnership(_owner); } /******************** * Public Functions * ********************/ /** * Allows the owner to modify the l2 gas price. * @param _gasPrice New l2 gas price. */ function setGasPrice( uint256 _gasPrice ) public onlyOwner { gasPrice = _gasPrice; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Contract Imports */ import { L2StandardERC20 } from "../../../libraries/standards/L2StandardERC20.sol"; import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol"; /** * @title OVM_L2StandardTokenFactory * @dev Factory contract for creating standard L2 token representations of L1 ERC20s * compatible with and working on the standard bridge. * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_L2StandardTokenFactory { event StandardL2TokenCreated(address indexed _l1Token, address indexed _l2Token); /** * @dev Creates an instance of the standard ERC20 token on L2. * @param _l1Token Address of the corresponding L1 token. * @param _name ERC20 name. * @param _symbol ERC20 symbol. */ function createStandardL2Token( address _l1Token, string memory _name, string memory _symbol ) external { require (_l1Token != address(0), "Must provide L1 token address"); L2StandardERC20 l2Token = new L2StandardERC20( Lib_PredeployAddresses.L2_STANDARD_BRIDGE, _l1Token, _name, _symbol ); emit StandardL2TokenCreated(_l1Token, address(l2Token)); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_Bytes32Utils } from "../../optimistic-ethereum/libraries/utils/Lib_Bytes32Utils.sol"; /** * @title TestLib_Byte32Utils */ contract TestLib_Bytes32Utils { function toBool( bytes32 _in ) public pure returns ( bool _out ) { return Lib_Bytes32Utils.toBool(_in); } function fromBool( bool _in ) public pure returns ( bytes32 _out ) { return Lib_Bytes32Utils.fromBool(_in); } function toAddress( bytes32 _in ) public pure returns ( address _out ) { return Lib_Bytes32Utils.toAddress(_in); } function fromAddress( address _in ) public pure returns ( bytes32 _out ) { return Lib_Bytes32Utils.fromAddress(_in); } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_EthUtils } from "../../optimistic-ethereum/libraries/utils/Lib_EthUtils.sol"; /** * @title TestLib_EthUtils */ contract TestLib_EthUtils { function getCode( address _address, uint256 _offset, uint256 _length ) public view returns ( bytes memory _code ) { return Lib_EthUtils.getCode( _address, _offset, _length ); } function getCode( address _address ) public view returns ( bytes memory _code ) { return Lib_EthUtils.getCode( _address ); } function getCodeSize( address _address ) public view returns ( uint256 _codeSize ) { return Lib_EthUtils.getCodeSize( _address ); } function getCodeHash( address _address ) public view returns ( bytes32 _codeHash ) { return Lib_EthUtils.getCodeHash( _address ); } function createContract( bytes memory _code ) public returns ( address _created ) { return Lib_EthUtils.createContract( _code ); } function getAddressForCREATE( address _creator, uint256 _nonce ) public pure returns ( address _address ) { return Lib_EthUtils.getAddressForCREATE( _creator, _nonce ); } function getAddressForCREATE2( address _creator, bytes memory _bytecode, bytes32 _salt ) public pure returns (address _address) { return Lib_EthUtils.getAddressForCREATE2( _creator, _bytecode, _salt ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_MerkleTree } from "../../optimistic-ethereum/libraries/utils/Lib_MerkleTree.sol"; /** * @title TestLib_MerkleTree */ contract TestLib_MerkleTree { function getMerkleRoot( bytes32[] memory _elements ) public pure returns ( bytes32 ) { return Lib_MerkleTree.getMerkleRoot( _elements ); } function verify( bytes32 _root, bytes32 _leaf, uint256 _index, bytes32[] memory _siblings, uint256 _totalLeaves ) public pure returns ( bool ) { return Lib_MerkleTree.verify( _root, _leaf, _index, _siblings, _totalLeaves ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol"; /* Contract Imports */ import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /** * @title mockOVM_BondManager */ contract mockOVM_BondManager is iOVM_BondManager, Lib_AddressResolver { constructor( address _libAddressManager ) Lib_AddressResolver(_libAddressManager) {} function recordGasSpent( bytes32 _preStateRoot, bytes32 _txHash, address _who, uint256 _gasSpent ) override public {} function finalize( bytes32 _preStateRoot, address _publisher, uint256 _timestamp ) override public {} function deposit() override public {} function startWithdrawal() override public {} function finalizeWithdrawal() override public {} function claim( address _who ) override public {} function isCollateralized( address _who ) override public view returns ( bool ) { // Only authenticate sequencer to submit state root batches. return _who == resolve("OVM_Proposer"); } function getGasSpent( bytes32, // _preStateRoot, address // _who ) override public pure returns ( uint256 ) { return 0; } }
Sequencers call this function to post collateral which will be used for the `appendBatch` call This cannot overflow
function deposit() override public { require( token.transferFrom(msg.sender, address(this), requiredCollateral), Errors.ERC20_ERR ); bonds[msg.sender].state = State.COLLATERALIZED; }
6,167,320
[ 1, 1761, 372, 1331, 414, 745, 333, 445, 358, 1603, 4508, 2045, 287, 1492, 903, 506, 1399, 364, 326, 1375, 6923, 4497, 68, 745, 1220, 2780, 9391, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 443, 1724, 1435, 3849, 1071, 288, 203, 3639, 2583, 12, 203, 5411, 1147, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 1931, 13535, 2045, 287, 3631, 203, 5411, 9372, 18, 654, 39, 3462, 67, 9712, 203, 3639, 11272, 203, 203, 3639, 15692, 63, 3576, 18, 15330, 8009, 2019, 273, 3287, 18, 4935, 12190, 654, 1013, 24131, 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 ]
/* Simple Storage An example of basic variable storage, courtesy Solidity documentation - https://solidity.readthedocs.io Lesson: Declare a single variable and use getter and setter methods to recall and change the data. To call this contract's methods, SimpleStorage.set(x) SimpleStorage.get() */ pragma solidity ^0.4.0; // backwards compatability contract SimpleStorage { // like a class definition in Python uint storedData; // only positive numbers of max 256 bytes function set(uint x) public { storedData = x; } function get() public constant returns (uint) { return storedData; } }
like a class definition in Python
contract SimpleStorage {
13,135,570
[ 1, 5625, 279, 667, 2379, 316, 6600, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4477, 3245, 288, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/EnumerableMap.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/tokens/erc20permit-upgradeable/IERC20PermitUpgradeable.sol"; import "./interfaces/IPolicyBookRegistry.sol"; import "./interfaces/IBMICoverStaking.sol"; import "./interfaces/IContractsRegistry.sol"; import "./interfaces/IRewardsGenerator.sol"; import "./interfaces/ILiquidityMining.sol"; import "./interfaces/IPolicyBook.sol"; import "./interfaces/IBMIStaking.sol"; import "./interfaces/ILiquidityRegistry.sol"; import "./tokens/ERC1155Upgradeable.sol"; import "./abstract/AbstractDependant.sol"; import "./abstract/AbstractSlasher.sol"; import "./Globals.sol"; contract BMICoverStaking is IBMICoverStaking, OwnableUpgradeable, ERC1155Upgradeable, AbstractDependant, AbstractSlasher { using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using SafeMath for uint256; using Math for uint256; IERC20 public bmiToken; IPolicyBookRegistry public policyBookRegistry; IRewardsGenerator public rewardsGenerator; ILiquidityMining public liquidityMining; IBMIStaking public bmiStaking; ILiquidityRegistry public liquidityRegistry; mapping(uint256 => StakingInfo) public override _stakersPool; // nft index -> info uint256 internal _nftMintId; // next nft mint id mapping(address => EnumerableSet.UintSet) internal _nftHolderTokens; // holder -> nfts EnumerableMap.UintToAddressMap internal _nftTokenOwners; // index nft -> holder event StakingNFTMinted(uint256 id, address policyBookAddress, address to); event StakingNFTBurned(uint256 id, address policyBookAddress); event StakingBMIProfitWithdrawn( uint256 id, address policyBookAddress, address to, uint256 amount ); event StakingFundsWithdrawn(uint256 id, address policyBookAddress, address to, uint256 amount); event TokensRecovered(address to, uint256 amount); modifier onlyPolicyBooks() { require(policyBookRegistry.isPolicyBook(_msgSender()), "BDS: No access"); _; } function __BMICoverStaking_init() external initializer { __Ownable_init(); __ERC1155_init(""); _nftMintId = 1; } function setDependencies(IContractsRegistry _contractsRegistry) external override onlyInjectorOrZero { bmiToken = IERC20(_contractsRegistry.getBMIContract()); rewardsGenerator = IRewardsGenerator(_contractsRegistry.getRewardsGeneratorContract()); policyBookRegistry = IPolicyBookRegistry( _contractsRegistry.getPolicyBookRegistryContract() ); liquidityMining = ILiquidityMining(_contractsRegistry.getLiquidityMiningContract()); bmiStaking = IBMIStaking(_contractsRegistry.getBMIStakingContract()); liquidityRegistry = ILiquidityRegistry(_contractsRegistry.getLiquidityRegistryContract()); } /// @dev the output URI will be: "https://token-cdn-domain/<tokenId>" function uri(uint256 tokenId) public view override(ERC1155Upgradeable, IBMICoverStaking) returns (string memory) { return string(abi.encodePacked(super.uri(0), Strings.toString(tokenId))); } /// @dev this is a correct URI: "https://token-cdn-domain/" function setBaseURI(string calldata newURI) external onlyOwner { _setURI(newURI); } function recoverTokens() external onlyOwner { uint256 balance = bmiToken.balanceOf(address(this)); bmiToken.transfer(_msgSender(), balance); emit TokensRecovered(_msgSender(), balance); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { for (uint256 i = 0; i < ids.length; i++) { if (amounts[i] != 1) { // not an NFT continue; } if (from == address(0)) { // mint happened _nftHolderTokens[to].add(ids[i]); _nftTokenOwners.set(ids[i], to); } else if (to == address(0)) { // burn happened _nftHolderTokens[from].remove(ids[i]); _nftTokenOwners.remove(ids[i]); } else { // transfer happened _nftHolderTokens[from].remove(ids[i]); _nftHolderTokens[to].add(ids[i]); _nftTokenOwners.set(ids[i], to); _updateLiquidityRegistry(to, from, _stakersPool[ids[i]].policyBookAddress); } } } function _updateLiquidityRegistry( address to, address from, address policyBookAddress ) internal { liquidityRegistry.tryToAddPolicyBook(to, policyBookAddress); liquidityRegistry.tryToRemovePolicyBook(from, policyBookAddress); } function _mintStake(address staker, uint256 id) internal { _mint(staker, id, 1, ""); // mint NFT } function _burnStake(address staker, uint256 id) internal { _burn(staker, id, 1); // burn NFT } function _mintAggregatedNFT( address staker, address policyBookAddress, uint256[] memory tokenIds ) internal { require(policyBookRegistry.isPolicyBook(policyBookAddress), "BDS: Not a PB"); uint256 totalBMIXAmount; for (uint256 i = 0; i < tokenIds.length; i++) { require(ownerOf(tokenIds[i]) == _msgSender(), "BDS: Not a token owner"); require( _stakersPool[tokenIds[i]].policyBookAddress == policyBookAddress, "BDS: NFTs from distinct origins" ); totalBMIXAmount = totalBMIXAmount.add(_stakersPool[tokenIds[i]].stakedBMIXAmount); _burnStake(staker, tokenIds[i]); emit StakingNFTBurned(tokenIds[i], policyBookAddress); /// @dev should be enough delete _stakersPool[tokenIds[i]].policyBookAddress; } _mintStake(staker, _nftMintId); _stakersPool[_nftMintId] = StakingInfo(policyBookAddress, totalBMIXAmount); emit StakingNFTMinted(_nftMintId, policyBookAddress, staker); _nftMintId++; } function _mintNewNFT( address staker, uint256 bmiXAmount, address policyBookAddress ) internal { _mintStake(staker, _nftMintId); _stakersPool[_nftMintId] = StakingInfo(policyBookAddress, bmiXAmount); emit StakingNFTMinted(_nftMintId, policyBookAddress, staker); _nftMintId++; } function aggregateNFTs(address policyBookAddress, uint256[] calldata tokenIds) external override { require(tokenIds.length > 1, "BDS: Can't aggregate"); _mintAggregatedNFT(_msgSender(), policyBookAddress, tokenIds); rewardsGenerator.aggregate(policyBookAddress, tokenIds, _nftMintId - 1); // nftMintId is changed, so -1 } function stakeBMIX(uint256 bmiXAmount, address policyBookAddress) external override { _stakeBMIX(_msgSender(), bmiXAmount, policyBookAddress); } function stakeBMIXWithPermit( uint256 bmiXAmount, address policyBookAddress, uint8 v, bytes32 r, bytes32 s ) external override { _stakeBMIXWithPermit(_msgSender(), bmiXAmount, policyBookAddress, v, r, s); } function stakeBMIXFrom(address user, uint256 bmiXAmount) external override onlyPolicyBooks { _stakeBMIX(user, bmiXAmount, _msgSender()); } function stakeBMIXFromWithPermit( address user, uint256 bmiXAmount, uint8 v, bytes32 r, bytes32 s ) external override onlyPolicyBooks { _stakeBMIXWithPermit(user, bmiXAmount, _msgSender(), v, r, s); } function _stakeBMIXWithPermit( address staker, uint256 bmiXAmount, address policyBookAddress, uint8 v, bytes32 r, bytes32 s ) internal { IERC20PermitUpgradeable(policyBookAddress).permit( staker, address(this), bmiXAmount, MAX_INT, v, r, s ); _stakeBMIX(staker, bmiXAmount, policyBookAddress); } function _stakeBMIX( address user, uint256 bmiXAmount, address policyBookAddress ) internal { require(policyBookRegistry.isPolicyBook(policyBookAddress), "BDS: Not a PB"); require(IPolicyBook(policyBookAddress).whitelisted(), "BDS: PB is not whitelisted"); require(bmiXAmount > 0, "BDS: Zero tokens"); uint256 stblAmount = IPolicyBook(policyBookAddress).convertBMIXToSTBL(bmiXAmount); IERC20(policyBookAddress).transferFrom(user, address(this), bmiXAmount); _mintNewNFT(user, bmiXAmount, policyBookAddress); rewardsGenerator.stake(policyBookAddress, _nftMintId - 1, stblAmount); // nftMintId is changed, so -1 } function _transferProfit(uint256 tokenId, bool onlyProfit) internal { address policyBookAddress = _stakersPool[tokenId].policyBookAddress; uint256 totalProfit; if (onlyProfit) { totalProfit = rewardsGenerator.withdrawReward(policyBookAddress, tokenId); } else { totalProfit = rewardsGenerator.withdrawFunds(policyBookAddress, tokenId); } uint256 bmiStakingProfit = _getSlashed(totalProfit, liquidityMining.startLiquidityMiningTime()); uint256 profit = totalProfit.sub(bmiStakingProfit); // transfer slashed bmi to the bmiStaking and add them to the pool bmiToken.transfer(address(bmiStaking), bmiStakingProfit); bmiStaking.addToPool(bmiStakingProfit); // transfer bmi profit to the user bmiToken.transfer(_msgSender(), profit); emit StakingBMIProfitWithdrawn(tokenId, policyBookAddress, _msgSender(), profit); } /// @param staker address of the staker account /// @param policyBookAddress addres of the policbook /// @param offset pagination start up place /// @param limit size of the listing page /// @param func callback function that returns a uint256 /// @return total function _aggregateForEach( address staker, address policyBookAddress, uint256 offset, uint256 limit, function(uint256) view returns (uint256) func ) internal view returns (uint256 total) { bool nullAddr = policyBookAddress == address(0); require(nullAddr || policyBookRegistry.isPolicyBook(policyBookAddress), "BDS: Not a PB"); uint256 to = (offset.add(limit)).min(balanceOf(staker)).max(offset); for (uint256 i = offset; i < to; i++) { uint256 nftIndex = tokenOfOwnerByIndex(staker, i); if (nullAddr || _stakersPool[nftIndex].policyBookAddress == policyBookAddress) { total = total.add(func(nftIndex)); } } } function _transferForEach(address policyBookAddress, function(uint256) func) internal { require(policyBookRegistry.isPolicyBook(policyBookAddress), "BDS: Not a PB"); uint256 stakerBalance = balanceOf(_msgSender()); for (int256 i = int256(stakerBalance) - 1; i >= 0; i--) { uint256 nftIndex = tokenOfOwnerByIndex(_msgSender(), uint256(i)); if (_stakersPool[nftIndex].policyBookAddress == policyBookAddress) { func(nftIndex); } } } function restakeBMIProfit(uint256 tokenId) public override { require(_stakersPool[tokenId].policyBookAddress != address(0), "BDS: Token doesn't exist"); require(ownerOf(tokenId) == _msgSender(), "BDS: Not a token owner"); uint256 totalProfit = rewardsGenerator.withdrawReward(_stakersPool[tokenId].policyBookAddress, tokenId); bmiToken.transfer(address(bmiStaking), totalProfit); bmiStaking.stakeFor(_msgSender(), totalProfit); } function restakeStakerBMIProfit(address policyBookAddress) external override { _transferForEach(policyBookAddress, restakeBMIProfit); } function withdrawBMIProfit(uint256 tokenId) public override { require(_stakersPool[tokenId].policyBookAddress != address(0), "BDS: Token doesn't exist"); require(ownerOf(tokenId) == _msgSender(), "BDS: Not a token owner"); _transferProfit(tokenId, true); } function withdrawStakerBMIProfit(address policyBookAddress) external override { _transferForEach(policyBookAddress, withdrawBMIProfit); } function withdrawFundsWithProfit(uint256 tokenId) public override { address policyBookAddress = _stakersPool[tokenId].policyBookAddress; require(policyBookAddress != address(0), "BDS: Token doesn't exist"); require(ownerOf(tokenId) == _msgSender(), "BDS: Not a token owner"); _transferProfit(tokenId, false); uint256 stakedFunds = _stakersPool[tokenId].stakedBMIXAmount; // transfer bmiX from staking to the user IERC20(policyBookAddress).transfer(_msgSender(), stakedFunds); emit StakingFundsWithdrawn(tokenId, policyBookAddress, _msgSender(), stakedFunds); _burnStake(_msgSender(), tokenId); emit StakingNFTBurned(tokenId, policyBookAddress); delete _stakersPool[tokenId]; } function withdrawStakerFundsWithProfit(address policyBookAddress) external override { _transferForEach(policyBookAddress, withdrawFundsWithProfit); } /// @dev returns percentage multiplied by 10**25 function getSlashingPercentage() external view override returns (uint256) { return getSlashingPercentage(liquidityMining.startLiquidityMiningTime()); } function getSlashedBMIProfit(uint256 tokenId) public view override returns (uint256) { return _applySlashing(getBMIProfit(tokenId), liquidityMining.startLiquidityMiningTime()); } /// @notice retrieves the BMI profit of a tokenId /// @param tokenId numeric id identifier of the token /// @return profit amount function getBMIProfit(uint256 tokenId) public view override returns (uint256) { return rewardsGenerator.getReward(_stakersPool[tokenId].policyBookAddress, tokenId); } function getSlashedStakerBMIProfit( address staker, address policyBookAddress, uint256 offset, uint256 limit ) external view override returns (uint256 totalProfit) { uint256 stakerBMIProfit = getStakerBMIProfit(staker, policyBookAddress, offset, limit); return _applySlashing(stakerBMIProfit, liquidityMining.startLiquidityMiningTime()); } function getStakerBMIProfit( address staker, address policyBookAddress, uint256 offset, uint256 limit ) public view override returns (uint256) { return _aggregateForEach(staker, policyBookAddress, offset, limit, getBMIProfit); } function totalStaked(address user) external view override returns (uint256) { return _aggregateForEach(user, address(0), 0, MAX_INT, stakedByNFT); } function totalStakedSTBL(address user) external view override returns (uint256) { return _aggregateForEach(user, address(0), 0, MAX_INT, stakedSTBLByNFT); } function stakedByNFT(uint256 tokenId) public view override returns (uint256) { return _stakersPool[tokenId].stakedBMIXAmount; } function stakedSTBLByNFT(uint256 tokenId) public view override returns (uint256) { return rewardsGenerator.getStakedNFTSTBL(tokenId); } /// @notice returns number of NFTs on user's account function balanceOf(address user) public view override returns (uint256) { return _nftHolderTokens[user].length(); } function ownerOf(uint256 tokenId) public view override returns (address) { return _nftTokenOwners.get(tokenId); } function tokenOfOwnerByIndex(address user, uint256 index) public view override returns (uint256) { return _nftHolderTokens[user].at(index); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds uint256 constant DAYS_IN_THE_YEAR = 365; uint256 constant MAX_INT = type(uint256).max; uint256 constant DECIMALS18 = 10**18; uint256 constant PRECISION = 10**25; uint256 constant PERCENTAGE_100 = 100 * PRECISION; uint256 constant BLOCKS_PER_DAY = 6450; uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365; uint256 constant APY_TOKENS = DECIMALS18; uint256 constant PROTOCOL_PERCENTAGE = 20 * PRECISION; uint256 constant DEFAULT_REBALANCING_THRESHOLD = 10**23; uint256 constant EPOCH_DAYS_AMOUNT = 7; // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "../interfaces/IContractsRegistry.sol"; abstract contract AbstractDependant { /// @dev keccak256(AbstractDependant.setInjector(address)) - 1 bytes32 private constant _INJECTOR_SLOT = 0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76; modifier onlyInjectorOrZero() { address _injector = injector(); require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector"); _; } function setInjector(address _injector) external onlyInjectorOrZero { bytes32 slot = _INJECTOR_SLOT; assembly { sstore(slot, _injector) } } /// @dev has to apply onlyInjectorOrZero() modifier function setDependencies(IContractsRegistry) external virtual; function injector() public view returns (address _injector) { bytes32 slot = _INJECTOR_SLOT; assembly { _injector := sload(slot) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "../Globals.sol"; abstract contract AbstractSlasher { using SafeMath for uint256; using Math for uint256; uint256 public constant MAX_EXIT_FEE = 90 * PRECISION; uint256 public constant MIN_EXIT_FEE = 20 * PRECISION; uint256 public constant EXIT_FEE_DURATION = 100 days; function getSlashingPercentage(uint256 startTime) public view returns (uint256) { startTime = startTime == 0 || startTime > block.timestamp ? block.timestamp : startTime; uint256 feeSpan = MAX_EXIT_FEE.sub(MIN_EXIT_FEE); uint256 feePerSecond = feeSpan.div(EXIT_FEE_DURATION); uint256 fee = Math.min(block.timestamp.sub(startTime).mul(feePerSecond), feeSpan); return MAX_EXIT_FEE.sub(fee); } function getSlashingPercentage() external view virtual returns (uint256); function _applySlashing(uint256 amount, uint256 startTime) internal view returns (uint256) { return amount.sub(_getSlashed(amount, startTime)); } function _getSlashed(uint256 amount, uint256 startTime) internal view returns (uint256) { return amount.mul(getSlashingPercentage(startTime)).div(PERCENTAGE_100); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface IBMICoverStaking { struct StakingInfo { address policyBookAddress; uint256 stakedBMIXAmount; } struct PolicyBookInfo { uint256 totalStakedSTBL; uint256 rewardPerBlock; uint256 stakingAPY; uint256 liquidityAPY; } struct UserInfo { uint256 totalStakedBMIX; uint256 totalStakedSTBL; uint256 totalBmiReward; } struct NFTsInfo { uint256 nftIndex; string uri; uint256 stakedBMIXAmount; uint256 stakedSTBLAmount; uint256 reward; } function aggregateNFTs(address policyBookAddress, uint256[] calldata tokenIds) external; function stakeBMIX(uint256 amount, address policyBookAddress) external; function stakeBMIXWithPermit( uint256 bmiXAmount, address policyBookAddress, uint8 v, bytes32 r, bytes32 s ) external; function stakeBMIXFrom(address user, uint256 amount) external; function stakeBMIXFromWithPermit( address user, uint256 bmiXAmount, uint8 v, bytes32 r, bytes32 s ) external; // mappings function _stakersPool(uint256 index) external view returns (address policyBookAddress, uint256 stakedBMIXAmount); // function getPolicyBookAPY(address policyBookAddress) external view returns (uint256); function restakeBMIProfit(uint256 tokenId) external; function restakeStakerBMIProfit(address policyBookAddress) external; function withdrawBMIProfit(uint256 tokenID) external; function withdrawStakerBMIProfit(address policyBookAddress) external; function withdrawFundsWithProfit(uint256 tokenID) external; function withdrawStakerFundsWithProfit(address policyBookAddress) external; function getSlashedBMIProfit(uint256 tokenId) external view returns (uint256); function getBMIProfit(uint256 tokenId) external view returns (uint256); function getSlashedStakerBMIProfit( address staker, address policyBookAddress, uint256 offset, uint256 limit ) external view returns (uint256 totalProfit); function getStakerBMIProfit( address staker, address policyBookAddress, uint256 offset, uint256 limit ) external view returns (uint256 totalProfit); function totalStaked(address user) external view returns (uint256); function totalStakedSTBL(address user) external view returns (uint256); function stakedByNFT(uint256 tokenId) external view returns (uint256); function stakedSTBLByNFT(uint256 tokenId) external view returns (uint256); function balanceOf(address user) external view returns (uint256); function ownerOf(uint256 tokenId) external view returns (address); function uri(uint256 tokenId) external view returns (string memory); function tokenOfOwnerByIndex(address user, uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "./tokens/ISTKBMIToken.sol"; interface IBMIStaking { event StakedBMI(uint256 stakedBMI, uint256 mintedStkBMI, address indexed recipient); event BMIWithdrawn(uint256 amountBMI, uint256 burnedStkBMI, address indexed recipient); event UnusedRewardPoolRevoked(address recipient, uint256 amount); event RewardPoolRevoked(address recipient, uint256 amount); struct WithdrawalInfo { uint256 coolDownTimeEnd; uint256 amountBMIRequested; } function stakeWithPermit( uint256 _amountBMI, uint8 _v, bytes32 _r, bytes32 _s ) external; function stakeFor(address _user, uint256 _amountBMI) external; function stake(uint256 _amountBMI) external; function maturityAt() external view returns (uint256); function isBMIRewardUnlocked() external view returns (bool); function whenCanWithdrawBMIReward(address _address) external view returns (uint256); function unlockTokensToWithdraw(uint256 _amountBMIUnlock) external; function withdraw() external; /// @notice Getting withdraw information /// @return _amountBMIRequested is amount of bmi tokens requested to unlock /// @return _amountStkBMI is amount of stkBMI that will burn /// @return _unlockPeriod is its timestamp when user can withdraw /// returns 0 if it didn't unlocked yet. User has 48hs to withdraw /// @return _availableFor is the end date if withdraw period has already begun /// or 0 if it is expired or didn't start function getWithdrawalInfo(address _userAddr) external view returns ( uint256 _amountBMIRequested, uint256 _amountStkBMI, uint256 _unlockPeriod, uint256 _availableFor ); function addToPool(uint256 _amount) external; function stakingReward(uint256 _amount) external view returns (uint256); function getStakedBMI(address _address) external view returns (uint256); function getAPY() external view returns (uint256); function setRewardPerBlock(uint256 _amount) external; function revokeRewardPool(uint256 _amount) external; function revokeUnusedRewardPool() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; interface IClaimingRegistry { enum ClaimStatus { CAN_CLAIM, UNCLAIMABLE, PENDING, AWAITING_CALCULATION, REJECTED_CAN_APPEAL, REJECTED, ACCEPTED } struct ClaimInfo { address claimer; address policyBookAddress; string evidenceURI; uint256 dateSubmitted; uint256 dateEnded; bool appeal; ClaimStatus status; uint256 claimAmount; } /// @notice returns anonymous voting duration function anonymousVotingDuration(uint256 index) external view returns (uint256); /// @notice returns the whole voting duration function votingDuration(uint256 index) external view returns (uint256); /// @notice returns how many time should pass before anyone could calculate a claim result function anyoneCanCalculateClaimResultAfter(uint256 index) external view returns (uint256); /// @notice returns true if a user can buy new policy of specified PolicyBook function canBuyNewPolicy(address buyer, address policyBookAddress) external view returns (bool); /// @notice submits new PolicyBook claim for the user function submitClaim( address user, address policyBookAddress, string calldata evidenceURI, uint256 cover, bool appeal ) external returns (uint256); /// @notice returns true if the claim with this index exists function claimExists(uint256 index) external view returns (bool); /// @notice returns claim submition time function claimSubmittedTime(uint256 index) external view returns (uint256); /// @notice returns claim end time or zero in case it is pending function claimEndTime(uint256 index) external view returns (uint256); /// @notice returns true if the claim is anonymously votable function isClaimAnonymouslyVotable(uint256 index) external view returns (bool); /// @notice returns true if the claim is exposably votable function isClaimExposablyVotable(uint256 index) external view returns (bool); /// @notice returns true if claim is anonymously votable or exposably votable function isClaimVotable(uint256 index) external view returns (bool); /// @notice returns true if a claim can be calculated by anyone function canClaimBeCalculatedByAnyone(uint256 index) external view returns (bool); /// @notice returns true if this claim is pending or awaiting function isClaimPending(uint256 index) external view returns (bool); /// @notice returns how many claims the holder has function countPolicyClaimerClaims(address user) external view returns (uint256); /// @notice returns how many pending claims are there function countPendingClaims() external view returns (uint256); /// @notice returns how many claims are there function countClaims() external view returns (uint256); /// @notice returns a claim index of it's claimer and an ordinal number function claimOfOwnerIndexAt(address claimer, uint256 orderIndex) external view returns (uint256); /// @notice returns pending claim index by its ordinal index function pendingClaimIndexAt(uint256 orderIndex) external view returns (uint256); /// @notice returns claim index by its ordinal index function claimIndexAt(uint256 orderIndex) external view returns (uint256); /// @notice returns current active claim index by policybook and claimer function claimIndex(address claimer, address policyBookAddress) external view returns (uint256); /// @notice returns true if the claim is appealed function isClaimAppeal(uint256 index) external view returns (bool); /// @notice returns current status of a claim function policyStatus(address claimer, address policyBookAddress) external view returns (ClaimStatus); /// @notice returns current status of a claim function claimStatus(uint256 index) external view returns (ClaimStatus); /// @notice returns the claim owner (claimer) function claimOwner(uint256 index) external view returns (address); /// @notice returns the claim PolicyBook function claimPolicyBook(uint256 index) external view returns (address); /// @notice returns claim info by its index function claimInfo(uint256 index) external view returns (ClaimInfo memory _claimInfo); function getAllPendingClaimsAmount() external view returns (uint256 _totalClaimsAmount); function getClaimableAmounts(uint256[] memory _claimIndexes) external view returns (uint256); /// @notice marks the user's claim as Accepted function acceptClaim(uint256 index) external; /// @notice marks the user's claim as Rejected function rejectClaim(uint256 index) external; /// @notice Update Image Uri in case it contains material that is ilegal /// or offensive. /// @dev Only the owner of the PolicyBookAdmin can erase/update evidenceUri. /// @param _claimIndex Claim Index that is going to be updated /// @param _newEvidenceURI New evidence uri. It can be blank. function updateImageUriOfClaim(uint256 _claimIndex, string calldata _newEvidenceURI) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface IContractsRegistry { function getUniswapRouterContract() external view returns (address); function getUniswapBMIToETHPairContract() external view returns (address); function getUniswapBMIToUSDTPairContract() external view returns (address); function getSushiswapRouterContract() external view returns (address); function getSushiswapBMIToETHPairContract() external view returns (address); function getSushiswapBMIToUSDTPairContract() external view returns (address); function getSushiSwapMasterChefV2Contract() external view returns (address); function getWETHContract() external view returns (address); function getUSDTContract() external view returns (address); function getBMIContract() external view returns (address); function getPriceFeedContract() external view returns (address); function getPolicyBookRegistryContract() external view returns (address); function getPolicyBookFabricContract() external view returns (address); function getBMICoverStakingContract() external view returns (address); function getBMICoverStakingViewContract() external view returns (address); function getLegacyRewardsGeneratorContract() external view returns (address); function getRewardsGeneratorContract() external view returns (address); function getBMIUtilityNFTContract() external view returns (address); function getNFTStakingContract() external view returns (address); function getLiquidityMiningContract() external view returns (address); function getClaimingRegistryContract() external view returns (address); function getPolicyRegistryContract() external view returns (address); function getLiquidityRegistryContract() external view returns (address); function getClaimVotingContract() external view returns (address); function getReinsurancePoolContract() external view returns (address); function getLeveragePortfolioViewContract() external view returns (address); function getCapitalPoolContract() external view returns (address); function getPolicyBookAdminContract() external view returns (address); function getPolicyQuoteContract() external view returns (address); function getLegacyBMIStakingContract() external view returns (address); function getBMIStakingContract() external view returns (address); function getSTKBMIContract() external view returns (address); function getVBMIContract() external view returns (address); function getLegacyLiquidityMiningStakingContract() external view returns (address); function getLiquidityMiningStakingETHContract() external view returns (address); function getLiquidityMiningStakingUSDTContract() external view returns (address); function getReputationSystemContract() external view returns (address); function getAaveProtocolContract() external view returns (address); function getAaveLendPoolAddressProvdierContract() external view returns (address); function getAaveATokenContract() external view returns (address); function getCompoundProtocolContract() external view returns (address); function getCompoundCTokenContract() external view returns (address); function getCompoundComptrollerContract() external view returns (address); function getYearnProtocolContract() external view returns (address); function getYearnVaultContract() external view returns (address); function getYieldGeneratorContract() external view returns (address); function getShieldMiningContract() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface ILeveragePortfolio { enum LeveragePortfolio {USERLEVERAGEPOOL, REINSURANCEPOOL} struct LevFundsFactors { uint256 netMPL; uint256 netMPLn; address policyBookAddr; // uint256 poolTotalLiquidity; // uint256 poolUR; // uint256 minUR; } function targetUR() external view returns (uint256); function d_ProtocolConstant() external view returns (uint256); function a_ProtocolConstant() external view returns (uint256); function max_ProtocolConstant() external view returns (uint256); /// @notice deploy lStable from user leverage pool or reinsurance pool using 2 formulas: access by policybook. /// @param leveragePoolType LeveragePortfolio is determine the pool which call the function function deployLeverageStableToCoveragePools(LeveragePortfolio leveragePoolType) external returns (uint256); /// @notice deploy the vStable from RP in v2 and for next versions it will be from RP and LP : access by policybook. function deployVirtualStableToCoveragePools() external returns (uint256); /// @notice set the threshold % for re-evaluation of the lStable provided across all Coverage pools : access by owner /// @param threshold uint256 is the reevaluatation threshold function setRebalancingThreshold(uint256 threshold) external; /// @notice set the protocol constant : access by owner /// @param _targetUR uint256 target utitlization ration /// @param _d_ProtocolConstant uint256 D protocol constant /// @param _a_ProtocolConstant uint256 A protocol constant /// @param _max_ProtocolConstant uint256 the max % included function setProtocolConstant( uint256 _targetUR, uint256 _d_ProtocolConstant, uint256 _a_ProtocolConstant, uint256 _max_ProtocolConstant ) external; /// @notice calc M factor by formual M = min( abs((1/ (Tur-UR))*d) /a, max) /// @param poolUR uint256 utitilization ratio for a coverage pool /// @return uint256 M facotr //function calcM(uint256 poolUR) external returns (uint256); /// @return uint256 the amount of vStable stored in the pool function totalLiquidity() external view returns (uint256); /// @notice add the portion of 80% of premium to user leverage pool where the leverage provide lstable : access policybook /// add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable) : access policybook /// @param epochsNumber uint256 the number of epochs which the policy holder will pay a premium for /// @param premiumAmount uint256 the premium amount which is a portion of 80% of the premium function addPolicyPremium(uint256 epochsNumber, uint256 premiumAmount) external; /// @notice Used to get a list of coverage pools which get leveraged , use with count() /// @return _coveragePools a list containing policybook addresses function listleveragedCoveragePools(uint256 offset, uint256 limit) external view returns (address[] memory _coveragePools); /// @notice get count of coverage pools which get leveraged function countleveragedCoveragePools() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface ILiquidityMining { struct TeamDetails { string teamName; address referralLink; uint256 membersNumber; uint256 totalStakedAmount; uint256 totalReward; } struct UserInfo { address userAddr; string teamName; uint256 stakedAmount; uint256 mainNFT; // 0 or NFT index if available uint256 platinumNFT; // 0 or NFT index if available } struct UserRewardsInfo { string teamName; uint256 totalBMIReward; // total BMI reward uint256 availableBMIReward; // current claimable BMI reward uint256 incomingPeriods; // how many month are incoming uint256 timeToNextDistribution; // exact time left to next distribution uint256 claimedBMI; // actual number of claimed BMI uint256 mainNFTAvailability; // 0 or NFT index if available uint256 platinumNFTAvailability; // 0 or NFT index if available bool claimedNFTs; // true if user claimed NFTs } struct MyTeamInfo { TeamDetails teamDetails; uint256 myStakedAmount; uint256 teamPlace; } struct UserTeamInfo { address teamAddr; uint256 stakedAmount; uint256 countOfRewardedMonth; bool isNFTDistributed; } struct TeamInfo { string name; uint256 totalAmount; address[] teamLeaders; } function startLiquidityMiningTime() external view returns (uint256); function getTopTeams() external view returns (TeamDetails[] memory teams); function getTopUsers() external view returns (UserInfo[] memory users); function getAllTeamsLength() external view returns (uint256); function getAllTeamsDetails(uint256 _offset, uint256 _limit) external view returns (TeamDetails[] memory _teamDetailsArr); function getMyTeamsLength() external view returns (uint256); function getMyTeamMembers(uint256 _offset, uint256 _limit) external view returns (address[] memory _teamMembers, uint256[] memory _memberStakedAmount); function getAllUsersLength() external view returns (uint256); function getAllUsersInfo(uint256 _offset, uint256 _limit) external view returns (UserInfo[] memory _userInfos); function getMyTeamInfo() external view returns (MyTeamInfo memory _myTeamInfo); function getRewardsInfo(address user) external view returns (UserRewardsInfo memory userRewardInfo); function createTeam(string calldata _teamName) external; function deleteTeam() external; function joinTheTeam(address _referralLink) external; function getSlashingPercentage() external view returns (uint256); function investSTBL(uint256 _tokensAmount, address _policyBookAddr) external; function distributeNFT() external; function checkPlatinumNFTReward(address _userAddr) external view returns (uint256); function checkMainNFTReward(address _userAddr) external view returns (uint256); function distributeBMIReward() external; function getTotalUserBMIReward(address _userAddr) external view returns (uint256); function checkAvailableBMIReward(address _userAddr) external view returns (uint256); /// @notice checks if liquidity mining event is lasting (startLiquidityMining() has been called) /// @return true if LM is started and not ended, false otherwise function isLMLasting() external view returns (bool); /// @notice checks if liquidity mining event is finished. In order to be finished, it has to be started /// @return true if LM is finished, false if event is still going or not started function isLMEnded() external view returns (bool); function getEndLMTime() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface ILiquidityRegistry { struct LiquidityInfo { address policyBookAddr; uint256 lockedAmount; uint256 availableAmount; uint256 bmiXRatio; // multiply availableAmount by this num to get stable coin } struct WithdrawalRequestInfo { address policyBookAddr; uint256 requestAmount; uint256 requestSTBLAmount; uint256 availableLiquidity; uint256 readyToWithdrawDate; uint256 endWithdrawDate; } struct WithdrawalSetInfo { address policyBookAddr; uint256 requestAmount; uint256 requestSTBLAmount; uint256 availableSTBLAmount; } function tryToAddPolicyBook(address _userAddr, address _policyBookAddr) external; function tryToRemovePolicyBook(address _userAddr, address _policyBookAddr) external; function getPolicyBooksArrLength(address _userAddr) external view returns (uint256); function getPolicyBooksArr(address _userAddr) external view returns (address[] memory _resultArr); function getLiquidityInfos( address _userAddr, uint256 _offset, uint256 _limit ) external view returns (LiquidityInfo[] memory _resultArr); function getWithdrawalRequests( address _userAddr, uint256 _offset, uint256 _limit ) external view returns (uint256 _arrLength, WithdrawalRequestInfo[] memory _resultArr); function getWithdrawalSet( address _userAddr, uint256 _offset, uint256 _limit ) external view returns (uint256 _arrLength, WithdrawalSetInfo[] memory _resultArr); function registerWithdrawl(address _policyBook, address _users) external; function getAllPendingWithdrawalRequestsAmount() external returns (uint256 _totalWithdrawlAmount); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; import "./IClaimingRegistry.sol"; import "./IPolicyBookFacade.sol"; interface IPolicyBook { enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED} struct PolicyHolder { uint256 coverTokens; uint256 startEpochNumber; uint256 endEpochNumber; uint256 paid; uint256 reinsurancePrice; } struct WithdrawalInfo { uint256 withdrawalAmount; uint256 readyToWithdrawDate; bool withdrawalAllowed; } struct BuyPolicyParameters { address buyer; address holder; uint256 epochsNumber; uint256 coverTokens; uint256 distributorFee; address distributor; } function policyHolders(address _holder) external view returns ( uint256, uint256, uint256, uint256, uint256 ); function policyBookFacade() external view returns (IPolicyBookFacade); function setPolicyBookFacade(address _policyBookFacade) external; function EPOCH_DURATION() external view returns (uint256); function stblDecimals() external view returns (uint256); function READY_TO_WITHDRAW_PERIOD() external view returns (uint256); function whitelisted() external view returns (bool); function epochStartTime() external view returns (uint256); // @TODO: should we let DAO to change contract address? /// @notice Returns address of contract this PolicyBook covers, access: ANY /// @return _contract is address of covered contract function insuranceContractAddress() external view returns (address _contract); /// @notice Returns type of contract this PolicyBook covers, access: ANY /// @return _type is type of contract function contractType() external view returns (IPolicyBookFabric.ContractType _type); function totalLiquidity() external view returns (uint256); function totalCoverTokens() external view returns (uint256); // /// @notice return MPL for user leverage pool // function userleveragedMPL() external view returns (uint256); // /// @notice return MPL for reinsurance pool // function reinsurancePoolMPL() external view returns (uint256); // function bmiRewardMultiplier() external view returns (uint256); function withdrawalsInfo(address _userAddr) external view returns ( uint256 _withdrawalAmount, uint256 _readyToWithdrawDate, bool _withdrawalAllowed ); function __PolicyBook_init( address _insuranceContract, IPolicyBookFabric.ContractType _contractType, string calldata _description, string calldata _projectSymbol ) external; function whitelist(bool _whitelisted) external; function getEpoch(uint256 time) external view returns (uint256); /// @notice get STBL equivalent function convertBMIXToSTBL(uint256 _amount) external view returns (uint256); /// @notice get BMIX equivalent function convertSTBLToBMIX(uint256 _amount) external view returns (uint256); /// @notice submits new claim of the policy book function submitClaimAndInitializeVoting(string calldata evidenceURI) external; /// @notice submits new appeal claim of the policy book function submitAppealAndInitializeVoting(string calldata evidenceURI) external; /// @notice updates info on claim acceptance function commitClaim( address claimer, uint256 claimAmount, uint256 claimEndTime, IClaimingRegistry.ClaimStatus status ) external; /// @notice forces an update of RewardsGenerator multiplier function forceUpdateBMICoverStakingRewardMultiplier() external; /// @notice function to get precise current cover and liquidity function getNewCoverAndLiquidity() external view returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity); /// @notice view function to get precise policy price /// @param _epochsNumber is number of epochs to cover /// @param _coverTokens is number of tokens to cover /// @param _buyer address of the user who buy the policy /// @return totalSeconds is number of seconds to cover /// @return totalPrice is the policy price which will pay by the buyer function getPolicyPrice( uint256 _epochsNumber, uint256 _coverTokens, address _buyer ) external view returns ( uint256 totalSeconds, uint256 totalPrice, uint256 pricePercentage ); /// @notice Let user to buy policy by supplying stable coin, access: ANY /// @param _buyer who is transferring funds /// @param _holder who owns coverage /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage /// @param _distributorFee distributor fee (commission). It can't be greater than PROTOCOL_PERCENTAGE /// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission) function buyPolicy( address _buyer, address _holder, uint256 _epochsNumber, uint256 _coverTokens, uint256 _distributorFee, address _distributor ) external returns (uint256, uint256); function updateEpochsInfo() external; function secondsToEndCurrentEpoch() external view returns (uint256); /// @notice Let eligible contracts add liqiudity for another user by supplying stable coin /// @param _liquidityHolderAddr is address of address to assign cover /// @param _liqudityAmount is amount of stable coin tokens to secure function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external; /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _liquidityBuyerAddr address the one that transfer funds /// @param _liquidityHolderAddr address the one that owns liquidity /// @param _liquidityAmount uint256 amount to be added on behalf the sender /// @param _stakeSTBLAmount uint256 the staked amount if add liq and stake function addLiquidity( address _liquidityBuyerAddr, address _liquidityHolderAddr, uint256 _liquidityAmount, uint256 _stakeSTBLAmount ) external; function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256); function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus); function requestWithdrawal(uint256 _tokensToWithdraw, address _user) external; // function requestWithdrawalWithPermit( // uint256 _tokensToWithdraw, // uint8 _v, // bytes32 _r, // bytes32 _s // ) external; function unlockTokens() external; /// @notice Let user to withdraw deposited liqiudity, access: ANY function withdrawLiquidity(address sender) external returns (uint256); function getAPY() external view returns (uint256); /// @notice Getting user stats, access: ANY function userStats(address _user) external view returns (PolicyHolder memory); /// @notice Getting number stats, access: ANY /// @return _maxCapacities is a max token amount that a user can buy /// @return _totalSTBLLiquidity is PolicyBook's liquidity /// @return _totalLeveragedLiquidity is PolicyBook's leveraged liquidity /// @return _stakedSTBL is how much stable coin are staked on this PolicyBook /// @return _annualProfitYields is its APY /// @return _annualInsuranceCost is percentage of cover tokens that is required to be paid for 1 year of insurance function numberStats() external view returns ( uint256 _maxCapacities, uint256 _totalSTBLLiquidity, uint256 _totalLeveragedLiquidity, uint256 _stakedSTBL, uint256 _annualProfitYields, uint256 _annualInsuranceCost, uint256 _bmiXRatio ); /// @notice Getting info, access: ANY /// @return _symbol is the symbol of PolicyBook (bmiXCover) /// @return _insuredContract is an addres of insured contract /// @return _contractType is a type of insured contract /// @return _whitelisted is a state of whitelisting function info() external view returns ( string memory _symbol, address _insuredContract, IPolicyBookFabric.ContractType _contractType, bool _whitelisted ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface IPolicyBookFabric { enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE, VARIOUS} /// @notice Create new Policy Book contract, access: ANY /// @param _contract is Contract to create policy book for /// @param _contractType is Contract to create policy book for /// @param _description is bmiXCover token desription for this policy book /// @param _projectSymbol replaces x in bmiXCover token symbol /// @param _initialDeposit is an amount user deposits on creation (addLiquidity()) /// @return _policyBook is address of created contract function create( address _contract, ContractType _contractType, string calldata _description, string calldata _projectSymbol, uint256 _initialDeposit, address _shieldMiningToken ) external returns (address); function createLeveragePools( ContractType _contractType, string calldata _description, string calldata _projectSymbol ) external returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "./IPolicyBook.sol"; import "./ILeveragePortfolio.sol"; interface IPolicyBookFacade { /// @notice Let user to buy policy by supplying stable coin, access: ANY /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage function buyPolicy(uint256 _epochsNumber, uint256 _coverTokens) external; /// @param _holder who owns coverage /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage function buyPolicyFor( address _holder, uint256 _epochsNumber, uint256 _coverTokens ) external; function policyBook() external view returns (IPolicyBook); function userLiquidity(address account) external view returns (uint256); /// @notice virtual funds deployed by reinsurance pool function VUreinsurnacePool() external view returns (uint256); /// @notice leverage funds deployed by reinsurance pool function LUreinsurnacePool() external view returns (uint256); /// @notice leverage funds deployed by user leverage pool function LUuserLeveragePool(address userLeveragePool) external view returns (uint256); /// @notice total leverage funds deployed to the pool sum of (VUreinsurnacePool,LUreinsurnacePool,LUuserLeveragePool) function totalLeveragedLiquidity() external view returns (uint256); function userleveragedMPL() external view returns (uint256); function reinsurancePoolMPL() external view returns (uint256); function rebalancingThreshold() external view returns (uint256); function safePricingModel() external view returns (bool); /// @notice policyBookFacade initializer /// @param pbProxy polciybook address upgreadable cotnract. function __PolicyBookFacade_init( address pbProxy, address liquidityProvider, uint256 initialDeposit ) external; /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage /// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission) function buyPolicyFromDistributor( uint256 _epochsNumber, uint256 _coverTokens, address _distributor ) external; /// @param _buyer who is buying the coverage /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage /// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission) function buyPolicyFromDistributorFor( address _buyer, uint256 _epochsNumber, uint256 _coverTokens, address _distributor ) external; /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _liquidityAmount is amount of stable coin tokens to secure function addLiquidity(uint256 _liquidityAmount) external; /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _user the one taht add liquidity /// @param _liquidityAmount is amount of stable coin tokens to secure function addLiquidityFromDistributorFor(address _user, uint256 _liquidityAmount) external; /// @notice Let user to add liquidity by supplying stable coin and stake it, /// @dev access: ANY function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external; /// @notice Let user to withdraw deposited liqiudity, access: ANY function withdrawLiquidity() external; /// @notice fetches all the pools data /// @return uint256 VUreinsurnacePool /// @return uint256 LUreinsurnacePool /// @return uint256 LUleveragePool /// @return uint256 user leverage pool address function getPoolsData() external view returns ( uint256, uint256, uint256, address ); /// @notice deploy leverage funds (RP lStable, ULP lStable) /// @param deployedAmount uint256 the deployed amount to be added or substracted from the total liquidity /// @param leveragePool whether user leverage or reinsurance leverage function deployLeverageFundsAfterRebalance( uint256 deployedAmount, ILeveragePortfolio.LeveragePortfolio leveragePool ) external; /// @notice deploy virtual funds (RP vStable) /// @param deployedAmount uint256 the deployed amount to be added to the liquidity function deployVirtualFundsAfterRebalance(uint256 deployedAmount) external; /// @notice set the MPL for the user leverage and the reinsurance leverage /// @param _userLeverageMPL uint256 value of the user leverage MPL /// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage MPL function setMPLs(uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL) external; /// @notice sets the rebalancing threshold value /// @param _newRebalancingThreshold uint256 rebalancing threshhold value function setRebalancingThreshold(uint256 _newRebalancingThreshold) external; /// @notice sets the rebalancing threshold value /// @param _safePricingModel bool is pricing model safe (true) or not (false) function setSafePricingModel(bool _safePricingModel) external; /// @notice returns how many BMI tokens needs to approve in order to submit a claim function getClaimApprovalAmount(address user) external view returns (uint256); /// @notice upserts a withdraw request /// @dev prevents adding a request if an already pending or ready request is open. /// @param _tokensToWithdraw uint256 amount of tokens to withdraw function requestWithdrawal(uint256 _tokensToWithdraw) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; interface IPolicyBookRegistry { struct PolicyBookStats { string symbol; address insuredContract; IPolicyBookFabric.ContractType contractType; uint256 maxCapacity; uint256 totalSTBLLiquidity; uint256 totalLeveragedLiquidity; uint256 stakedSTBL; uint256 APY; uint256 annualInsuranceCost; uint256 bmiXRatio; bool whitelisted; } function policyBooksByInsuredAddress(address insuredContract) external view returns (address); function policyBookFacades(address facadeAddress) external view returns (address); /// @notice Adds PolicyBook to registry, access: PolicyFabric function add( address insuredContract, IPolicyBookFabric.ContractType contractType, address policyBook, address facadeAddress ) external; function whitelist(address policyBookAddress, bool whitelisted) external; /// @notice returns required allowances for the policybooks function getPoliciesPrices( address[] calldata policyBooks, uint256[] calldata epochsNumbers, uint256[] calldata coversTokens ) external view returns (uint256[] memory _durations, uint256[] memory _allowances); /// @notice Buys a batch of policies function buyPolicyBatch( address[] calldata policyBooks, uint256[] calldata epochsNumbers, uint256[] calldata coversTokens ) external; /// @notice Checks if provided address is a PolicyBook function isPolicyBook(address policyBook) external view returns (bool); /// @notice Checks if provided address is a policyBookFacade function isPolicyBookFacade(address _facadeAddress) external view returns (bool); /// @notice Checks if provided address is a user leverage pool function isUserLeveragePool(address policyBookAddress) external view returns (bool); /// @notice Returns number of registered PolicyBooks with certain contract type function countByType(IPolicyBookFabric.ContractType contractType) external view returns (uint256); /// @notice Returns number of registered PolicyBooks, access: ANY function count() external view returns (uint256); function countByTypeWhitelisted(IPolicyBookFabric.ContractType contractType) external view returns (uint256); function countWhitelisted() external view returns (uint256); /// @notice Listing registered PolicyBooks with certain contract type, access: ANY /// @return _policyBooksArr is array of registered PolicyBook addresses with certain contract type function listByType( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr); /// @notice Listing registered PolicyBooks, access: ANY /// @return _policyBooksArr is array of registered PolicyBook addresses function list(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr); function listByTypeWhitelisted( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr); function listWhitelisted(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr); /// @notice Listing registered PolicyBooks with stats and certain contract type, access: ANY function listWithStatsByType( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); /// @notice Listing registered PolicyBooks with stats, access: ANY function listWithStats(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); function listWithStatsByTypeWhitelisted( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); function listWithStatsWhitelisted(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); /// @notice Getting stats from policy books, access: ANY /// @param policyBooks is list of PolicyBooks addresses function stats(address[] calldata policyBooks) external view returns (PolicyBookStats[] memory _stats); /// @notice Return existing Policy Book contract, access: ANY /// @param insuredContract is contract address to lookup for created IPolicyBook function policyBookFor(address insuredContract) external view returns (address); /// @notice Getting stats from policy books, access: ANY /// @param insuredContracts is list of insuredContracts in registry function statsByInsuredContracts(address[] calldata insuredContracts) external view returns (PolicyBookStats[] memory _stats); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface IRewardsGenerator { struct PolicyBookRewardInfo { uint256 rewardMultiplier; // includes 5 decimal places uint256 totalStaked; uint256 lastUpdateBlock; uint256 lastCumulativeSum; // includes 100 percentage uint256 cumulativeReward; // includes 100 percentage } struct StakeRewardInfo { uint256 lastCumulativeSum; // includes 100 percentage uint256 cumulativeReward; uint256 stakeAmount; } /// @notice this function is called every time policybook's STBL to bmiX rate changes function updatePolicyBookShare(uint256 newRewardMultiplier) external; /// @notice aggregates specified nfts into a single one function aggregate( address policyBookAddress, uint256[] calldata nftIndexes, uint256 nftIndexTo ) external; /// @notice migrates stake from the LegacyRewardsGenerator (will be called once for each user) /// the rewards multipliers must be set in advance function migrationStake( address policyBookAddress, uint256 nftIndex, uint256 amount, uint256 currentReward ) external; /// @notice informs generator of stake (rewards) function stake( address policyBookAddress, uint256 nftIndex, uint256 amount ) external; /// @notice returns policybook's APY multiplied by 10**5 function getPolicyBookAPY(address policyBookAddress) external view returns (uint256); /// @notice returns policybook's RewardMultiplier multiplied by 10**5 function getPolicyBookRewardMultiplier(address policyBookAddress) external view returns (uint256); /// @dev returns PolicyBook reward per block multiplied by 10**25 function getPolicyBookRewardPerBlock(address policyBookAddress) external view returns (uint256); /// @notice returns PolicyBook's staked STBL function getStakedPolicyBookSTBL(address policyBookAddress) external view returns (uint256); /// @notice returns NFT's staked STBL function getStakedNFTSTBL(uint256 nftIndex) external view returns (uint256); /// @notice returns a reward of NFT function getReward(address policyBookAddress, uint256 nftIndex) external view returns (uint256); /// @notice informs generator of withdrawal (all funds) function withdrawFunds(address policyBookAddress, uint256 nftIndex) external returns (uint256); /// @notice informs generator of withdrawal (rewards) function withdrawReward(address policyBookAddress, uint256 nftIndex) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface ISTKBMIToken is IERC20Upgradeable { function mint(address account, uint256 amount) external; function burn(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * COPIED FROM https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/tree/release-v3.4/contracts/drafts * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20PermitUpgradeable { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155MetadataURIUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.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 ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable 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}. */ function __ERC1155_init(string memory uri_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC1155_init_unchained(uri_); } function __ERC1155_init_unchained(string memory uri_) internal initializer { _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) 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 override returns (uint256) { require(account != address(0), "ERC1155: 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 override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { require(accounts[i] != address(0), "ERC1155: zero address"); batchBalances[i] = _balances[ids[i]][accounts[i]]; } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: self approval"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view 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: zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer failed" ); address operator = _msgSender(); _beforeTokenTransfer( operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data ); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance"); _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: length mismatch"); require(to != address(0), "ERC1155: zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer failed" ); 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"); _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 `to` 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: 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: zero address"); require(ids.length == amounts.length, "ERC1155: 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].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: length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 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 IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155ReceiverUpgradeable(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: non ERC1155Receiver"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived( operator, from, ids, amounts, data ) returns (bytes4 response) { if (response != IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: non ERC1155Receiver"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } uint256[47] private __gap; } // 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.6.0 <0.8.0; import "../GSN/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 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.6.0 <0.8.0; import "./IERC165Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.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 IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <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 {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC1155Upgradeable.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 IERC1155MetadataURIUpgradeable is IERC1155Upgradeable { /** * @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.6.0 <0.8.0; import "../../introspection/IERC165Upgradeable.sol"; /** * _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @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.6.2 <0.8.0; import "../../introspection/IERC165Upgradeable.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 IERC1155Upgradeable is IERC165Upgradeable { /** * @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.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.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, 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.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev 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 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) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (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(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(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(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.7.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--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } }
mappings function getPolicyBookAPY(address policyBookAddress) external view returns (uint256); SPDX-License-Identifier: MIT
interface IBMIStaking { event StakedBMI(uint256 stakedBMI, uint256 mintedStkBMI, address indexed recipient); event BMIWithdrawn(uint256 amountBMI, uint256 burnedStkBMI, address indexed recipient); event UnusedRewardPoolRevoked(address recipient, uint256 amount); event RewardPoolRevoked(address recipient, uint256 amount); function aggregateNFTs(address policyBookAddress, uint256[] calldata tokenIds) external; function stakeBMIX(uint256 amount, address policyBookAddress) external; function stakeBMIXWithPermit( uint256 bmiXAmount, address policyBookAddress, uint8 v, bytes32 r, bytes32 s ) external; function stakeBMIXFrom(address user, uint256 amount) external; function stakeBMIXFromWithPermit( address user, uint256 bmiXAmount, uint8 v, bytes32 r, bytes32 s ) external; function _stakersPool(uint256 index) external view returns (address policyBookAddress, uint256 stakedBMIXAmount); function restakeBMIProfit(uint256 tokenId) external; function restakeStakerBMIProfit(address policyBookAddress) external; function withdrawBMIProfit(uint256 tokenID) external; function withdrawStakerBMIProfit(address policyBookAddress) external; function withdrawFundsWithProfit(uint256 tokenID) external; function withdrawStakerFundsWithProfit(address policyBookAddress) external; function getSlashedBMIProfit(uint256 tokenId) external view returns (uint256); function getBMIProfit(uint256 tokenId) external view returns (uint256); function getSlashedStakerBMIProfit( address staker, address policyBookAddress, uint256 offset, uint256 limit ) external view returns (uint256 totalProfit); function getStakerBMIProfit( address staker, address policyBookAddress, uint256 offset, uint256 limit ) external view returns (uint256 totalProfit); function totalStaked(address user) external view returns (uint256); function totalStakedSTBL(address user) external view returns (uint256); function stakedByNFT(uint256 tokenId) external view returns (uint256); function stakedSTBLByNFT(uint256 tokenId) external view returns (uint256); function balanceOf(address user) external view returns (uint256); function ownerOf(uint256 tokenId) external view returns (address); function uri(uint256 tokenId) external view returns (string memory); function tokenOfOwnerByIndex(address user, uint256 index) external view returns (uint256); } pragma solidity ^0.7.4; import "./tokens/ISTKBMIToken.sol"; struct WithdrawalInfo { uint256 coolDownTimeEnd; uint256 amountBMIRequested; } }
5,976,622
[ 1, 16047, 445, 1689, 1590, 9084, 2203, 61, 12, 2867, 3329, 9084, 1887, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 11405, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 23450, 7492, 510, 6159, 288, 203, 565, 871, 934, 9477, 38, 7492, 12, 11890, 5034, 384, 9477, 38, 7492, 16, 2254, 5034, 312, 474, 329, 510, 79, 38, 7492, 16, 1758, 8808, 8027, 1769, 203, 565, 871, 605, 7492, 1190, 9446, 82, 12, 11890, 5034, 3844, 38, 7492, 16, 2254, 5034, 18305, 329, 510, 79, 38, 7492, 16, 1758, 8808, 8027, 1769, 203, 203, 565, 871, 1351, 3668, 17631, 1060, 2864, 10070, 14276, 12, 2867, 8027, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 534, 359, 1060, 2864, 10070, 14276, 12, 2867, 8027, 16, 2254, 5034, 3844, 1769, 203, 203, 565, 445, 7047, 50, 4464, 87, 12, 2867, 3329, 9084, 1887, 16, 2254, 5034, 8526, 745, 892, 1147, 2673, 13, 3903, 31, 203, 203, 565, 445, 384, 911, 38, 7492, 60, 12, 11890, 5034, 3844, 16, 1758, 3329, 9084, 1887, 13, 3903, 31, 203, 203, 565, 445, 384, 911, 38, 7492, 60, 1190, 9123, 305, 12, 203, 3639, 2254, 5034, 324, 9197, 60, 6275, 16, 203, 3639, 1758, 3329, 9084, 1887, 16, 203, 3639, 2254, 28, 331, 16, 203, 3639, 1731, 1578, 436, 16, 203, 3639, 1731, 1578, 272, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 384, 911, 38, 7492, 60, 1265, 12, 2867, 729, 16, 2254, 5034, 3844, 13, 3903, 31, 203, 203, 565, 445, 384, 911, 38, 7492, 60, 1265, 1190, 9123, 305, 12, 203, 3639, 1758, 729, 16, 203, 3639, 2254, 5034, 324, 9197, 60, 6275, 16, 203, 3639, 2254, 28, 331, 16, 203, 3639, 1731, 1578, 436, 2 ]
pragma solidity 0.5.11; pragma experimental ABIEncoderV2; import "./QuasarPool.sol"; import "../../src/framework/PlasmaFramework.sol"; import "../../src/exits/payment/PaymentExitGame.sol"; import "../../src/utils/PosLib.sol"; import "../../src/utils/Merkle.sol"; import "../../src/exits/utils/ExitId.sol"; import "../../src/exits/payment/routers/PaymentInFlightExitRouter.sol"; import "../../src/utils/SafeEthTransfer.sol"; import "../../src/transactions/PaymentTransactionModel.sol"; import "../../src/transactions/GenericTransaction.sol"; import "../../src/exits/utils/MoreVpFinalization.sol"; import "../../src/exits/interfaces/ISpendingCondition.sol"; import "../../src/exits/registries/SpendingConditionRegistry.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; /** * @title Quasar Contract * Implementation Doc - https://github.com/omgnetwork/research-workshop/blob/master/Incognito_fast_withdrawals.md */ contract Quasar is QuasarPool { using SafeERC20 for IERC20; using SafeMath for uint256; using SafeMath for uint64; using PosLib for PosLib.Position; PlasmaFramework public plasmaFramework; // This contract works with the current exit game // Any changes to the exit game would require modifications to this contract // Verify the exit game before interacting PaymentExitGame public paymentExitGame; SpendingConditionRegistry public spendingConditionRegistry; address public quasarOwner; uint256 public safeBlockMargin; uint256 public waitingPeriod; uint256 constant public TICKET_VALIDITY_PERIOD = 14400; uint256 constant public IFE_CLAIM_MARGIN = 28800; // 7+1 days waiting period for IFE Claims uint256 constant public IFE_CLAIM_WAITING_PERIOD = 691200; uint256 public bondValue; // bond is added to this reserve only when tickets are flushed, bond is returned every other time uint256 public unclaimedBonds; bool public isPaused; struct Ticket { address payable outputOwner; uint256 validityTimestamp; uint256 reservedAmount; address token; uint256 bondValue; bytes rlpOutputCreationTx; bool isClaimed; } struct Claim { bytes rlpClaimTx; uint256 finalizationTimestamp; bool isValid; } mapping (uint256 => Ticket) public ticketData; mapping (uint256 => Claim) private ifeClaimData; event NewTicketObtained(uint256 utxoPos); event IFEClaimSubmitted(uint256 utxoPos, uint168 exitId); modifier onlyQuasarMaintainer() { require(msg.sender == quasarMaintainer, "Only the Quasar Maintainer can invoke this method"); _; } modifier onlyWhenNotPaused() { require(!isPaused, "The Quasar contract is paused"); _; } /** * @dev Constructor, takes params to set up quasar contract * @param plasmaFrameworkContract Plasma Framework contract address * @param _quasarOwner Receiver address on Plasma * @param _safeBlockMargin The Quasar will not accept exits for outputs younger than the current plasma block minus the safe block margin * @param _waitingPeriod Waiting period from submission to processing claim * @param _bondValue bond to obtain tickets */ constructor ( address plasmaFrameworkContract, address spendingConditionRegistryContract, address _quasarOwner, uint256 _safeBlockMargin, uint256 _waitingPeriod, uint256 _bondValue ) public { plasmaFramework = PlasmaFramework(plasmaFrameworkContract); paymentExitGame = PaymentExitGame(plasmaFramework.exitGames(1)); spendingConditionRegistry = SpendingConditionRegistry(spendingConditionRegistryContract); quasarOwner = _quasarOwner; quasarMaintainer = msg.sender; safeBlockMargin = _safeBlockMargin; waitingPeriod = _waitingPeriod; bondValue = _bondValue; unclaimedBonds = 0; } /** * @return The latest safe block number */ function getLatestSafeBlock() public view returns(uint256) { uint256 childBlockInterval = plasmaFramework.childBlockInterval(); uint currentPlasmaBlock = plasmaFramework.nextChildBlock().sub(childBlockInterval); return currentPlasmaBlock.sub(safeBlockMargin.mul(childBlockInterval)); } //////////////////////////////////////////// // Maintenance methods //////////////////////////////////////////// /** * @dev Set the safe block margin. * @param margin the new safe block margin */ function setSafeBlockMargin (uint256 margin) public onlyQuasarMaintainer() { safeBlockMargin = margin; } /** * @dev Flush an expired ticket to free up reserved funds * @notice Only an unclaimed ticket can be flushed, bond amount is added to unclaimedBonds * @param utxoPos pos of the output, which is the ticket identifier */ function flushExpiredTicket(uint256 utxoPos) public { uint256 expiryTimestamp = ticketData[utxoPos].validityTimestamp; require(!ticketData[utxoPos].isClaimed, "The UTXO has already been claimed"); require(block.timestamp > expiryTimestamp && expiryTimestamp != 0, "Ticket still valid or doesn't exist"); uint256 tokenAmount = ticketData[utxoPos].reservedAmount; ticketData[utxoPos].reservedAmount = 0; ticketData[utxoPos].validityTimestamp = 0; tokenUsableCapacity[ticketData[utxoPos].token] = tokenUsableCapacity[ticketData[utxoPos].token].add(tokenAmount); unclaimedBonds = unclaimedBonds.add(ticketData[utxoPos].bondValue); } /** * @dev Pause contract in a byzantine state */ function pauseQuasar() public onlyQuasarMaintainer() { isPaused = true; } /** * @dev Unpause contract and allow tickets */ function resumeQuasar() public onlyQuasarMaintainer() { isPaused = false; } /** * @dev Withdraw Unclaimed bonds from the contract */ function withdrawUnclaimedBonds() public onlyQuasarMaintainer() { uint256 amount = unclaimedBonds; unclaimedBonds = 0; SafeEthTransfer.transferRevertOnError(msg.sender, amount, SAFE_GAS_STIPEND); } //////////////////////////////////////////// // Exit procedure //////////////////////////////////////////// /** * @dev Obtain a ticket from the Quasar * @notice Ticket is valid for four hours, pay bond here for obtaining ticket * @param utxoPos Output that will be spent to the quasar later, is the ticket identifier * @param rlpOutputCreationTx RLP-encoded transaction that created the output * @param outputCreationTxInclusionProof Transaction inclusion proof */ function obtainTicket(uint256 utxoPos, bytes memory rlpOutputCreationTx, bytes memory outputCreationTxInclusionProof) public payable onlyWhenNotPaused() { require(msg.value == bondValue, "Bond Value incorrect"); require(!ticketData[utxoPos].isClaimed, "The UTXO has already been claimed"); require(ticketData[utxoPos].validityTimestamp == 0, "This UTXO already has a ticket"); PosLib.Position memory utxoPosDecoded = PosLib.decode(utxoPos); require(utxoPosDecoded.blockNum <= getLatestSafeBlock(), "The UTXO is from a block later than the safe limit"); PaymentTransactionModel.Transaction memory decodedTx = PaymentTransactionModel.decode(rlpOutputCreationTx); FungibleTokenOutputModel.Output memory outputData = PaymentTransactionModel.getOutput(decodedTx, utxoPosDecoded.outputIndex); // verify the owner of output is obtaining the ticket require(verifyOwnership(outputData, msg.sender), "Was not called by the Output owner"); require(MoreVpFinalization.isStandardFinalized( plasmaFramework, rlpOutputCreationTx, utxoPosDecoded.toStrictTxPos(), outputCreationTxInclusionProof ), "Provided Tx doesn't exist"); require(outputData.amount <= tokenUsableCapacity[outputData.token], "Requested amount exceeds the Usable Liqudity"); require(outputData.amount != 0, "Requested amount cannot be zero"); tokenUsableCapacity[outputData.token] = tokenUsableCapacity[outputData.token].sub(outputData.amount); ticketData[utxoPos] = Ticket(msg.sender, block.timestamp.add(TICKET_VALIDITY_PERIOD), outputData.amount, outputData.token, msg.value, rlpOutputCreationTx, false); emit NewTicketObtained(utxoPos); } // for simplicity fee has to be from a seperate input in the tx to quasar /** * @dev Submit claim after spending the output to the quasar owner * @param utxoPos pos of the output, which is the ticket identifier * @param utxoPosQuasarOwner pos of the quasar owner's output * @param rlpTxToQuasarOwner RLP-encoded transaction that spends the output to quasar owner * @param txToQuasarOwnerInclusionProof Transaction Inclusion proof */ function claim( uint256 utxoPos, uint256 utxoPosQuasarOwner, bytes memory rlpTxToQuasarOwner, bytes memory txToQuasarOwnerInclusionProof ) public { verifyTicketValidityForClaim(utxoPos); verifyClaimTxCorrectlyFormed(utxoPos, rlpTxToQuasarOwner); PosLib.Position memory utxoQuasarOwnerDecoded = PosLib.decode(utxoPosQuasarOwner); require(MoreVpFinalization.isStandardFinalized( plasmaFramework, rlpTxToQuasarOwner, utxoQuasarOwnerDecoded.toStrictTxPos(), txToQuasarOwnerInclusionProof ), "Provided Tx doesn't exist"); ticketData[utxoPos].isClaimed = true; address payable outputOwner = ticketData[utxoPos].outputOwner; address token = ticketData[utxoPos].token; if (token == address(0)) { uint256 totalAmount = ticketData[utxoPos].reservedAmount.add(ticketData[utxoPos].bondValue); SafeEthTransfer.transferRevertOnError(outputOwner, totalAmount, SAFE_GAS_STIPEND); } else { IERC20(token).safeTransfer(outputOwner, ticketData[utxoPos].reservedAmount); SafeEthTransfer.transferRevertOnError(outputOwner, ticketData[utxoPos].bondValue, SAFE_GAS_STIPEND); } } /** * @dev Submit an IFE claim for claims without inclusion proof * @param utxoPos pos of the output, which is the ticket identifier * @param inFlightClaimTx in-flight tx that spends the output to quasar owner */ function ifeClaim(uint256 utxoPos, bytes memory inFlightClaimTx) public { verifyTicketValidityForClaim(utxoPos); verifyClaimTxCorrectlyFormed(utxoPos, inFlightClaimTx); //verify IFE started uint168 exitId = ExitId.getInFlightExitId(inFlightClaimTx); uint168[] memory exitIdArr = new uint168[](1); exitIdArr[0] = exitId; PaymentExitDataModel.InFlightExit[] memory ifeData = paymentExitGame.inFlightExits(exitIdArr); require(ifeData[0].exitStartTimestamp != 0, "IFE has not been started"); // IFE claims should start within IFE_CLAIM_MARGIN from starting IFE to enable sufficient time to piggyback // this might be overriden by the ticket expiry check usually, except if the ticket is obtained later require(block.timestamp <= ifeData[0].exitStartTimestamp.add(IFE_CLAIM_MARGIN), "IFE Claim period has passed"); ticketData[utxoPos].isClaimed = true; ifeClaimData[utxoPos] = Claim(inFlightClaimTx, block.timestamp.add(IFE_CLAIM_WAITING_PERIOD), true); emit IFEClaimSubmitted(utxoPos, exitId); } /** * @dev Challenge an IFE claim * @notice A challenge is required if any of the claimTx's inputs are double spent * @param utxoPos pos of the output, which is the ticket identifier * @param rlpChallengeTx RLP-encoded challenge transaction * @param challengeTxInputIndex index pos of the same utxo in the challenge transaction * @param challengeTxWitness Witness for challenging transaction * @param otherInputIndex (optional) index pos of another input from the claimTx that is spent * @param otherInputCreationTx (optional) Transaction that created this shared input * @param senderData A keccak256 hash of the sender's address */ function challengeIfeClaim( uint256 utxoPos, bytes memory rlpChallengeTx, uint16 challengeTxInputIndex, bytes memory challengeTxWitness, uint16 otherInputIndex, bytes memory otherInputCreationTx, bytes32 senderData ) public { require(senderData == keccak256(abi.encodePacked(msg.sender)), "Incorrect SenderData"); require(ticketData[utxoPos].isClaimed && ifeClaimData[utxoPos].isValid, "The claim is not challengeable"); require(block.timestamp <= ifeClaimData[utxoPos].finalizationTimestamp, "The challenge period is over"); require( keccak256(ifeClaimData[utxoPos].rlpClaimTx) != keccak256(rlpChallengeTx), "The challenging transaction is the same as the claim transaction" ); require(MoreVpFinalization.isProtocolFinalized( plasmaFramework, rlpChallengeTx ), "The challenging transaction is invalid"); if (otherInputCreationTx.length == 0) { verifySpendingCondition(utxoPos, ticketData[utxoPos].rlpOutputCreationTx, rlpChallengeTx, challengeTxInputIndex, challengeTxWitness); } else { PaymentTransactionModel.Transaction memory decodedTx = PaymentTransactionModel.decode(ifeClaimData[utxoPos].rlpClaimTx); verifySpendingCondition(uint256(decodedTx.inputs[otherInputIndex]), otherInputCreationTx, rlpChallengeTx, challengeTxInputIndex, challengeTxWitness); } ifeClaimData[utxoPos].isValid = false; Ticket memory ticket = ticketData[utxoPos]; tokenUsableCapacity[ticket.token] = tokenUsableCapacity[ticket.token].add(ticket.reservedAmount); SafeEthTransfer.transferRevertOnError(msg.sender, ticket.bondValue, SAFE_GAS_STIPEND); } /** * @dev Process the IFE claim to get liquid funds * @param utxoPos pos of the output, which is the ticket identifier */ function processIfeClaim(uint256 utxoPos) public { require(block.timestamp > ifeClaimData[utxoPos].finalizationTimestamp, "The claim is not finalized yet"); require(ifeClaimData[utxoPos].isValid, "The claim has already been claimed or challenged"); address payable outputOwner = ticketData[utxoPos].outputOwner; ifeClaimData[utxoPos].isValid = false; address token = ticketData[utxoPos].token; if (token == address(0)) { uint256 totalAmount = ticketData[utxoPos].reservedAmount.add(ticketData[utxoPos].bondValue); SafeEthTransfer.transferRevertOnError(outputOwner, totalAmount, SAFE_GAS_STIPEND); } else { IERC20(token).safeTransfer(outputOwner, ticketData[utxoPos].reservedAmount); SafeEthTransfer.transferRevertOnError(outputOwner, ticketData[utxoPos].bondValue, SAFE_GAS_STIPEND); } } //////////////////////////////////////////// // Helper methods //////////////////////////////////////////// /** * @dev Verify the owner of the output * @param output Output Data * @param expectedOutputOwner expected owner of the output */ function verifyOwnership(FungibleTokenOutputModel.Output memory output, address expectedOutputOwner) private pure returns(bool) { address outputOwner = PaymentTransactionModel.getOutputOwner(output); return outputOwner == expectedOutputOwner; } /** * @dev Verify the challengeTx spends the output * @param utxoPos pos of the output * @param rlpOutputCreationTx transaction that created the output * @param rlpChallengeTx RLP-encoded challenge transaction * @param challengeTxInputIndex index pos of the same utxo in the challenge transaction * @param challengeTxWitness Witness for challenging transaction */ function verifySpendingCondition(uint256 utxoPos, bytes memory rlpOutputCreationTx, bytes memory rlpChallengeTx, uint16 challengeTxInputIndex, bytes memory challengeTxWitness) private { GenericTransaction.Transaction memory challengingTx = GenericTransaction.decode(rlpChallengeTx); GenericTransaction.Transaction memory inputTx = GenericTransaction.decode(rlpOutputCreationTx); PosLib.Position memory utxoPosDecoded = PosLib.decode(utxoPos); GenericTransaction.Output memory output = GenericTransaction.getOutput(inputTx, utxoPosDecoded.outputIndex); ISpendingCondition condition = spendingConditionRegistry.spendingConditions( output.outputType, challengingTx.txType ); require(address(condition) != address(0), "Spending condition contract not found"); bool isSpent = condition.verify( rlpOutputCreationTx, utxoPos, rlpChallengeTx, challengeTxInputIndex, challengeTxWitness ); require(isSpent, "Spending condition failed"); } /** * @dev Verify the validity of the ticket * @param utxoPos pos of the output, which is the ticket identifier */ function verifyTicketValidityForClaim(uint256 utxoPos) private { require(!ticketData[utxoPos].isClaimed, "Already claimed"); require(ticketData[utxoPos].outputOwner == msg.sender, "Not called by the ticket owner"); uint256 expiryTimestamp = ticketData[utxoPos].validityTimestamp; require(expiryTimestamp != 0 && block.timestamp <= expiryTimestamp, "Ticket is not valid"); } /** * @dev Verify the claim Tx is properly formed * @param utxoPos pos of the output, which is the ticket identifier * @param claimTx the Claim Tx to the quasar owner */ function verifyClaimTxCorrectlyFormed(uint256 utxoPos, bytes memory claimTx) private { PaymentTransactionModel.Transaction memory decodedTx = PaymentTransactionModel.decode(claimTx); // first input should be the Utxo with which ticket was obtained require(decodedTx.inputs[0] == bytes32(utxoPos), "The claim transaction does not spend the correct output"); // first output should be the utxo for Quasar owner FungibleTokenOutputModel.Output memory outputData = PaymentTransactionModel.getOutput(decodedTx, 0); // verify output to Quasar Owner require(verifyOwnership(outputData, quasarOwner), "The output is not owned by the quasar owner"); // considering fee as a separate input require(ticketData[utxoPos].reservedAmount == outputData.amount, "Wrong amount sent to quasar owner"); require(ticketData[utxoPos].token == outputData.token, "Wrong token sent to quasar owner"); } }
// Helper methods//* @dev Verify the owner of the output @param output Output Data @param expectedOutputOwner expected owner of the output/
function verifyOwnership(FungibleTokenOutputModel.Output memory output, address expectedOutputOwner) private pure returns(bool) { address outputOwner = PaymentTransactionModel.getOutputOwner(output); return outputOwner == expectedOutputOwner; }
6,460,156
[ 1, 759, 9705, 2590, 759, 225, 8553, 326, 3410, 434, 326, 876, 225, 876, 3633, 1910, 225, 2665, 1447, 5541, 2665, 3410, 434, 326, 876, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3929, 5460, 12565, 12, 42, 20651, 1523, 1345, 1447, 1488, 18, 1447, 3778, 876, 16, 1758, 2665, 1447, 5541, 13, 3238, 16618, 1135, 12, 6430, 13, 288, 203, 3639, 1758, 876, 5541, 273, 12022, 3342, 1488, 18, 588, 1447, 5541, 12, 2844, 1769, 203, 3639, 327, 876, 5541, 422, 2665, 1447, 5541, 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 ]
./full_match/42161/0x049EdE31EAf1aC7ecA556E95E8dC7aBC31943178/sources/contracts/TheBullionGameArb.sol
Calculate 30% of the balance
uint256 depositAmount = (balance * 3) / 10;
16,306,690
[ 1, 8695, 5196, 9, 434, 326, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 443, 1724, 6275, 273, 261, 12296, 380, 890, 13, 342, 1728, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-02-13 */ // 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/interfaces/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC721Receiver.sol) pragma solidity ^0.8.0; // 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/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/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: @openzeppelin/contracts/interfaces/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC721Metadata.sol) pragma solidity ^0.8.0; // File: @openzeppelin/contracts/interfaces/IERC721.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC721.sol) pragma solidity ^0.8.0; // File: @openzeppelin/contracts/interfaces/IERC165.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; // File: @openzeppelin/contracts/interfaces/IERC2981.sol // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol) pragma solidity ^0.8.0; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * * _Available since v4.5._ */ interface IERC2981 is IERC165 { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // 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/access/IAccessControl.sol // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) 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; } // 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/interfaces/IERC1271.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * * _Available since v4.1._ */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // 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: github/nicole-air/testlove/contracts/erc/ERC721.sol pragma solidity ^0.8.7; /** * @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; // 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() { } /** * @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 ""; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return ""; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Mints `tokenId` and transfers it to `to`. * * * 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 Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // 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/access/AccessControl.sol // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; /** * @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 virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", 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 virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: github/nicole-air/testlove/contracts/pptl/PPTLBase.sol pragma solidity ^0.8.7; contract PPTLBase is ERC721, IERC2981, AccessControl, Ownable { // ======== Royalties ========= address private _royaltyAddress; uint256 private _royaltyPercent; /** * @dev Initializes the contract by setting a `default_admin` of the token access control. */ constructor(address default_admin) { _setupRole(DEFAULT_ADMIN_ROLE, default_admin); _royaltyAddress = address(this); _royaltyPercent = 6; } /** * @dev Returns the token collection name. */ function name() public view virtual override returns (string memory) { return "PeopleInThePlaceTheyLoveBase"; } /** * @dev Returns the token collection symbol */ function symbol() public view virtual override returns (string memory) { return "PPTLBase"; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl, ERC721, IERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Set royalty info for all tokens * @param royaltyReceiver address to receive royalty fee * @param royaltyPercentage percentage of royalty fee * * Requirements: * * - the caller must have the contract owner. */ function setRoyaltyInfo(address royaltyReceiver, uint256 royaltyPercentage) public onlyOwner { require(royaltyPercentage <= 100, "PPTL: RoyaltyPercentage exceed"); _royaltyAddress = royaltyReceiver; _royaltyPercent = royaltyPercentage; } /** * @dev See {IERC2981-royaltyInfo}. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view override returns (address receiver, uint256 royaltyAmount){ require(_exists(tokenId), "PPTL: Query royalty info for non-existent token"); return (_royaltyAddress, (salePrice * _royaltyPercent) / 100); } } // File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // File: @openzeppelin/contracts/utils/cryptography/SignatureChecker.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/SignatureChecker.sol) pragma solidity ^0.8.0; /** * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like * Argent and Gnosis Safe. * * _Available since v4.1._ */ library SignatureChecker { /** * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`. * * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus * change through time. It could return true at block N and false at block N+1 (or the opposite). */ function isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature); if (error == ECDSA.RecoverError.NoError && recovered == signer) { return true; } (bool success, bytes memory result) = signer.staticcall( abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature) ); return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector); } } // File: github/nicole-air/testlove/contracts/testlove/TESTLOVE.sol pragma solidity ^0.8.7; contract TESTLOVE is PPTLBase { using Strings for uint256; // ======================== Access Control ========================= bytes32 internal constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 internal constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); bytes32 internal constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE"); // ================ Lucky Draw ================ struct UserTier { uint256 startTime; uint256 duration; uint256 ticketMaxNum; uint256 ticketPrice; mapping(address => uint256) users; } mapping(uint256 => UserTier) private _userTiers; bool public luckyDrawActive; // ===== Provenance ====== bytes32 public provenance; // ======= Burning ========= bool public isBurningActive; // ======= Supply ========= uint256 public maxSupply; uint256 public totalSupply; // ===== Metadata ====== string private _baseURI; // ====== Signature ======= address private _authority; // === Marketplace ==== address private _payee; // =================== Events ==================== event PaymentReceived(address from, uint256 amount); event BalancePayout(address recipient, uint256 amount); /** * @dev Constructor function * @param default_admin access control default_admin * @param authority signature authority * @param payee lucky draw Ether receiver * @param maxSupply_ token max supply */ constructor(address default_admin, address authority, address payee, uint256 maxSupply_) PPTLBase(default_admin) { _authority = authority; _payee = payee; maxSupply = maxSupply_; } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. */ receive() external payable { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Returns the token collection name. */ function name() public view virtual override returns (string memory) { return "TESTLOVE"; } /** * @dev Returns the token collection symbol */ function symbol() public view virtual override returns (string memory) { return "TESTLOVE"; } /** * @dev Sets base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. * @param baseURI base URI to set * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function setBaseURI(string memory baseURI) external onlyRole(MINTER_ROLE) { require(bytes(_baseURI).length == 0, "PPTL: BaseURI already set"); _baseURI = baseURI; } /** * @dev Returns the URI for a given token ID * Throws if the token ID does not exist. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if (bytes(_baseURI).length > 0) return string(abi.encodePacked(_baseURI, tokenId.toString())); return string(abi.encodePacked("https://raffle.thefwenclub.com/token/", tokenId.toString())); } /** * @dev Toggles burning active flag * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function toggleBurningActive() external onlyRole(MINTER_ROLE) { isBurningActive = !isBurningActive; } /** * @dev Destroys `tokenId`. * Throws if the caller is not token owner or approved * @param tokenId uint256 ID of the token to be destroyed */ function burn(uint256 tokenId) external { require(isBurningActive && !luckyDrawActive, "PPTL: Burning not active"); require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: Caller not owner or approved"); _burn(tokenId); } /** * @dev Toggles lucky draw active flag * * Requirements: * * - the caller must have the `OPERATOR_ROLE`. */ function toggleLuckydrawActive() external onlyRole(OPERATOR_ROLE) { luckyDrawActive = !luckyDrawActive; } /** * @dev Creates a new token for every address in `tos`. TokenIDs will be automatically assigned * @param tos owners of new tokens * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function privateMint(address[] memory tos) external onlyRole(MINTER_ROLE) { require(!luckyDrawActive, "PPTL: Lucky draw has begun"); for (uint256 i = 0; i < tos.length; i++) { _mint(tos[i], totalSupply + 1 + i); } totalSupply += tos.length; require(totalSupply <= maxSupply, "PPTL: Exceed max supply"); } /** * @dev Creates lucky draw provenance and user tiers * @param provenance_ provenance of lucky draw token metadatas * @param userTierIds ids of user tiers in lucky draw * @param userTierStartTimes start times of user tiers in lucky draw * @param userTierDurations durations of user tiers in lucky draw * @param userTierTicketMaxNums max ticket numbers per user of user tiers in lucky draw * @param userTierTicketPrices ticket prices of user tiers in lucky draw * * Requirements: * * - the caller must have the `OPERATOR_ROLE`. */ function createLuckyDraw( bytes32 provenance_, uint256[] memory userTierIds, uint256[] memory userTierStartTimes, uint256[] memory userTierDurations, uint256[] memory userTierTicketMaxNums, uint256[] memory userTierTicketPrices ) external onlyRole(OPERATOR_ROLE) { require(!luckyDrawActive, "PPTL: Lucky draw has begun"); require( userTierIds.length == userTierStartTimes.length && userTierIds.length == userTierDurations.length && userTierIds.length == userTierTicketMaxNums.length && userTierIds.length == userTierTicketPrices.length, "PPTL: array length mismatch" ); provenance = provenance_; for (uint256 i = 0; i < userTierIds.length; i++) { _userTiers[userTierIds[i]].startTime = userTierStartTimes[i]; _userTiers[userTierIds[i]].duration = userTierDurations[i]; _userTiers[userTierIds[i]].ticketMaxNum = userTierTicketMaxNums[i]; _userTiers[userTierIds[i]].ticketPrice = userTierTicketPrices[i]; } } /** * @dev Creates new token(s) for valid caller. TokenID(s) will be automatically assigned * * @param userTierId user tier id of caller belonged to * @param ticketNum number of tokens to create * @param signature signature from `_authority` */ function draw(uint256 userTierId, uint256 ticketNum, bytes memory signature) external payable { require(luckyDrawActive, "PPTL: Lucky draw inactive"); uint256 startTime = _userTiers[userTierId].startTime; uint256 endTime = startTime + _userTiers[userTierId].duration * 1 seconds; require(block.timestamp >= startTime && block.timestamp < endTime, "PPTL: Invalid time"); bytes32 data = keccak256(abi.encode(address(this), _msgSender(), userTierId)); require(SignatureChecker.isValidSignatureNow(_authority, data, signature), "PPTL: Invalid signature"); uint256 newSupply = totalSupply + ticketNum; require(newSupply <= maxSupply, "PPTL: Exceed max supply"); uint256 newTicketNum = _userTiers[userTierId].users[_msgSender()] + ticketNum; require(newTicketNum <= _userTiers[userTierId].ticketMaxNum, "PPTL: Exceed max ticket num"); _userTiers[userTierId].users[_msgSender()] = newTicketNum; require(msg.value == _userTiers[userTierId].ticketPrice * ticketNum, "PPTL: Incorrect payment"); (bool sent, ) = _payee.call{value: msg.value}(""); require(sent, "PPTL: Failed to send Ether"); for (uint256 i = 0; i < ticketNum; i++) { _mint(_msgSender(), totalSupply + i + 1); } totalSupply = newSupply; } /** * @dev Payouts contract balance * * @param recipients addresses to receive Ether * @param fractions percentages of recipients receiving Ether * * Requirements: * * - the caller must have the `WITHDRAW_ROLE`. */ function payout(address[] memory recipients, uint96[] memory fractions) external onlyRole(WITHDRAW_ROLE) { require(recipients.length == fractions.length, "PPTL: Array length mismatch"); uint256 balance = address(this).balance; require(balance > 0, "PPTL: Invalid contract balance to payout"); uint256 counter = 0; for (uint256 i = 0; i < recipients.length; i++) { require(recipients[i] != address(0), "PPTL: Invalid payout recipient"); counter += fractions[i]; uint256 amount = balance * fractions[i] / 100; (bool success, ) = recipients[i].call{value: amount}(""); require(success, "PPTL: Failed to send Ether"); emit BalancePayout(recipients[i], amount); } require(counter <= 100, "PPTL: Invalid payout"); } }
* @dev Returns the URI for a given token ID Throws if the token ID does not exist. @param tokenId uint256 ID of the token to query/
function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if (bytes(_baseURI).length > 0) return string(abi.encodePacked(_baseURI, tokenId.toString())); }
6,790,739
[ 1, 1356, 326, 3699, 364, 279, 864, 1147, 1599, 22435, 309, 326, 1147, 1599, 1552, 486, 1005, 18, 225, 1147, 548, 2254, 5034, 1599, 434, 326, 1147, 358, 843, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 2583, 24899, 1808, 12, 2316, 548, 3631, 315, 654, 39, 27, 5340, 2277, 30, 3699, 843, 364, 1661, 19041, 1147, 8863, 203, 3639, 309, 261, 3890, 24899, 1969, 3098, 2934, 2469, 405, 374, 13, 203, 5411, 327, 533, 12, 21457, 18, 3015, 4420, 329, 24899, 1969, 3098, 16, 1147, 548, 18, 10492, 1435, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x02973B7048B4827fFc388249CD8d7a6C7A6F491A/sources/blockbet/blockbet.sol
Where the bet should be evaluated
uint evaluateAtBlock;
14,183,017
[ 1, 5262, 326, 2701, 1410, 506, 12697, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5956, 861, 1768, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.1; interface IMoonCatReference { function doc (address contractAddress) external view returns (string memory name, string memory description, string memory details); function setDoc (address contractAddress, string calldata name, string calldata description) external; } interface IMoonCatTraits { function kTraitsOf (bytes5 catId) external view returns (bool genesis, bool pale, uint8 facing, uint8 expression, uint8 pattern, uint8 pose); } interface IMoonCatColors { function BasePalette (uint index) external view returns (uint8); function colorsOf (bytes5 catId) external view returns (uint8[24] memory); function accessoryColorsOf (bytes5 catId) external view returns (uint8[45] memory); function colorAlpha (uint8 id) external pure returns (uint8); } interface IMoonCatSVGs { function flip (bytes memory svgData) external pure returns (bytes memory); function getPixelData (uint8 facing, uint8 expression, uint8 pose, uint8 pattern, uint8[24] memory colors) external view returns (bytes memory); function boundingBox (uint8 facing, uint8 pose) external view returns (uint8 x, uint8 y, uint8 width, uint8 height); function glowGroup (bytes memory pixels, uint8 r, uint8 g, uint8 b) external pure returns (bytes memory); function svgTag (uint8 x, uint8 y, uint8 w, uint8 h) external pure returns (bytes memory); function uint2str (uint value) external pure returns (string memory); } interface IMoonCatRescue { function rescueOrder(uint256 tokenId) external view returns (bytes5); function catOwners(bytes5 catId) external view returns (address); } interface IMoonCatAccessories { function accessoryImageData (uint256 accessoryId) external view returns (bytes2[4] memory positions, bytes8[7] memory palettes, uint8 width, uint8 height, uint8 meta, bytes memory IDAT); function doesMoonCatOwnAccessory (uint256 rescueOrder, uint256 accessoryId) external view returns (bool); function balanceOf (uint256 rescueOrder) external view returns (uint256); struct OwnedAccessory { uint232 accessoryId; uint8 paletteIndex; uint16 zIndex; } function ownedAccessoryByIndex (uint256 rescueOrder, uint256 ownedAccessoryIndex) external view returns (OwnedAccessory memory); } interface IMoonCatSVGS { function imageOfExtended (bytes5 catId, bytes memory pre, bytes memory post) external view returns (string memory); } interface IReverseResolver { function claim(address owner) external returns (bytes32); } interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); } interface IERC721 { function safeTransferFrom(address from, address to, uint256 tokenId) external; function ownerOf(uint256 tokenId) external view returns (address); } library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } } /** * @title AccessoryPNGs * @notice On Chain MoonCat Accessory Image Generation * @dev Builds PNGs of MoonCat Accessories */ contract MoonCatAccessoryImages { /* External Contracts */ IMoonCatRescue MoonCatRescue = IMoonCatRescue(0x60cd862c9C687A9dE49aecdC3A99b74A4fc54aB6); IMoonCatAccessories MoonCatAccessories = IMoonCatAccessories(0x8d33303023723dE93b213da4EB53bE890e747C63); IMoonCatReference MoonCatReference; IMoonCatTraits MoonCatTraits; IMoonCatColors MoonCatColors; IMoonCatSVGs MoonCatSVGs; address MoonCatAcclimatorAddress = 0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69; /* CRC */ uint32[256] CRCTable = [0x0,0x77073096,0xee0e612c,0x990951ba,0x76dc419,0x706af48f,0xe963a535,0x9e6495a3,0xedb8832,0x79dcb8a4,0xe0d5e91e,0x97d2d988,0x9b64c2b,0x7eb17cbd,0xe7b82d07,0x90bf1d91,0x1db71064,0x6ab020f2,0xf3b97148,0x84be41de,0x1adad47d,0x6ddde4eb,0xf4d4b551,0x83d385c7,0x136c9856,0x646ba8c0,0xfd62f97a,0x8a65c9ec,0x14015c4f,0x63066cd9,0xfa0f3d63,0x8d080df5,0x3b6e20c8,0x4c69105e,0xd56041e4,0xa2677172,0x3c03e4d1,0x4b04d447,0xd20d85fd,0xa50ab56b,0x35b5a8fa,0x42b2986c,0xdbbbc9d6,0xacbcf940,0x32d86ce3,0x45df5c75,0xdcd60dcf,0xabd13d59,0x26d930ac,0x51de003a,0xc8d75180,0xbfd06116,0x21b4f4b5,0x56b3c423,0xcfba9599,0xb8bda50f,0x2802b89e,0x5f058808,0xc60cd9b2,0xb10be924,0x2f6f7c87,0x58684c11,0xc1611dab,0xb6662d3d,0x76dc4190,0x1db7106,0x98d220bc,0xefd5102a,0x71b18589,0x6b6b51f,0x9fbfe4a5,0xe8b8d433,0x7807c9a2,0xf00f934,0x9609a88e,0xe10e9818,0x7f6a0dbb,0x86d3d2d,0x91646c97,0xe6635c01,0x6b6b51f4,0x1c6c6162,0x856530d8,0xf262004e,0x6c0695ed,0x1b01a57b,0x8208f4c1,0xf50fc457,0x65b0d9c6,0x12b7e950,0x8bbeb8ea,0xfcb9887c,0x62dd1ddf,0x15da2d49,0x8cd37cf3,0xfbd44c65,0x4db26158,0x3ab551ce,0xa3bc0074,0xd4bb30e2,0x4adfa541,0x3dd895d7,0xa4d1c46d,0xd3d6f4fb,0x4369e96a,0x346ed9fc,0xad678846,0xda60b8d0,0x44042d73,0x33031de5,0xaa0a4c5f,0xdd0d7cc9,0x5005713c,0x270241aa,0xbe0b1010,0xc90c2086,0x5768b525,0x206f85b3,0xb966d409,0xce61e49f,0x5edef90e,0x29d9c998,0xb0d09822,0xc7d7a8b4,0x59b33d17,0x2eb40d81,0xb7bd5c3b,0xc0ba6cad,0xedb88320,0x9abfb3b6,0x3b6e20c,0x74b1d29a,0xead54739,0x9dd277af,0x4db2615,0x73dc1683,0xe3630b12,0x94643b84,0xd6d6a3e,0x7a6a5aa8,0xe40ecf0b,0x9309ff9d,0xa00ae27,0x7d079eb1,0xf00f9344,0x8708a3d2,0x1e01f268,0x6906c2fe,0xf762575d,0x806567cb,0x196c3671,0x6e6b06e7,0xfed41b76,0x89d32be0,0x10da7a5a,0x67dd4acc,0xf9b9df6f,0x8ebeeff9,0x17b7be43,0x60b08ed5,0xd6d6a3e8,0xa1d1937e,0x38d8c2c4,0x4fdff252,0xd1bb67f1,0xa6bc5767,0x3fb506dd,0x48b2364b,0xd80d2bda,0xaf0a1b4c,0x36034af6,0x41047a60,0xdf60efc3,0xa867df55,0x316e8eef,0x4669be79,0xcb61b38c,0xbc66831a,0x256fd2a0,0x5268e236,0xcc0c7795,0xbb0b4703,0x220216b9,0x5505262f,0xc5ba3bbe,0xb2bd0b28,0x2bb45a92,0x5cb36a04,0xc2d7ffa7,0xb5d0cf31,0x2cd99e8b,0x5bdeae1d,0x9b64c2b0,0xec63f226,0x756aa39c,0x26d930a,0x9c0906a9,0xeb0e363f,0x72076785,0x5005713,0x95bf4a82,0xe2b87a14,0x7bb12bae,0xcb61b38,0x92d28e9b,0xe5d5be0d,0x7cdcefb7,0xbdbdf21,0x86d3d2d4,0xf1d4e242,0x68ddb3f8,0x1fda836e,0x81be16cd,0xf6b9265b,0x6fb077e1,0x18b74777,0x88085ae6,0xff0f6a70,0x66063bca,0x11010b5c,0x8f659eff,0xf862ae69,0x616bffd3,0x166ccf45,0xa00ae278,0xd70dd2ee,0x4e048354,0x3903b3c2,0xa7672661,0xd06016f7,0x4969474d,0x3e6e77db,0xaed16a4a,0xd9d65adc,0x40df0b66,0x37d83bf0,0xa9bcae53,0xdebb9ec5,0x47b2cf7f,0x30b5ffe9,0xbdbdf21c,0xcabac28a,0x53b39330,0x24b4a3a6,0xbad03605,0xcdd70693,0x54de5729,0x23d967bf,0xb3667a2e,0xc4614ab8,0x5d681b02,0x2a6f2b94,0xb40bbe37,0xc30c8ea1,0x5a05df1b,0x2d02ef8d]; /** * @dev Create a cyclic redundancy check (CRC) value for a given set of data. * * This is the error-detecting code used for the PNG data format to validate each chunk of data within the file. This Solidity implementation * is needed to be able to dynamically create PNG files piecemeal. */ function crc32 (bytes memory data) public view returns (uint32) { uint32 crc = type(uint32).max; for (uint i = 0; i < data.length; i++) { uint8 byt; assembly { byt := mload(add(add(data, 0x1), i)) } crc = (crc >> 8) ^ CRCTable[(crc & 255) ^ byt]; } return ~crc; } /* accessoryPNGs */ uint64 constant public PNGHeader = 0x89504e470d0a1a0a; uint96 constant public PNGFooter = 0x0000000049454e44ae426082; uint40 constant internal IHDRDetails = 0x0803000000; /** * @dev Assemble a block of data into a valid PNG file chunk. */ function generatePNGChunk (string memory typeCode, bytes memory data) public view returns (bytes memory) { uint32 crc = crc32(abi.encodePacked(typeCode, data)); return abi.encodePacked(uint32(data.length), typeCode, data, crc); } /** * @dev Take metadata about an individual Accessory and the MoonCat wearing it, and render the Accessory as a PNG image. */ function assemblePNG (uint8[45] memory accessoryColors, bytes8 palette, uint8 width, uint8 height, bytes memory IDAT) internal view returns (bytes memory) { bytes memory colors = new bytes(27); bytes memory alphas = new bytes(9); for (uint i = 0; i < 8; i++) { uint256 colorIndex = uint256(uint8(palette[i])); alphas[i + 1] = bytes1(MoonCatColors.colorAlpha(uint8(colorIndex))); if (colorIndex > 113) { colorIndex = (colorIndex - 113) * 3; colors[i * 3 + 3] = bytes1(accessoryColors[colorIndex]); colors[i * 3 + 4] = bytes1(accessoryColors[colorIndex + 1]); colors[i * 3 + 5] = bytes1(accessoryColors[colorIndex + 2]); } else { colorIndex = colorIndex * 3; colors[i * 3 + 3] = bytes1(MoonCatColors.BasePalette(colorIndex)); colors[i * 3 + 4] = bytes1(MoonCatColors.BasePalette(colorIndex + 1)); colors[i * 3 + 5] = bytes1(MoonCatColors.BasePalette(colorIndex + 2)); } } return abi.encodePacked(PNGHeader, generatePNGChunk("IHDR", abi.encodePacked(uint32(width), uint32(height), IHDRDetails)), generatePNGChunk("PLTE", colors),//abi.encodePacked(colors)), generatePNGChunk("tRNS", alphas), generatePNGChunk("IDAT", IDAT), PNGFooter); } /** * @dev For a given MoonCat rescue order and Accessory ID and palette ID, render as PNG. * The PNG output is converted to a base64-encoded blob, which is the format used for encoding into an SVG or inline HTML. */ function accessoryPNG (uint256 rescueOrder, uint256 accessoryId, uint16 paletteIndex) public view returns (string memory) { require(rescueOrder < 25440, "Invalid Rescue Order"); bytes5 catId = MoonCatRescue.rescueOrder(rescueOrder); uint8[45] memory accessoryColors = MoonCatColors.accessoryColorsOf(catId); (,bytes8[7] memory palettes, uint8 width, uint8 height,,bytes memory IDAT) = MoonCatAccessories.accessoryImageData(accessoryId); return string(abi.encodePacked("data:image/png;base64,", Base64.encode(assemblePNG(accessoryColors, palettes[paletteIndex], width, height, IDAT)))); } /* Composite */ struct PreppedAccessory { uint16 zIndex; uint8 offsetX; uint8 offsetY; uint8 width; uint8 height; bool mirror; bool background; bytes8 palette; bytes IDAT; } /** * @dev Given a list of accessories, sort them by z-index. */ function sortAccessories(PreppedAccessory[] memory pas) internal pure { for (uint i = 1; i < pas.length; i++) { PreppedAccessory memory pa = pas[i]; uint key = pa.zIndex; uint j = i; while (j > 0 && pas[j - 1].zIndex > key) { pas[j] = pas[j - 1]; j--; } pas[j] = pa; } } /** * @dev Given a MoonCat and accessory's basic information, derive colors and other metadata for them. */ function prepAccessory (uint8 facing, uint8 pose, bool allowUnverified, IMoonCatAccessories.OwnedAccessory memory accessory) internal view returns (PreppedAccessory memory) { (bytes2[4] memory positions, bytes8[7] memory palettes, uint8 width, uint8 height, uint8 meta, bytes memory IDAT) = MoonCatAccessories.accessoryImageData(accessory.accessoryId); bytes2 position = positions[pose]; uint8 offsetX = uint8(position[0]); uint8 offsetY = uint8(position[1]); bool mirror; if (facing == 1) { mirror = ((meta >> 1) & 1) == 1; if (((meta >> 2) & 1) == 1) { // mirrorPlacement if (!mirror) { offsetX = 128 - offsetX - width; } } else if (mirror) { offsetX = 128 - offsetX - width; } } uint16 zIndex = accessory.zIndex; if (!allowUnverified) { zIndex = zIndex * (meta >> 7); // check for approval } return PreppedAccessory(zIndex, offsetX, offsetY, width, height, mirror, (meta & 1) == 1, // background palettes[accessory.paletteIndex], IDAT); } /** * @dev Given a MoonCat and a set of basic Accessories' information, derive their metadata and split into foreground/background lists. */ function prepAccessories (uint256 rescueOrder, uint8 facing, uint8 pose, bool allowUnverified, IMoonCatAccessories.OwnedAccessory[] memory accessories) public view returns (PreppedAccessory[] memory, PreppedAccessory[] memory) { PreppedAccessory[] memory preppedAccessories = new PreppedAccessory[](accessories.length); uint bgCount = 0; uint fgCount = 0; for (uint i = 0; i < accessories.length; i++) { IMoonCatAccessories.OwnedAccessory memory accessory = accessories[i]; require(MoonCatAccessories.doesMoonCatOwnAccessory(rescueOrder, accessory.accessoryId), "Accessory Not Owned By MoonCat"); if (accessory.zIndex > 0) { preppedAccessories[i] = prepAccessory(facing, pose, allowUnverified, accessory); if (preppedAccessories[i].background) { bgCount++; } else { fgCount++; } } } PreppedAccessory[] memory background = new PreppedAccessory[](bgCount); PreppedAccessory[] memory foreground = new PreppedAccessory[](fgCount); bgCount = 0; fgCount = 0; for (uint i = 0; i < preppedAccessories.length; i++) { if (preppedAccessories[i].zIndex > 0) { if (preppedAccessories[i].background) { background[bgCount] = preppedAccessories[i]; bgCount++; } else { foreground[fgCount] = preppedAccessories[i]; fgCount++; } } } sortAccessories(background); sortAccessories(foreground); return (background, foreground); } /** * @dev Convert a MoonCat facing and pose trait information into an SVG viewBox definition to set that canvas size. */ function initialBoundingBox (uint8 facing, uint8 pose) internal view returns (uint8, uint8, uint8, uint8) { (uint8 x1, uint8 y1, uint8 width, uint8 height) = MoonCatSVGs.boundingBox(facing, pose); return (x1, y1, x1 + width, y1 + height); } /** * @dev Given a MoonCat's pose information and a list of Accessories, calculate a bounding box that will cover them all. */ function getBoundingBox (uint8 facing, uint8 pose, PreppedAccessory[] memory background, PreppedAccessory[] memory foreground) internal view returns (uint8, uint8, uint8, uint8) { (uint8 x1, uint8 y1, uint8 x2, uint8 y2) = initialBoundingBox(facing, pose); uint8 offsetX; for (uint i = 0; i < background.length; i++) { PreppedAccessory memory pa = background[i]; if (pa.zIndex > 0) { if (pa.mirror) { offsetX = 128 - pa.offsetX - pa.width; } else { offsetX = pa.offsetX; } if (offsetX < x1) x1 = offsetX; if (pa.offsetY < y1) y1 = pa.offsetY; if ((offsetX + pa.width) > x2) x2 = offsetX + pa.width; if ((pa.offsetY + pa.height) > y2) y2 = pa.offsetY + pa.height; } } for (uint i = 0; i < foreground.length; i++) { PreppedAccessory memory pa = foreground[i]; if (pa.zIndex > 0) { if (pa.mirror) { offsetX = 128 - pa.offsetX - pa.width; } else { offsetX = pa.offsetX; } if (offsetX < x1) x1 = offsetX; if (pa.offsetY < y1) y1 = pa.offsetY; if ((offsetX + pa.width) > x2) x2 = offsetX + pa.width; if ((pa.offsetY + pa.height) > y2) y2 = pa.offsetY + pa.height; } } return (x1, y1, x2 - x1, y2 - y1); } /** * @dev Given an Accessory's metadata, generate a PNG image of that Accessory and wrap in an SVG image object. */ function accessorySVGSnippet (PreppedAccessory memory pa, uint8[45] memory accessoryColors) internal view returns (bytes memory) { bytes memory img = assemblePNG(accessoryColors, pa.palette, pa.width, pa.height, pa.IDAT); bytes memory snippet = abi.encodePacked("<image x=\"", MoonCatSVGs.uint2str(pa.offsetX), "\" y=\"", MoonCatSVGs.uint2str(pa.offsetY), "\" width=\"", MoonCatSVGs.uint2str(pa.width), "\" height=\"", MoonCatSVGs.uint2str(pa.height), "\" href=\"data:image/png;base64,", Base64.encode(img), "\"/>"); if (pa.mirror) { return MoonCatSVGs.flip(snippet); } return snippet; } /** * @dev Given a set of metadata about MoonCat and desired Accessories to render on it, generate an SVG of that appearance. */ function assembleSVG (uint8 x, uint8 y, uint8 width, uint8 height, bytes memory mooncatPixelData, uint8[45] memory accessoryColors, PreppedAccessory[] memory background, PreppedAccessory[] memory foreground, uint8 glowLevel) internal view returns (string memory) { bytes memory bg; bytes memory fg; for (uint i = background.length; i >= 1; i--) { bg = abi.encodePacked(bg, accessorySVGSnippet(background[i - 1], accessoryColors)); } for (uint i = 0; i < foreground.length; i++) { fg = abi.encodePacked(fg, accessorySVGSnippet(foreground[i], accessoryColors)); } if (glowLevel == 0) { return string(abi.encodePacked(MoonCatSVGs.svgTag(x, y, width, height), bg, mooncatPixelData, fg, "</svg>")); } else if (glowLevel == 1) { return string(abi.encodePacked(MoonCatSVGs.svgTag(x, y, width, height), MoonCatSVGs.glowGroup(mooncatPixelData, accessoryColors[0], accessoryColors[1], accessoryColors[2]), bg, mooncatPixelData, fg, "</svg>")); } else { return string(abi.encodePacked(MoonCatSVGs.svgTag(x, y, width, height), MoonCatSVGs.glowGroup(abi.encodePacked(bg, mooncatPixelData, fg), accessoryColors[0], accessoryColors[1], accessoryColors[2]), "</svg>")); } } /** * @dev Given a set of metadata about MoonCat and desired Accessories to render on it, generate an SVG of that appearance. */ function assembleSVG (uint8 facing, uint8 pose, bytes memory mooncatPixelData, uint8[45] memory accessoryColors, PreppedAccessory[] memory background, PreppedAccessory[] memory foreground, uint8 glowLevel) internal view returns (string memory) { (uint8 x, uint8 y, uint8 width, uint8 height) = getBoundingBox(facing, pose, background, foreground); return assembleSVG(x, y, width, height, mooncatPixelData, accessoryColors, background, foreground, glowLevel); } /** * @dev Given a MoonCat Rescue Order and a list of Accessories they own, render an SVG of them wearing those accessories. */ function accessorizedImageOf (uint256 rescueOrder, IMoonCatAccessories.OwnedAccessory[] memory accessories, uint8 glowLevel, bool allowUnverified) public view returns (string memory) { uint8 facing; uint8 pose; bytes memory mooncatPixelData; uint8[45] memory accessoryColors; { require(rescueOrder < 25440, "Invalid Rescue Order"); bytes5 catId = MoonCatRescue.rescueOrder(rescueOrder); uint8[24] memory colors = MoonCatColors.colorsOf(catId); { uint8 expression; uint8 pattern; (,, facing, expression, pattern, pose) = MoonCatTraits.kTraitsOf(catId); mooncatPixelData = MoonCatSVGs.getPixelData(facing, expression, pose, pattern, colors); } accessoryColors = MoonCatColors.accessoryColorsOf(catId); } (PreppedAccessory[] memory background, PreppedAccessory[] memory foreground) = prepAccessories(rescueOrder, facing, pose, allowUnverified, accessories); return assembleSVG(facing, pose, mooncatPixelData, accessoryColors, background, foreground, glowLevel); } /** * @dev Given a MoonCat Rescue Order, look up what Accessories they are currently wearing, and render an SVG of them wearing those accessories. */ function accessorizedImageOf (uint256 rescueOrder, uint8 glowLevel, bool allowUnverified) public view returns (string memory) { uint accessoryCount = MoonCatAccessories.balanceOf(rescueOrder); IMoonCatAccessories.OwnedAccessory[] memory accessories = new IMoonCatAccessories.OwnedAccessory[](accessoryCount); for (uint i = 0; i < accessoryCount; i++) { accessories[i] = MoonCatAccessories.ownedAccessoryByIndex(rescueOrder, i); } return accessorizedImageOf(rescueOrder, accessories, glowLevel, allowUnverified); } /** * @dev Given a MoonCat Rescue Order, look up what verified Accessories they are currently wearing, and render an SVG of them wearing those accessories. */ function accessorizedImageOf (uint256 rescueOrder, uint8 glowLevel) public view returns (string memory) { return accessorizedImageOf(rescueOrder, glowLevel, false); } /** * @dev Given a MoonCat Rescue Order, look up what verified Accessories they are currently wearing, and render an unglowing SVG of them wearing those accessories. */ function accessorizedImageOf (uint256 rescueOrder) public view returns (string memory) { return accessorizedImageOf(rescueOrder, 0, false); } /** * @dev Given a MoonCat Rescue Order and an Accessory ID, return the bounding box of the Accessory, relative to the MoonCat. */ function placementOf (uint256 rescueOrder, uint256 accessoryId) public view returns (uint8 offsetX, uint8 offsetY, uint8 width, uint8 height, bool mirror, bool background) { bytes5 catId = MoonCatRescue.rescueOrder(rescueOrder); (,, uint8 facing,,, uint8 pose) = MoonCatTraits.kTraitsOf(catId); bytes2[4] memory positions; uint8 meta; (positions,, width, height, meta,) = MoonCatAccessories.accessoryImageData(accessoryId); bytes2 position = positions[pose]; background = (meta & 1) == 1; bool mirrorPlacement; if (facing == 1) { mirror = ((meta >> 1) & 1) == 1; mirrorPlacement = ((meta >> 2) & 1) == 1; } offsetX = uint8(position[0]); offsetY = uint8(position[1]); if (mirrorPlacement) { offsetX = 128 - offsetX - width; } } /* General */ /** * @dev Get documentation about this contract. */ function doc() public view returns (string memory name, string memory description, string memory details) { return MoonCatReference.doc(address(this)); } constructor (address MoonCatReferenceAddress, address MoonCatTraitsAddress, address MoonCatColorsAddress, address MoonCatSVGsAddress) { owner = payable(msg.sender); // https://docs.ens.domains/contract-api-reference/reverseregistrar#claim-address IReverseResolver(0x084b1c3C81545d370f3634392De611CaaBFf8148).claim(msg.sender); MoonCatReference = IMoonCatReference(MoonCatReferenceAddress); MoonCatTraits = IMoonCatTraits(MoonCatTraitsAddress); MoonCatColors = IMoonCatColors(MoonCatColorsAddress); MoonCatSVGs = IMoonCatSVGs(MoonCatSVGsAddress); } address payable public owner; modifier onlyOwner () { require(msg.sender == owner, "Only Owner"); _; } /** * @dev Allow current `owner` to transfer ownership to another address. */ function transferOwnership (address payable newOwner) public onlyOwner { owner = newOwner; } /** * @dev Update the location of the Reference Contract. */ function setReferenceContract (address referenceContract) public onlyOwner { MoonCatReference = IMoonCatReference(referenceContract); } /** * @dev Rescue ERC20 assets sent directly to this contract. */ function withdrawForeignERC20(address tokenContract) public onlyOwner { IERC20 token = IERC20(tokenContract); token.transfer(owner, token.balanceOf(address(this))); } /** * @dev Rescue ERC721 assets sent directly to this contract. */ function withdrawForeignERC721(address tokenContract, uint256 tokenId) public onlyOwner { IERC721(tokenContract).safeTransferFrom(address(this), owner, tokenId); } }
* @dev Given a set of metadata about MoonCat and desired Accessories to render on it, generate an SVG of that appearance./
{ bytes memory bg; bytes memory fg; function assembleSVG (uint8 x, uint8 y, uint8 width, uint8 height, bytes memory mooncatPixelData, uint8[45] memory accessoryColors, PreppedAccessory[] memory background, PreppedAccessory[] memory foreground, uint8 glowLevel) internal view returns (string memory) for (uint i = background.length; i >= 1; i--) { bg = abi.encodePacked(bg, accessorySVGSnippet(background[i - 1], accessoryColors)); } for (uint i = 0; i < foreground.length; i++) { fg = abi.encodePacked(fg, accessorySVGSnippet(foreground[i], accessoryColors)); } if (glowLevel == 0) { return string(abi.encodePacked(MoonCatSVGs.svgTag(x, y, width, height), bg, mooncatPixelData, fg, "</svg>")); return string(abi.encodePacked(MoonCatSVGs.svgTag(x, y, width, height), MoonCatSVGs.glowGroup(mooncatPixelData, accessoryColors[0], accessoryColors[1], accessoryColors[2]), bg, mooncatPixelData, fg, "</svg>")); return string(abi.encodePacked(MoonCatSVGs.svgTag(x, y, width, height), MoonCatSVGs.glowGroup(abi.encodePacked(bg, mooncatPixelData, fg), accessoryColors[0], accessoryColors[1], accessoryColors[2]), "</svg>")); } } else if (glowLevel == 1) { } else { }
13,788,015
[ 1, 6083, 279, 444, 434, 1982, 2973, 14987, 265, 11554, 471, 6049, 5016, 2401, 358, 1743, 603, 518, 16, 2103, 392, 11281, 434, 716, 9788, 1359, 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, 565, 288, 203, 203, 3639, 1731, 3778, 7611, 31, 203, 3639, 1731, 3778, 10186, 31, 203, 203, 565, 445, 19540, 26531, 261, 11890, 28, 619, 16, 203, 12900, 2254, 28, 677, 16, 203, 12900, 2254, 28, 1835, 16, 203, 12900, 2254, 28, 2072, 16, 203, 12900, 1731, 3778, 7344, 265, 2574, 9037, 751, 16, 203, 12900, 2254, 28, 63, 7950, 65, 3778, 2006, 630, 12570, 16, 203, 12900, 2962, 84, 1845, 1862, 630, 8526, 3778, 5412, 16, 203, 12900, 2962, 84, 1845, 1862, 630, 8526, 3778, 16231, 16, 203, 12900, 2254, 28, 314, 821, 2355, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 1080, 3778, 13, 203, 3639, 364, 261, 11890, 277, 273, 5412, 18, 2469, 31, 277, 1545, 404, 31, 277, 413, 13, 288, 203, 5411, 7611, 273, 24126, 18, 3015, 4420, 329, 12, 12370, 16, 2006, 630, 26531, 19614, 12, 9342, 63, 77, 300, 404, 6487, 2006, 630, 12570, 10019, 203, 3639, 289, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 16231, 18, 2469, 31, 277, 27245, 288, 203, 5411, 10186, 273, 24126, 18, 3015, 4420, 329, 12, 2137, 16, 2006, 630, 26531, 19614, 12, 1405, 2915, 63, 77, 6487, 2006, 630, 12570, 10019, 203, 3639, 289, 203, 203, 3639, 309, 261, 75, 821, 2355, 422, 374, 13, 288, 203, 5411, 327, 533, 12, 21457, 18, 3015, 4420, 329, 12, 16727, 265, 11554, 26531, 87, 18, 11451, 1805, 12, 92, 16, 677, 16, 1835, 16, 2072, 3631, 203, 4766, 6647, 7611, 16, 203, 4766, 6647, 2 ]
./full_match/1/0xCD3c2aB95cF91665D590751CdD3d7959C41951f4/sources/contracts/protocol/vault/ethereum/ConvexVault/ConvexCurveLPVault.sol
* @dev The function to get rewards token address/
function getBaseRewardPool() internal view returns (address) { IConvexBooster.PoolInfo memory poolInfo = IConvexBooster(convexBooster).poolInfo(convexPoolId); return poolInfo.crvRewards; }
17,094,175
[ 1, 1986, 445, 358, 336, 283, 6397, 1147, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 8297, 17631, 1060, 2864, 1435, 2713, 1476, 1135, 261, 2867, 13, 288, 203, 565, 467, 17467, 338, 26653, 264, 18, 2864, 966, 3778, 2845, 966, 273, 467, 17467, 338, 26653, 264, 12, 4896, 338, 26653, 264, 2934, 6011, 966, 12, 4896, 338, 25136, 1769, 203, 565, 327, 2845, 966, 18, 3353, 90, 17631, 14727, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.4; import {Clone} from "Clone.sol"; import {ERC20} from "ERC20.sol"; import {ERC721, ERC721TokenReceiver} from "ERC721.sol"; import {SafeTransferLib} from "SafeTransferLib.sol"; import {Ownable} from "Ownable.sol"; import {FullMath} from "FullMath.sol"; /// @title ERC721StakingPool /// @author zefram.eth /// @notice A modern, gas optimized staking pool contract for rewarding ERC721 stakers /// with ERC20 tokens periodically and continuously contract ERC721StakingPool is Ownable, Clone, ERC721TokenReceiver { /// ----------------------------------------------------------------------- /// Library usage /// ----------------------------------------------------------------------- using SafeTransferLib for ERC20; /// ----------------------------------------------------------------------- /// Errors /// ----------------------------------------------------------------------- error Error_ZeroOwner(); error Error_AlreadyInitialized(); error Error_NotRewardDistributor(); error Error_AmountTooLarge(); error Error_NotTokenOwner(); error Error_NotStakeToken(); /// ----------------------------------------------------------------------- /// Events /// ----------------------------------------------------------------------- event RewardAdded(uint256 reward); event Staked(address indexed user, uint256[] idList); event Withdrawn(address indexed user, uint256[] idList); event RewardPaid(address indexed user, uint256 reward); /// ----------------------------------------------------------------------- /// Constants /// ----------------------------------------------------------------------- uint256 internal constant PRECISION = 1e30; address internal constant BURN_ADDRESS = address(0xdead); /// ----------------------------------------------------------------------- /// Storage variables /// ----------------------------------------------------------------------- /// @notice The last Unix timestamp (in seconds) when rewardPerTokenStored was updated uint64 public lastUpdateTime; /// @notice The Unix timestamp (in seconds) at which the current reward period ends uint64 public periodFinish; /// @notice The per-second rate at which rewardPerToken increases uint256 public rewardRate; /// @notice The last stored rewardPerToken value uint256 public rewardPerTokenStored; /// @notice The total tokens staked in the pool uint256 public totalSupply; /// @notice Tracks if an address can call notifyReward() mapping(address => bool) public isRewardDistributor; /// @notice The owner of a staked ERC721 token mapping(uint256 => address) public ownerOf; /// @notice The amount of tokens staked by an account mapping(address => uint256) public balanceOf; /// @notice The rewardPerToken value when an account last staked/withdrew/withdrew rewards mapping(address => uint256) public userRewardPerTokenPaid; /// @notice The earned() value when an account last staked/withdrew/withdrew rewards mapping(address => uint256) public rewards; /// ----------------------------------------------------------------------- /// Immutable parameters /// ----------------------------------------------------------------------- /// @notice The token being rewarded to stakers function rewardToken() public pure returns (ERC20 rewardToken_) { return ERC20(_getArgAddress(0)); } /// @notice The token being staked in the pool function stakeToken() public pure returns (ERC721 stakeToken_) { return ERC721(_getArgAddress(0x14)); } /// @notice The length of each reward period, in seconds function DURATION() public pure returns (uint64 DURATION_) { return _getArgUint64(0x28); } /// ----------------------------------------------------------------------- /// Initialization /// ----------------------------------------------------------------------- /// @notice Initializes the owner, called by StakingPoolFactory /// @param initialOwner The initial owner of the contract function initialize(address initialOwner) external { if (owner() != address(0)) { revert Error_AlreadyInitialized(); } if (initialOwner == address(0)) { revert Error_ZeroOwner(); } _transferOwnership(initialOwner); } /// ----------------------------------------------------------------------- /// User actions /// ----------------------------------------------------------------------- /// @notice Stakes a list of ERC721 tokens in the pool to earn rewards /// @param idList The list of ERC721 token IDs to stake function stake(uint256[] calldata idList) external { /// ----------------------------------------------------------------------- /// Validation /// ----------------------------------------------------------------------- if (idList.length == 0) { return; } /// ----------------------------------------------------------------------- /// Storage loads /// ----------------------------------------------------------------------- uint256 accountBalance = balanceOf[msg.sender]; uint64 lastTimeRewardApplicable_ = lastTimeRewardApplicable(); uint256 totalSupply_ = totalSupply; uint256 rewardPerToken_ = _rewardPerToken( totalSupply_, lastTimeRewardApplicable_, rewardRate ); /// ----------------------------------------------------------------------- /// State updates /// ----------------------------------------------------------------------- // accrue rewards rewardPerTokenStored = rewardPerToken_; lastUpdateTime = lastTimeRewardApplicable_; rewards[msg.sender] = _earned( msg.sender, accountBalance, rewardPerToken_, rewards[msg.sender] ); userRewardPerTokenPaid[msg.sender] = rewardPerToken_; // stake totalSupply = totalSupply_ + idList.length; balanceOf[msg.sender] = accountBalance + idList.length; unchecked { for (uint256 i = 0; i < idList.length; i++) { ownerOf[idList[i]] = msg.sender; } } /// ----------------------------------------------------------------------- /// Effects /// ----------------------------------------------------------------------- unchecked { for (uint256 i = 0; i < idList.length; i++) { stakeToken().safeTransferFrom( msg.sender, address(this), idList[i] ); } } emit Staked(msg.sender, idList); } /// @notice Withdraws staked tokens from the pool /// @param idList The list of ERC721 token IDs to stake function withdraw(uint256[] calldata idList) external { /// ----------------------------------------------------------------------- /// Validation /// ----------------------------------------------------------------------- if (idList.length == 0) { return; } /// ----------------------------------------------------------------------- /// Storage loads /// ----------------------------------------------------------------------- uint256 accountBalance = balanceOf[msg.sender]; uint64 lastTimeRewardApplicable_ = lastTimeRewardApplicable(); uint256 totalSupply_ = totalSupply; uint256 rewardPerToken_ = _rewardPerToken( totalSupply_, lastTimeRewardApplicable_, rewardRate ); /// ----------------------------------------------------------------------- /// State updates /// ----------------------------------------------------------------------- // accrue rewards rewardPerTokenStored = rewardPerToken_; lastUpdateTime = lastTimeRewardApplicable_; rewards[msg.sender] = _earned( msg.sender, accountBalance, rewardPerToken_, rewards[msg.sender] ); userRewardPerTokenPaid[msg.sender] = rewardPerToken_; // withdraw stake balanceOf[msg.sender] = accountBalance - idList.length; // total supply has 1:1 relationship with staked amounts // so can't ever underflow unchecked { totalSupply = totalSupply_ - idList.length; for (uint256 i = 0; i < idList.length; i++) { // verify ownership address tokenOwner = ownerOf[idList[i]]; if (tokenOwner != msg.sender || tokenOwner == BURN_ADDRESS) { revert Error_NotTokenOwner(); } // keep the storage slot dirty to save gas // if someone else stakes the same token again ownerOf[idList[i]] = BURN_ADDRESS; } } /// ----------------------------------------------------------------------- /// Effects /// ----------------------------------------------------------------------- unchecked { for (uint256 i = 0; i < idList.length; i++) { stakeToken().safeTransferFrom( address(this), msg.sender, idList[i] ); } } emit Withdrawn(msg.sender, idList); } /// @notice Withdraws specified staked tokens and earned rewards function exit(uint256[] calldata idList) external { /// ----------------------------------------------------------------------- /// Validation /// ----------------------------------------------------------------------- if (idList.length == 0) { return; } /// ----------------------------------------------------------------------- /// Storage loads /// ----------------------------------------------------------------------- uint256 accountBalance = balanceOf[msg.sender]; uint64 lastTimeRewardApplicable_ = lastTimeRewardApplicable(); uint256 totalSupply_ = totalSupply; uint256 rewardPerToken_ = _rewardPerToken( totalSupply_, lastTimeRewardApplicable_, rewardRate ); /// ----------------------------------------------------------------------- /// State updates /// ----------------------------------------------------------------------- // give rewards uint256 reward = _earned( msg.sender, accountBalance, rewardPerToken_, rewards[msg.sender] ); if (reward > 0) { rewards[msg.sender] = 0; } // accrue rewards rewardPerTokenStored = rewardPerToken_; lastUpdateTime = lastTimeRewardApplicable_; userRewardPerTokenPaid[msg.sender] = rewardPerToken_; // withdraw stake balanceOf[msg.sender] = accountBalance - idList.length; // total supply has 1:1 relationship with staked amounts // so can't ever underflow unchecked { totalSupply = totalSupply_ - idList.length; for (uint256 i = 0; i < idList.length; i++) { // verify ownership address tokenOwner = ownerOf[idList[i]]; if (tokenOwner != msg.sender || tokenOwner == BURN_ADDRESS) { revert Error_NotTokenOwner(); } // keep the storage slot dirty to save gas // if someone else stakes the same token again ownerOf[idList[i]] = BURN_ADDRESS; } } /// ----------------------------------------------------------------------- /// Effects /// ----------------------------------------------------------------------- // transfer stake unchecked { for (uint256 i = 0; i < idList.length; i++) { stakeToken().safeTransferFrom( address(this), msg.sender, idList[i] ); } } emit Withdrawn(msg.sender, idList); // transfer rewards if (reward > 0) { rewardToken().safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } /// @notice Withdraws all earned rewards function getReward() external { /// ----------------------------------------------------------------------- /// Storage loads /// ----------------------------------------------------------------------- uint256 accountBalance = balanceOf[msg.sender]; uint64 lastTimeRewardApplicable_ = lastTimeRewardApplicable(); uint256 totalSupply_ = totalSupply; uint256 rewardPerToken_ = _rewardPerToken( totalSupply_, lastTimeRewardApplicable_, rewardRate ); /// ----------------------------------------------------------------------- /// State updates /// ----------------------------------------------------------------------- uint256 reward = _earned( msg.sender, accountBalance, rewardPerToken_, rewards[msg.sender] ); // accrue rewards rewardPerTokenStored = rewardPerToken_; lastUpdateTime = lastTimeRewardApplicable_; userRewardPerTokenPaid[msg.sender] = rewardPerToken_; // withdraw rewards if (reward > 0) { rewards[msg.sender] = 0; /// ----------------------------------------------------------------------- /// Effects /// ----------------------------------------------------------------------- rewardToken().safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } /// ----------------------------------------------------------------------- /// Getters /// ----------------------------------------------------------------------- /// @notice The latest time at which stakers are earning rewards. function lastTimeRewardApplicable() public view returns (uint64) { return block.timestamp < periodFinish ? uint64(block.timestamp) : periodFinish; } /// @notice The amount of reward tokens each staked token has earned so far function rewardPerToken() external view returns (uint256) { return _rewardPerToken( totalSupply, lastTimeRewardApplicable(), rewardRate ); } /// @notice The amount of reward tokens an account has accrued so far. Does not /// include already withdrawn rewards. function earned(address account) external view returns (uint256) { return _earned( account, balanceOf[account], _rewardPerToken( totalSupply, lastTimeRewardApplicable(), rewardRate ), rewards[account] ); } /// @dev ERC721 compliance function onERC721Received( address, address, uint256, bytes calldata ) external view override returns (bytes4) { if (msg.sender != address(stakeToken())) { revert Error_NotStakeToken(); } return this.onERC721Received.selector; } /// ----------------------------------------------------------------------- /// Owner actions /// ----------------------------------------------------------------------- /// @notice Lets a reward distributor start a new reward period. The reward tokens must have already /// been transferred to this contract before calling this function. If it is called /// when a reward period is still active, a new reward period will begin from the time /// of calling this function, using the leftover rewards from the old reward period plus /// the newly sent rewards as the reward. /// @dev If the reward amount will cause an overflow when computing rewardPerToken, then /// this function will revert. /// @param reward The amount of reward tokens to use in the new reward period. function notifyRewardAmount(uint256 reward) external { /// ----------------------------------------------------------------------- /// Validation /// ----------------------------------------------------------------------- if (reward == 0) { return; } if (!isRewardDistributor[msg.sender]) { revert Error_NotRewardDistributor(); } /// ----------------------------------------------------------------------- /// Storage loads /// ----------------------------------------------------------------------- uint256 rewardRate_ = rewardRate; uint64 periodFinish_ = periodFinish; uint64 lastTimeRewardApplicable_ = block.timestamp < periodFinish_ ? uint64(block.timestamp) : periodFinish_; uint64 DURATION_ = DURATION(); uint256 totalSupply_ = totalSupply; /// ----------------------------------------------------------------------- /// State updates /// ----------------------------------------------------------------------- // accrue rewards rewardPerTokenStored = _rewardPerToken( totalSupply_, lastTimeRewardApplicable_, rewardRate_ ); lastUpdateTime = lastTimeRewardApplicable_; // record new reward uint256 newRewardRate; if (block.timestamp >= periodFinish_) { newRewardRate = reward / DURATION_; } else { uint256 remaining = periodFinish_ - block.timestamp; uint256 leftover = remaining * rewardRate_; newRewardRate = (reward + leftover) / DURATION_; } // prevent overflow when computing rewardPerToken if (newRewardRate >= ((type(uint256).max / PRECISION) / DURATION_)) { revert Error_AmountTooLarge(); } rewardRate = newRewardRate; lastUpdateTime = uint64(block.timestamp); periodFinish = uint64(block.timestamp + DURATION_); emit RewardAdded(reward); } /// @notice Lets the owner add/remove accounts from the list of reward distributors. /// Reward distributors can call notifyRewardAmount() /// @param rewardDistributor The account to add/remove /// @param isRewardDistributor_ True to add the account, false to remove the account function setRewardDistributor( address rewardDistributor, bool isRewardDistributor_ ) external onlyOwner { isRewardDistributor[rewardDistributor] = isRewardDistributor_; } /// ----------------------------------------------------------------------- /// Internal functions /// ----------------------------------------------------------------------- function _earned( address account, uint256 accountBalance, uint256 rewardPerToken_, uint256 accountRewards ) internal view returns (uint256) { return FullMath.mulDiv( accountBalance, rewardPerToken_ - userRewardPerTokenPaid[account], PRECISION ) + accountRewards; } function _rewardPerToken( uint256 totalSupply_, uint256 lastTimeRewardApplicable_, uint256 rewardRate_ ) internal view returns (uint256) { if (totalSupply_ == 0) { return rewardPerTokenStored; } return rewardPerTokenStored + FullMath.mulDiv( (lastTimeRewardApplicable_ - lastUpdateTime) * PRECISION, rewardRate_, totalSupply_ ); } function _getImmutableVariablesOffset() internal pure returns (uint256 offset) { assembly { offset := sub( calldatasize(), add(shr(240, calldataload(sub(calldatasize(), 2))), 2) ) } } } // SPDX-License-Identifier: BSD pragma solidity ^0.8.4; /// @title Clone /// @author zefram.eth /// @notice Provides helper functions for reading immutable args from calldata contract Clone { /// @notice Reads an immutable arg with type address /// @param argOffset The offset of the arg in the packed data /// @return arg The arg value function _getArgAddress(uint256 argOffset) internal pure returns (address arg) { uint256 offset = _getImmutableArgsOffset(); assembly { arg := shr(0x60, calldataload(add(offset, argOffset))) } } /// @notice Reads an immutable arg with type uint256 /// @param argOffset The offset of the arg in the packed data /// @return arg The arg value function _getArgUint256(uint256 argOffset) internal pure returns (uint256 arg) { uint256 offset = _getImmutableArgsOffset(); // solhint-disable-next-line no-inline-assembly assembly { arg := calldataload(add(offset, argOffset)) } } /// @notice Reads an immutable arg with type uint64 /// @param argOffset The offset of the arg in the packed data /// @return arg The arg value function _getArgUint64(uint256 argOffset) internal pure returns (uint64 arg) { uint256 offset = _getImmutableArgsOffset(); // solhint-disable-next-line no-inline-assembly assembly { arg := shr(0xc0, calldataload(add(offset, argOffset))) } } /// @notice Reads an immutable arg with type uint8 /// @param argOffset The offset of the arg in the packed data /// @return arg The arg value function _getArgUint8(uint256 argOffset) internal pure returns (uint8 arg) { uint256 offset = _getImmutableArgsOffset(); // solhint-disable-next-line no-inline-assembly assembly { arg := shr(0xf8, calldataload(add(offset, argOffset))) } } /// @return offset The offset of the packed immutable args in calldata function _getImmutableArgsOffset() internal pure returns (uint256 offset) { // solhint-disable-next-line no-inline-assembly assembly { offset := sub( calldatasize(), add(shr(240, calldataload(sub(calldatasize(), 2))), 2) ) } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; import {Clone} from "Clone.sol"; /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 is Clone { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval( address indexed owner, address indexed spender, uint256 amount ); /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// METADATA //////////////////////////////////////////////////////////////*/ function name() external pure returns (string memory) { return string(abi.encodePacked(_getArgUint256(0))); } function symbol() external pure returns (string memory) { return string(abi.encodePacked(_getArgUint256(0x20))); } function decimals() external pure returns (uint8) { return _getArgUint8(0x40); } /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// INTERNAL LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } function _getImmutableVariablesOffset() internal pure returns (uint256 offset) { assembly { offset := sub( calldatasize(), add(shr(240, calldataload(sub(calldatasize(), 2))), 2) ) } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Modern, minimalist, and gas efficient ERC-721 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol) /// @dev Note that balanceOf does not revert if passed the zero address, in defiance of the ERC. abstract contract ERC721 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer( address indexed from, address indexed to, uint256 indexed id ); event Approval( address indexed owner, address indexed spender, uint256 indexed id ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /*/////////////////////////////////////////////////////////////// METADATA STORAGE/LOGIC //////////////////////////////////////////////////////////////*/ string public name; string public symbol; function tokenURI(uint256 id) public view virtual returns (string memory); /*/////////////////////////////////////////////////////////////// ERC721 STORAGE //////////////////////////////////////////////////////////////*/ mapping(address => uint256) public balanceOf; mapping(uint256 => address) public ownerOf; mapping(uint256 => address) public getApproved; mapping(address => mapping(address => bool)) public isApprovedForAll; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor(string memory _name, string memory _symbol) { name = _name; symbol = _symbol; } /*/////////////////////////////////////////////////////////////// ERC721 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 id) public virtual { address owner = ownerOf[id]; require( msg.sender == owner || isApprovedForAll[owner][msg.sender], "NOT_AUTHORIZED" ); getApproved[id] = spender; emit Approval(owner, spender, id); } function setApprovalForAll(address operator, bool approved) public virtual { isApprovedForAll[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function transferFrom( address from, address to, uint256 id ) public virtual { require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } ownerOf[id] = to; delete getApproved[id]; emit Transfer(from, to, id); } function safeTransferFrom( address from, address to, uint256 id ) public virtual { transferFrom(from, to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received( msg.sender, from, id, "" ) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom( address from, address to, uint256 id, bytes memory data ) public virtual { transferFrom(from, to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received( msg.sender, from, id, data ) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } /*/////////////////////////////////////////////////////////////// ERC165 LOGIC //////////////////////////////////////////////////////////////*/ function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721 interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 id) internal virtual { require(to != address(0), "INVALID_RECIPIENT"); require(ownerOf[id] == address(0), "ALREADY_MINTED"); // Counter overflow is incredibly unrealistic. unchecked { balanceOf[to]++; } ownerOf[id] = to; emit Transfer(address(0), to, id); } function _burn(uint256 id) internal virtual { address owner = ownerOf[id]; require(ownerOf[id] != address(0), "NOT_MINTED"); // Ownership check above ensures no underflow. unchecked { balanceOf[owner]--; } delete ownerOf[id]; delete getApproved[id]; emit Transfer(owner, address(0), id); } /*/////////////////////////////////////////////////////////////// INTERNAL SAFE MINT LOGIC //////////////////////////////////////////////////////////////*/ function _safeMint(address to, uint256 id) internal virtual { _mint(to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received( msg.sender, address(0), id, "" ) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function _safeMint( address to, uint256 id, bytes memory data ) internal virtual { _mint(to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received( msg.sender, address(0), id, data ) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } } /// @notice A generic interface for a contract which properly accepts ERC721 tokens. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol) interface ERC721TokenReceiver { function onERC721Received( address operator, address from, uint256 id, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; import {ERC20} from "ERC20.sol"; /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol) /// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol) /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer. /// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller. library SafeTransferLib { /*/////////////////////////////////////////////////////////////// ETH OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferETH(address to, uint256 amount) internal { bool callStatus; assembly { // Transfer the ETH and store if it succeeded or not. callStatus := call(gas(), to, amount, 0, 0, 0, 0) } require(callStatus, "ETH_TRANSFER_FAILED"); } /*/////////////////////////////////////////////////////////////// ERC20 OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferFrom( ERC20 token, address from, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore( freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000 ) // Begin with the function selector. mstore( add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff) ) // Mask and append the "from" argument. mstore( add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff) ) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 100 because the calldata length is 4 + 32 * 3. callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0) } require( didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FROM_FAILED" ); } function safeTransfer( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore( freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000 ) // Begin with the function selector. mstore( add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff) ) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require( didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FAILED" ); } function safeApprove( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore( freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000 ) // Begin with the function selector. mstore( add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff) ) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED"); } /*/////////////////////////////////////////////////////////////// INTERNAL HELPER LOGIC //////////////////////////////////////////////////////////////*/ function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) { assembly { // Get how many bytes the call returned. let returnDataSize := returndatasize() // If the call reverted: if iszero(callStatus) { // Copy the revert message into memory. returndatacopy(0, 0, returnDataSize) // Revert with the same message. revert(0, returnDataSize) } switch returnDataSize case 32 { // Copy the return data into memory. returndatacopy(0, 0, returnDataSize) // Set success to whether it returned true. success := iszero(iszero(mload(0))) } case 0 { // There was no return data. success := 1 } default { // It returned some malformed input. success := 0 } } } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.4; abstract contract Ownable { error Ownable_NotOwner(); error Ownable_NewOwnerZeroAddress(); address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /// @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() { if (owner() != msg.sender) revert Ownable_NotOwner(); _; } /// @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 { if (newOwner == address(0)) revert Ownable_NewOwnerZeroAddress(); _transferOwnership(newOwner); } /// @dev Transfers ownership of the contract to a new account (`newOwner`). /// Internal function without access restriction. function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.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) { unchecked { // 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 = (type(uint256).max - denominator + 1) & 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); unchecked { if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } }
@notice Modern, minimalist, and gas efficient ERC-721 implementation. @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol) @dev Note that balanceOf does not revert if passed the zero address, in defiance of the ERC.
abstract contract ERC721 { EVENTS event Transfer( address indexed from, address indexed to, uint256 indexed id ); event Approval( address indexed owner, address indexed spender, uint256 indexed id ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); METADATA STORAGE/LOGIC string public name; string public symbol; function tokenURI(uint256 id) public view virtual returns (string memory); ERC721 STORAGE mapping(address => uint256) public balanceOf; mapping(uint256 => address) public ownerOf; mapping(uint256 => address) public getApproved; mapping(address => mapping(address => bool)) public isApprovedForAll; CONSTRUCTOR pragma solidity >=0.8.0; constructor(string memory _name, string memory _symbol) { name = _name; symbol = _symbol; } ERC721 LOGIC function approve(address spender, uint256 id) public virtual { address owner = ownerOf[id]; require( msg.sender == owner || isApprovedForAll[owner][msg.sender], "NOT_AUTHORIZED" ); getApproved[id] = spender; emit Approval(owner, spender, id); } function setApprovalForAll(address operator, bool approved) public virtual { isApprovedForAll[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function transferFrom( address from, address to, uint256 id ) public virtual { require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); unchecked { balanceOf[from]--; balanceOf[to]++; } ownerOf[id] = to; delete getApproved[id]; emit Transfer(from, to, id); } function transferFrom( address from, address to, uint256 id ) public virtual { require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); unchecked { balanceOf[from]--; balanceOf[to]++; } ownerOf[id] = to; delete getApproved[id]; emit Transfer(from, to, id); } function safeTransferFrom( address from, address to, uint256 id ) public virtual { transferFrom(from, to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received( msg.sender, from, id, "" ) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom( address from, address to, uint256 id, bytes memory data ) public virtual { transferFrom(from, to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received( msg.sender, from, id, data ) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } ERC165 LOGIC function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) { return } INTERNAL MINT/BURN LOGIC function _mint(address to, uint256 id) internal virtual { require(to != address(0), "INVALID_RECIPIENT"); require(ownerOf[id] == address(0), "ALREADY_MINTED"); unchecked { balanceOf[to]++; } ownerOf[id] = to; emit Transfer(address(0), to, id); } function _mint(address to, uint256 id) internal virtual { require(to != address(0), "INVALID_RECIPIENT"); require(ownerOf[id] == address(0), "ALREADY_MINTED"); unchecked { balanceOf[to]++; } ownerOf[id] = to; emit Transfer(address(0), to, id); } function _burn(uint256 id) internal virtual { address owner = ownerOf[id]; require(ownerOf[id] != address(0), "NOT_MINTED"); unchecked { balanceOf[owner]--; } delete ownerOf[id]; delete getApproved[id]; emit Transfer(owner, address(0), id); } INTERNAL SAFE MINT LOGIC function _burn(uint256 id) internal virtual { address owner = ownerOf[id]; require(ownerOf[id] != address(0), "NOT_MINTED"); unchecked { balanceOf[owner]--; } delete ownerOf[id]; delete getApproved[id]; emit Transfer(owner, address(0), id); } INTERNAL SAFE MINT LOGIC function _safeMint(address to, uint256 id) internal virtual { _mint(to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received( msg.sender, address(0), id, "" ) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function _safeMint( address to, uint256 id, bytes memory data ) internal virtual { _mint(to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received( msg.sender, address(0), id, data ) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } }
6,864,243
[ 1, 1739, 8865, 16, 16745, 376, 16, 471, 16189, 14382, 4232, 39, 17, 27, 5340, 4471, 18, 225, 348, 355, 81, 340, 261, 4528, 2207, 6662, 18, 832, 19, 54, 12954, 17, 4664, 7053, 19, 18281, 81, 340, 19, 10721, 19, 5254, 19, 4816, 19, 7860, 19, 654, 39, 27, 5340, 18, 18281, 13, 225, 3609, 716, 11013, 951, 1552, 486, 15226, 309, 2275, 326, 3634, 1758, 16, 316, 1652, 77, 1359, 434, 326, 4232, 39, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 17801, 6835, 4232, 39, 27, 5340, 288, 203, 4766, 9964, 55, 203, 203, 565, 871, 12279, 12, 203, 3639, 1758, 8808, 628, 16, 203, 3639, 1758, 8808, 358, 16, 203, 3639, 2254, 5034, 8808, 612, 203, 565, 11272, 203, 203, 565, 871, 1716, 685, 1125, 12, 203, 3639, 1758, 8808, 3410, 16, 203, 3639, 1758, 8808, 17571, 264, 16, 203, 3639, 2254, 5034, 8808, 612, 203, 565, 11272, 203, 203, 565, 871, 1716, 685, 1125, 1290, 1595, 12, 203, 3639, 1758, 8808, 3410, 16, 203, 3639, 1758, 8808, 3726, 16, 203, 3639, 1426, 20412, 203, 565, 11272, 203, 203, 12900, 24175, 2347, 15553, 19, 4842, 2871, 203, 203, 565, 533, 1071, 508, 31, 203, 203, 565, 533, 1071, 3273, 31, 203, 203, 565, 445, 1147, 3098, 12, 11890, 5034, 612, 13, 1071, 1476, 5024, 1135, 261, 1080, 3778, 1769, 203, 203, 18701, 4232, 39, 27, 5340, 2347, 15553, 7682, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 11013, 951, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 1071, 3410, 951, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 1071, 336, 31639, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 1426, 3719, 1071, 353, 31639, 1290, 1595, 31, 203, 203, 17311, 3492, 13915, 916, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 28, 18, 20, 31, 203, 565, 3885, 12, 1080, 3778, 389, 529, 16, 533, 3778, 389, 7175, 13, 288, 203, 3639, 508, 273, 389, 529, 31, 203, 3639, 3273, 2 ]
./full_match/42/0x5c1a35F25F15D100e0011865f741a41E960D173D/sources/b.sol
event reflects burn of erc20 votes
emit Transfer(prop.to[i], address(0), prop.value[i]);}}
9,573,052
[ 1, 2575, 3037, 87, 18305, 434, 6445, 71, 3462, 19588, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 10792, 3626, 12279, 12, 5986, 18, 869, 63, 77, 6487, 1758, 12, 20, 3631, 2270, 18, 1132, 63, 77, 19226, 9090, 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 ]
./partial_match/1/0x000000e7Ec00e7B300774b00001314B8610022b8/sources/contracts/zones/SignedZone.sol
* @dev Derive the signedOrder hash from the orderHash and expiration. @param fulfiller The expected fulfiller address. @param expiration The signature expiration timestamp. @param orderHash The order hash. @param context The optional variable-length context. @return signedOrderHash The signedOrder hash./ Derive the signed order hash.
function _deriveSignedOrderHash( address fulfiller, uint64 expiration, bytes32 orderHash, bytes calldata context ) internal view returns (bytes32 signedOrderHash) { signedOrderHash = keccak256( abi.encode( _SIGNED_ORDER_TYPEHASH, fulfiller, expiration, orderHash, keccak256(context) ) ); }
9,360,395
[ 1, 12041, 688, 326, 6726, 2448, 1651, 628, 326, 1353, 2310, 471, 7686, 18, 225, 22290, 264, 225, 1021, 2665, 22290, 264, 1758, 18, 225, 7686, 1021, 3372, 7686, 2858, 18, 225, 1353, 2310, 225, 1021, 1353, 1651, 18, 225, 819, 565, 1021, 3129, 2190, 17, 2469, 819, 18, 327, 6726, 2448, 2310, 1021, 6726, 2448, 1651, 18, 19, 14969, 688, 326, 6726, 1353, 1651, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 765, 688, 12294, 2448, 2310, 12, 203, 3639, 1758, 22290, 264, 16, 203, 3639, 2254, 1105, 7686, 16, 203, 3639, 1731, 1578, 1353, 2310, 16, 203, 3639, 1731, 745, 892, 819, 203, 565, 262, 2713, 1476, 1135, 261, 3890, 1578, 6726, 2448, 2310, 13, 288, 203, 3639, 6726, 2448, 2310, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 12, 203, 7734, 389, 21049, 67, 7954, 67, 2399, 15920, 16, 203, 7734, 22290, 264, 16, 203, 7734, 7686, 16, 203, 7734, 1353, 2310, 16, 203, 7734, 417, 24410, 581, 5034, 12, 2472, 13, 203, 5411, 262, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x8002Aa3A2065cdc24c72FE518a0aEd5c9f8FA9D9/sources/ShareTokenSaleData.sol
* @dev Decrease shareholder balance with `amount` of BNU for round `round`/
function _decreaseShareholderBalance(address account, uint amount, uint round) internal{ _shareholderBalances[round][account] = _shareholderBalances[round][account].sub(amount); }
4,138,307
[ 1, 23326, 448, 7433, 4505, 11013, 598, 1375, 8949, 68, 434, 605, 50, 57, 364, 3643, 1375, 2260, 68, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 323, 11908, 9535, 4505, 13937, 12, 2867, 2236, 16, 2254, 3844, 16, 2254, 3643, 13, 2713, 95, 203, 3639, 389, 14419, 4505, 38, 26488, 63, 2260, 6362, 4631, 65, 273, 389, 14419, 4505, 38, 26488, 63, 2260, 6362, 4631, 8009, 1717, 12, 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 ]
./full_match/1/0xA8D5eEd6b519c37BFC506409A76d0E446c04e8b9/sources/contracts/core/connext/helpers/RelayerProxyHub.sol
* @title RelayerProxyHub @author Connext Labs, Inc. @notice This is a temporary contract that wraps the Connext RootManager's propagate() function so that it can be called by Gelato's legacy relayer network. The contract stores native assets and pays them to the relayer on function call./ ============ Properties ============ ============ Events ============ ============ Constructor ============
contract RelayerProxyHub is RelayerProxy { IRootManager public rootManager; event RootManagerChanged(address rootManager, address oldRootManager); constructor( address _connext, address _spokeConnector, address _gelatoRelayer, address _feeCollector, address _rootManager pragma solidity 0.8.17; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import {GelatoRelayFeeCollector} from "@gelatonetwork/relay-context/contracts/GelatoRelayFeeCollector.sol"; import {ProposedOwnable} from "../../../shared/ProposedOwnable.sol"; import {IRootManager} from "../../../messaging/interfaces/IRootManager.sol"; import {RelayerProxy} from "./RelayerProxy.sol"; ) RelayerProxy(_connext, _spokeConnector, _gelatoRelayer, _feeCollector) { _setRootManager(_rootManager); } function setRootManager(address _rootManager) external onlyOwner definedAddress(_rootManager) { _setRootManager(_rootManager); } function propagate( address[] calldata _connectors, uint256[] calldata _messageFees, bytes[] memory _encodedData, uint256 _relayerFee ) external onlyRelayer nonReentrant { uint256 sum = 0; uint256 length = _connectors.length; for (uint32 i; i < length; ) { sum += _messageFees[i]; unchecked { ++i; } } emit FundsDeducted(sum, address(this).balance); transferRelayerFee(_relayerFee); } function propagate( address[] calldata _connectors, uint256[] calldata _messageFees, bytes[] memory _encodedData, uint256 _relayerFee ) external onlyRelayer nonReentrant { uint256 sum = 0; uint256 length = _connectors.length; for (uint32 i; i < length; ) { sum += _messageFees[i]; unchecked { ++i; } } emit FundsDeducted(sum, address(this).balance); transferRelayerFee(_relayerFee); } function propagate( address[] calldata _connectors, uint256[] calldata _messageFees, bytes[] memory _encodedData, uint256 _relayerFee ) external onlyRelayer nonReentrant { uint256 sum = 0; uint256 length = _connectors.length; for (uint32 i; i < length; ) { sum += _messageFees[i]; unchecked { ++i; } } emit FundsDeducted(sum, address(this).balance); transferRelayerFee(_relayerFee); } rootManager.propagate{value: sum}(_connectors, _messageFees, _encodedData); function _setRootManager(address _rootManager) internal { emit RootManagerChanged(_rootManager, address(rootManager)); rootManager = IRootManager(_rootManager); } }
4,978,983
[ 1, 1971, 1773, 3886, 8182, 225, 735, 4285, 511, 5113, 16, 15090, 18, 225, 1220, 353, 279, 6269, 6835, 716, 9059, 326, 735, 4285, 7450, 1318, 1807, 13551, 1435, 445, 1427, 716, 518, 848, 506, 2566, 635, 611, 292, 31093, 1807, 8866, 1279, 1773, 2483, 18, 1021, 6835, 9064, 6448, 7176, 471, 293, 8271, 2182, 358, 326, 1279, 1773, 603, 445, 745, 18, 19, 422, 1432, 631, 6183, 422, 1432, 631, 422, 1432, 631, 9043, 422, 1432, 631, 422, 1432, 631, 11417, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 4275, 1773, 3886, 8182, 353, 4275, 1773, 3886, 288, 203, 203, 225, 467, 2375, 1318, 1071, 1365, 1318, 31, 203, 203, 225, 871, 7450, 1318, 5033, 12, 2867, 1365, 1318, 16, 1758, 1592, 2375, 1318, 1769, 203, 203, 203, 225, 3885, 12, 203, 565, 1758, 389, 591, 4285, 16, 203, 565, 1758, 389, 1752, 3056, 7487, 16, 203, 565, 1758, 389, 75, 292, 31093, 1971, 1773, 16, 203, 565, 1758, 389, 21386, 7134, 16, 203, 565, 1758, 389, 3085, 1318, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 4033, 31, 203, 5666, 288, 1887, 97, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 5471, 19, 1887, 18, 18281, 14432, 203, 5666, 288, 426, 8230, 12514, 16709, 97, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 7462, 19, 426, 8230, 12514, 16709, 18, 18281, 14432, 203, 5666, 288, 43, 292, 31093, 27186, 14667, 7134, 97, 628, 8787, 75, 292, 16799, 1572, 19, 2878, 528, 17, 2472, 19, 16351, 87, 19, 43, 292, 31093, 27186, 14667, 7134, 18, 18281, 14432, 203, 5666, 288, 626, 7423, 5460, 429, 97, 628, 315, 16644, 6216, 11574, 19, 626, 7423, 5460, 429, 18, 18281, 14432, 203, 5666, 288, 45, 2375, 1318, 97, 628, 315, 16644, 6216, 23208, 19, 15898, 19, 45, 2375, 1318, 18, 18281, 14432, 203, 5666, 288, 1971, 1773, 3886, 97, 628, 25165, 1971, 1773, 3886, 18, 18281, 14432, 203, 225, 262, 4275, 1773, 3886, 24899, 591, 4285, 16, 389, 1752, 3056, 7487, 16, 389, 75, 292, 31093, 2 ]
./partial_match/1/0x9E04B84BfDCd26d740F2dD6ddbEdd6971C2Cf0d0/sources/Farming.sol
Timestamp of farming duration Amount the user has farmed Reward the user will get after farming period ends Rewards paid to user Farm starting timestamp Farm ending timestamp
contract Farming is FarmingTokenWrapper, RewardsDistributionRecipient { using StableMath for uint256; IERC20 public rewardsToken; uint256 public farmingDuration = 0; mapping(address => uint256) public userFarmedTokens; mapping(address => uint256) public rewards; mapping(address => uint256) public userRewardsPaid; mapping(address => uint256) public farmStarted; mapping(address => uint256) public farmEnded; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount, address payer); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); CONSTRUCTOR constructor ( address _farmingToken, address _rewardsToken, address _rewardsDistributor, uint256 _farmingDurationDays ) public FarmingTokenWrapper(_farmingToken) RewardsDistributionRecipient(_rewardsDistributor) { rewardsToken = IERC20(_rewardsToken); farmingDuration = _farmingDurationDays.mul(ONE_DAY); } MODIFIERS modifier isAccount(address _account) { require(!Address.isContract(_account), "Only external owned accounts allowed"); _; } ACTIONS function farm(uint256 _amount) external { _farm(msg.sender, _amount); } function _farm(address _beneficiary, uint256 _amount) internal isAccount(_beneficiary) { require(_amount >= 1, "Minimum staking amount is 1"); super._farm(_beneficiary, _amount); userFarmedTokens[_beneficiary] = userFarmedTokens[_beneficiary].add(_amount); uint256 __userAmount = userFarmedTokens[_beneficiary]; uint256 _rewardAmount = (__userAmount.mul(3 * 3600 * (rewardPercent.mul(10**21)))).div(10**27); rewards[_beneficiary] = _rewardAmount; farmStarted[_beneficiary] = block.timestamp; farmEnded[_beneficiary] = (block.timestamp).add(farmingDuration); emit Staked(_beneficiary, _amount, msg.sender); } function unfarm() external { require(block.timestamp >= farmEnded[msg.sender], "Reward cannot be claimed before 30 days"); withdraw(balanceOf(msg.sender)); claimReward(); farmStarted[msg.sender] = 0; farmEnded[msg.sender] = 0; } function withdraw(uint256 _amount) public isAccount(msg.sender) { require(_amount > 0, "Cannot withdraw 0"); require(block.timestamp >= farmEnded[msg.sender], "Reward cannot be claimed before 30 days"); userFarmedTokens[msg.sender] = userFarmedTokens[msg.sender].sub(_amount); _withdraw(_amount); emit Withdrawn(msg.sender, _amount); } function claimReward() public isAccount(msg.sender) { require(block.timestamp >= farmEnded[msg.sender], "Reward cannot be claimed before 30 days"); uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.transfer(msg.sender, reward); userRewardsPaid[msg.sender] = userRewardsPaid[msg.sender].add(reward); emit RewardPaid(msg.sender, reward); } } function claimReward() public isAccount(msg.sender) { require(block.timestamp >= farmEnded[msg.sender], "Reward cannot be claimed before 30 days"); uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.transfer(msg.sender, reward); userRewardsPaid[msg.sender] = userRewardsPaid[msg.sender].add(reward); emit RewardPaid(msg.sender, reward); } } GETTERS function getRewardToken() external view returns (IERC20) { return rewardsToken; } function earned(address _account) public view returns (uint256) { return rewards[_account]; } function tokensFarmed(address _account) public view returns (uint256) { return userFarmedTokens[_account]; } ADMIN function sendRewardTokens(uint256 _amount) public onlyRewardsDistributor { require(rewardsToken.transferFrom(msg.sender, address(this), _amount), "Transfering not approved!"); } function withdrawRewardTokens(address receiver, uint256 _amount) public onlyRewardsDistributor { require(rewardsToken.transfer(receiver, _amount), "Not enough tokens on contract!"); } function withdrawFarmTokens(address receiver, uint256 _amount) public onlyRewardsDistributor { require(farmingToken.transfer(receiver, _amount), "Not enough tokens on contract!"); } }
2,643,632
[ 1, 4921, 434, 284, 4610, 310, 3734, 16811, 326, 729, 711, 10247, 2937, 534, 359, 1060, 326, 729, 903, 336, 1839, 284, 4610, 310, 3879, 3930, 534, 359, 14727, 30591, 358, 729, 478, 4610, 5023, 2858, 478, 4610, 11463, 2858, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 478, 4610, 310, 353, 478, 4610, 310, 1345, 3611, 16, 534, 359, 14727, 9003, 18241, 288, 203, 203, 565, 1450, 934, 429, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 654, 39, 3462, 1071, 283, 6397, 1345, 31, 203, 203, 203, 565, 2254, 5034, 1071, 284, 4610, 310, 5326, 273, 374, 31, 203, 377, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 729, 17393, 2937, 5157, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 283, 6397, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 729, 17631, 14727, 16507, 350, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 284, 4610, 9217, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 284, 4610, 28362, 31, 203, 203, 565, 871, 534, 359, 1060, 8602, 12, 11890, 5034, 19890, 1769, 203, 565, 871, 934, 9477, 12, 2867, 8808, 729, 16, 2254, 5034, 3844, 16, 1758, 293, 1773, 1769, 203, 565, 871, 3423, 9446, 82, 12, 2867, 8808, 729, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 534, 359, 1060, 16507, 350, 12, 2867, 8808, 729, 16, 2254, 5034, 19890, 1769, 203, 203, 10792, 3492, 13915, 916, 203, 203, 565, 3885, 261, 203, 3639, 1758, 389, 74, 4610, 310, 1345, 16, 203, 3639, 1758, 389, 266, 6397, 1345, 16, 203, 3639, 1758, 389, 266, 6397, 1669, 19293, 16, 203, 3639, 2254, 5034, 389, 74, 4610, 310, 5326, 9384, 203, 565, 262, 203, 3639, 1071, 203, 3639, 478, 4610, 310, 1345, 3611, 24899, 74, 4610, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./IFateRewardController.sol"; import "./IRewardSchedule.sol"; import "./MockLpToken.sol"; import "./IMockLpTokenFactory.sol"; // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once FATE is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract FateRewardControllerV2 is IFateRewardController { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfoV2 { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. bool isUpdated; // true if the user has been migrated from the v1 controller to v2 // // We do some fancy math here. Basically, any point in time, the amount of FATEs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accumulatedFatePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accumulatedFatePerShare` (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. } IERC20 public override fate; address public override vault; IFateRewardController[] public oldControllers; // The emission scheduler that calculates fate per block over a given period IRewardSchedule public override emissionSchedule; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public override migrator; // Info of each pool. PoolInfo[] public override poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfoV2)) internal _userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public override totalAllocPoint = 0; // The block number when FATE mining starts. uint256 public override startBlock; IMockLpTokenFactory public mockLpTokenFactory; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event ClaimRewards(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmissionScheduleSet(address indexed emissionSchedule); event MigratorSet(address indexed migrator); event VaultSet(address indexed emissionSchedule); event PoolAdded(uint indexed pid, address indexed lpToken, uint allocPoint); event PoolAllocPointSet(uint indexed pid, uint allocPoint); constructor( IERC20 _fate, IRewardSchedule _emissionSchedule, address _vault, IFateRewardController[] memory _oldControllers, IMockLpTokenFactory _mockLpTokenFactory ) public { fate = _fate; emissionSchedule = _emissionSchedule; vault = _vault; oldControllers = _oldControllers; mockLpTokenFactory = _mockLpTokenFactory; startBlock = _oldControllers[0].startBlock(); } function poolLength() external override view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public override onlyOwner { for (uint i = 0; i < poolInfo.length; i++) { require( poolInfo[i].lpToken != _lpToken, "add: LP token already added" ); } if (_withUpdate) { massUpdatePools(); } require( _lpToken.balanceOf(address(this)) >= 0, "add: invalid LP token" ); uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken : _lpToken, allocPoint : _allocPoint, lastRewardBlock : lastRewardBlock, accumulatedFatePerShare : 0 }) ); emit PoolAdded(poolInfo.length - 1, address(_lpToken), _allocPoint); } // Update the given pool's FATE allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; emit PoolAllocPointSet(_pid, _allocPoint); } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public override onlyOwner { migrator = _migrator; emit MigratorSet(address(_migrator)); } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public override { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } function migrate( IERC20 token ) external override returns (IERC20) { IFateRewardController oldController = IFateRewardController(address(0)); for (uint i = 0; i < oldControllers.length; i++) { if (address(oldControllers[i]) == msg.sender) { oldController = oldControllers[i]; } } require( address(oldController) != address(0), "migrate: invalid sender" ); IERC20 lpToken; uint256 allocPoint; uint256 lastRewardBlock; uint256 accumulatedFatePerShare; uint oldPoolLength = oldController.poolLength(); for (uint i = 0; i < oldPoolLength; i++) { (lpToken, allocPoint, lastRewardBlock, accumulatedFatePerShare) = oldController.poolInfo(poolInfo.length); if (address(lpToken) == address(token)) { break; } } // transfer all of the tokens from the previous controller to here token.transferFrom(msg.sender, address(this), token.balanceOf(msg.sender)); poolInfo.push( PoolInfo({ lpToken : lpToken, allocPoint : allocPoint, lastRewardBlock : lastRewardBlock, accumulatedFatePerShare : accumulatedFatePerShare }) ); emit PoolAdded(poolInfo.length - 1, address(token), allocPoint); uint _totalAllocPoint = 0; for (uint i = 0; i < poolInfo.length; i++) { _totalAllocPoint = _totalAllocPoint.add(poolInfo[i].allocPoint); } totalAllocPoint = _totalAllocPoint; return IERC20(mockLpTokenFactory.create(address(lpToken), address(this))); } function userInfo( uint _pid, address _user ) public override view returns (uint amount, uint rewardDebt) { UserInfoV2 memory user = _userInfo[_pid][_user]; if (user.isUpdated) { return (user.amount, user.rewardDebt); } else { return oldControllers[0].userInfo(_pid, _user); } } function _getUserInfo( uint _pid, address _user ) internal view returns (IFateRewardController.UserInfo memory) { UserInfoV2 memory user = _userInfo[_pid][_user]; if (user.isUpdated) { return IFateRewardController.UserInfo(user.amount, user.rewardDebt); } else { (uint amount, uint rewardDebt) = oldControllers[0].userInfo(_pid, _user); return IFateRewardController.UserInfo(amount, rewardDebt); } } // View function to see pending FATE tokens on frontend. function pendingFate(uint256 _pid, address _user) external override view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; IFateRewardController.UserInfo memory user = _getUserInfo(_pid, _user); uint256 accumulatedFatePerShare = pool.accumulatedFatePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 fatePerBlock = emissionSchedule.getFatePerBlock(startBlock, pool.lastRewardBlock, block.number); uint256 fateReward = fatePerBlock.mul(pool.allocPoint).div(totalAllocPoint); accumulatedFatePerShare = accumulatedFatePerShare.add(fateReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accumulatedFatePerShare).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); } } function getNewRewardPerBlock(uint pid1) public view returns (uint) { uint256 fatePerBlock = emissionSchedule.getFatePerBlock(startBlock, block.number - 1, block.number); if (pid1 == 0) { return fatePerBlock; } else { return fatePerBlock.mul(poolInfo[pid1 - 1].allocPoint).div(totalAllocPoint); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 fatePerBlock = emissionSchedule.getFatePerBlock(startBlock, pool.lastRewardBlock, block.number); uint256 fateReward = fatePerBlock.mul(pool.allocPoint).div(totalAllocPoint); if (fateReward > 0) { fate.transferFrom(vault, address(this), fateReward); pool.accumulatedFatePerShare = pool.accumulatedFatePerShare.add(fateReward.mul(1e12).div(lpSupply)); } pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for FATE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; IFateRewardController.UserInfo memory user = _getUserInfo(_pid, msg.sender); updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accumulatedFatePerShare).div(1e12).sub(user.rewardDebt); _safeFateTransfer(msg.sender, pending); emit ClaimRewards(msg.sender, _pid, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); uint userBalance = user.amount.add(_amount); _userInfo[_pid][msg.sender] = UserInfoV2({ amount : userBalance, rewardDebt : userBalance.mul(pool.accumulatedFatePerShare).div(1e12), isUpdated : true }); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; IFateRewardController.UserInfo memory user = _getUserInfo(_pid, msg.sender); require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accumulatedFatePerShare).div(1e12).sub(user.rewardDebt); _safeFateTransfer(msg.sender, pending); emit ClaimRewards(msg.sender, _pid, pending); uint userBalance = user.amount.sub(_amount); _userInfo[_pid][msg.sender] = UserInfoV2({ amount : userBalance, rewardDebt : userBalance.mul(pool.accumulatedFatePerShare).div(1e12), isUpdated : true }); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // claim any pending rewards from this pool, from msg.sender function claimReward(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; IFateRewardController.UserInfo memory user = _getUserInfo(_pid, msg.sender); updatePool(_pid); uint256 pending = user.amount.mul(pool.accumulatedFatePerShare).div(1e12).sub(user.rewardDebt); _safeFateTransfer(msg.sender, pending); emit ClaimRewards(msg.sender, _pid, pending); _userInfo[_pid][msg.sender] = UserInfoV2({ amount : user.amount, rewardDebt : user.amount.mul(pool.accumulatedFatePerShare).div(1e12), isUpdated : true }); } // claim any pending rewards from this pool, from msg.sender function claimRewards(uint256[] calldata _pids) external { for (uint i = 0; i < _pids.length; i++) { claimReward(_pids[i]); } } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; IFateRewardController.UserInfo memory user = _getUserInfo(_pid, msg.sender); pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); _userInfo[_pid][msg.sender] = UserInfoV2({ amount : 0, rewardDebt : 0, isUpdated : true }); } // Safe fate transfer function, just in case if rounding error causes pool to not have enough FATEs. function _safeFateTransfer(address _to, uint256 _amount) internal { uint256 fateBal = fate.balanceOf(address(this)); if (_amount > fateBal) { fate.transfer(_to, fateBal); } else { fate.transfer(_to, _amount); } } function setEmissionSchedule( IRewardSchedule _emissionSchedule ) public onlyOwner { // pro-rate the pools to the current block, before changing the schedule massUpdatePools(); emissionSchedule = _emissionSchedule; emit EmissionScheduleSet(address(_emissionSchedule)); } function setVault( address _vault ) public override onlyOwner { // pro-rate the pools to the current block, before changing the schedule vault = _vault; emit VaultSet(_vault); } }
Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public override totalAllocPoint = 0;
14,083,687
[ 1, 5269, 13481, 3143, 18, 6753, 506, 326, 2142, 434, 777, 13481, 3143, 316, 777, 16000, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 3849, 2078, 8763, 2148, 273, 374, 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.4.24; import "./safeMath.sol"; import "./NameFilter.sol"; // datasets library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner addr bytes32 winnerName; // winner name uint256 amountWon; uint256 newPot; uint256 genAmount; uint256 potAmount; // amount added to the pot } struct Player { address addr; // player addr bytes32 name; uint256 names; uint256 win; // jackpot won uint256 gen; // key reward won uint256 aff; // ref reward uint256 lrnd; // last round played uint256 laff; // last reffer } struct PlayerRounds { uint256 eth; // Amount of ETH puts into cur round uint256 keys; // # of keys uint256 mask; } struct Round { uint256 plyr; // round leader's pID uint256 end; // ending time timeStamp bool ended; // is ended uint256 strt; // starting time uint256 keys; // number of keys uint256 eth; // total eth in uint256 pot; // total jackpot uint256 mask; } } contract Ape3D { using SafeMath for *; using NameFilter for string; string constant public name = "Ape3D long"; string constant public symbol = "A3D"; // game symbol // Game data address public devs; // dev addr bool public activated_ = false; uint256 constant private rndInit_ = 24 hours; uint256 constant private rndInc_ = 60 seconds; uint256 constant private rndMax_ = 24 hours; uint256 public rID_; // roundID uint256 public registrationFee_ = 10 finney; // register fee // player data uint256 public pID_; // Total number of players mapping(address => uint256) public pIDxAddr_; //(addr => pID)addr to pID mapping(bytes32 => uint256) public pIDxName_; //(name => pID)name to pID mapping(uint256 => F3Ddatasets.Player) public plyr_; //(pID => data)pID to player data mapping(uint256 => mapping(uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; //(pID => rID => data mapping(uint256 => mapping(bytes32 => bool)) public plyrNames_; // round data mapping(uint256 => F3Ddatasets.Round) public round_; //(rID => data) rID to round data mapping(uint256 => uint256) public rndEth_; //(rID => data) rID to round total eth // emit when a player register a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, uint256 amountPaid, uint256 timeStamp ); event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 genAmount ); event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 genAmount, uint256 potAmount ); event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 genAmountf ); event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 genAmount ); modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } // anti-contract modifier isHuman() { require(msg.sender == tx.origin); _; } modifier onlyDevs() { require(msg.sender == devs, "msg sender is not a dev"); _; } modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } function activate() public onlyDevs { require(activated_ == false, "Ape3D already activated"); activated_ = true; // start the first round rID_ = 1; round_[1].strt = now; round_[1].end = now + rndInit_; } constructor() public { devs = msg.sender; } /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePlayer(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; buyCore(_pID, plyr_[_pID].laff, _eventData_); } // assigning a new pID to a new player function determinePlayer(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; if (_pID == 0) { // assigning a new pID. determinePID(msg.sender); _pID = pIDxAddr_[msg.sender]; bytes32 _name = plyr_[_pID].name; uint256 _laff = plyr_[_pID].laff; pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // sets "true" for new player _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } // determine player ID function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; // return true for new player return (true); } else { return (false); } } // register name using ref's ID function registerNameXname(string _nameString, bytes32 _affCode) external payable { require(msg.value >= registrationFee_, "umm..... you have to pay the name fee"); address _addr = msg.sender; bytes32 _name = NameFilter.nameFilter(_nameString); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID = 0; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer); } // core function for register name function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer) private { // check if the name is taken if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); // setting up player name and id plyr_[_pID].name = _name; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; } // register fee sends to dev address(devs).transfer(10 finney); emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, msg.value, now); } // buy key using refs name function buyXname(bytes32 _affCode) isActivated() isHuman() isWithinLimits(msg.value) external payable { F3Ddatasets.EventReturns memory _eventData_ = determinePlayer(_eventData_); // getting player's ID uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last ref code saved _affID = plyr_[_pID].laff; } else { // getting the ref's pID _affID = pIDxName_[_affCode]; // If the ref's pID is new if (_affID != plyr_[_pID].laff) { // Update plyr_[_pID].laff = _affID; } } buyCore(_pID, _affID, _eventData_); } // use vault to rebuy keys, with name as ref function reLoadXname(bytes32 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) external { F3Ddatasets.EventReturns memory _eventData_; // get player ID uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == '' || _affCode == plyr_[_pID].name) { // getting ref pID _affID = plyr_[_pID].laff; } else { // getting ref pID _affID = pIDxName_[_affCode]; // If the ref's pID is new if (_affID != plyr_[_pID].laff) { // Update plyr_[_pID].laff = _affID; } } reLoadCore(_pID, _affID, _eth, _eventData_); } /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.genAmount ); } } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return (_eventData_); } /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns (uint256) { return ((((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask)); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 10000000000) //0.00000001eth { // calculate key received uint256 _keys = keysRec(round_[_rID].eth,_eth); // at least one key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leader if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndEth_[_rID] = _eth.add(rndEth_[_rID]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _eth, _keys, _eventData_); } } function endTx(uint256 _pID, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.genAmount, _eventData_.potAmount ); } /** * @dev distributes eth based on fees to dev and aff */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _devs = (_eth.mul(3)) / 100; address(devs).transfer(_devs); _devs = 0; // distribute share to affiliate uint256 _aff = _eth / 10; if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _devs = _aff; } if (_devs > 0) { address(devs).transfer(_devs); _devs = 0; } return (_eventData_); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(67)) / 100; // calculate pot uint256 _pot = (_eth.mul(20)) / 100; // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return (_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns (uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); //calculate & return dust return (_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local ID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(80)) / 100; uint256 _gen = 0; uint256 _res = _pot.sub(_win); plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_); round_[_rID].pot = _res; return (_eventData_); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns (uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is a winner if (round_[_rID].plyr == _pID) { return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 (plyr_[_pID].win).add(((round_[_rID].pot).mul(80)) / 100), //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } else { return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 (plyr_[_pID].win), //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } } else{ return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } } /** * @dev returns all current round info needed for front end * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256) { // setup local rID uint256 _rID = rID_; return ( _rID, //0 round_[_rID].keys, //1 round_[_rID].end, //2 round_[_rID].strt, //3 round_[_rID].pot, //4 round_[_rID].plyr, // 5 plyr_[round_[_rID].plyr].addr, //6 plyr_[round_[_rID].plyr].name, //7 round_[_rID].eth //8 ); } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * @return time left in seconds */ function getTimeLeft() public view returns(uint256,uint256,uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) return((round_[_rID].end),_now, (round_[_rID].end).sub(_now)); // return( ); else return(0,0,0); } /** * @dev withdraws all of your earnings. */ function withdraw() isActivated() isHuman() external { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // pay the player if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.genAmount ); } else { // in any other situation // get their earnings _eth = withdrawEarnings(_pID); // pay the player if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns (uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vault uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return (_earnings); } /** * @dev returns the amount of keys you would get given an amount of eth. * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns (uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { return keysRec(round_[_rID].eth, _eth); } else { // rounds over. need keys for new round return keys(_eth); } } /** * @dev returns current eth price for X keys. * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns (uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ethRec(round_[_rID].keys + _keys,_keys); else // rounds over. need price for new round return eth(_keys); } function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } function keys(uint256 _eth) internal pure returns(uint256) { return (10000*((_eth.mul(1000000000000000000)).sqrt())); } function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } function eth(uint256 _keys) internal pure returns(uint256) { return ((10000000000).mul(_keys.sq())) / ((1000000000000000000).sq()); } }
call end tx function to fire end tx event.
endTx(_pID, _eth, _keys, _eventData_);
23,170
[ 1, 1991, 679, 2229, 445, 358, 4452, 679, 2229, 871, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 679, 4188, 24899, 84, 734, 16, 389, 546, 16, 389, 2452, 16, 389, 2575, 751, 67, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract OnChainSands is ERC721, ERC721Enumerable, Ownable { using Counters for Counters.Counter; using SafeMath for uint256; Counters.Counter private _tokenIdCounter; uint private constant maxTokensPerTransaction = 30; uint256 private tokenPrice = 30000000000000000; //0.03 ETH uint256 private constant nftsNumber = 5000; uint256 private constant nftsPublicNumber = 4950; constructor() ERC721("OnChain Sands", "SND") { _tokenIdCounter.increment(); } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // 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); } function safeMint(address to) public onlyOwner { _safeMint(to, _tokenIdCounter.current()); _tokenIdCounter.increment(); } // The following functions are overrides required by Solidity. function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function toHashCode(uint256 value) internal pure returns (string memory) { if (value == 0) { return "000000"; } uint256 i; bytes memory buffer = "000000"; for(i=6;i>0;i--) { if (value % 16 < 10) buffer[i-1] = bytes1(uint8(48 + uint256(value % 16))); else buffer[i-1] = bytes1(uint8(55 + uint256(value % 16))); value /= 16; } return string(buffer); } function getFarObject(uint256 num) internal pure returns (string memory) { string[4] memory far; far[0] ='M431.741,537.724 371.85,467.096 321.582,517.364 254.859,442.361 160.11,537.109'; far[1] ='M191,556l219-2l-99-117L191,556z'; far[2] ='M244,557 238,488 248,488 238,413 298,398 296,389 424,407 401,484 391,487 383,555'; far[3] ='M209,511c0-0,36-8,36-8 s10-1,11-1s17-15,17-16s0-6,0-6l19-0v-6h9l1-6h4v-1 h67v2h5v4c0,0,11-1,11,0s0,8,0,8h20v6l18,18h7v10v70H209 L209,511z'; return far[num-1]; } function getSun(uint256 num) internal pure returns (string memory) { uint256 suns; uint256 suns_m; suns_m = 650299126634312082; suns = 709260192684279125512259162535278106613289157619291124044823099706295099; if (num >= 8) { suns = num == 8 ? suns_m : suns_m / 1000000000; } else { if (num > 0) suns = suns / (1000 ** (num*3)); } string memory output = string(abi.encodePacked('cx="',toString((suns/1000000)%1000),'" cy="',toString((suns/1000)%1000), '" r="',toString(suns%1000),'"')); return output; } //this feature is just for fun, it's pointless. function getCamel(uint256 num) internal pure returns (string memory) { uint256[50] memory xtypes; uint256 pos; uint256 i; uint256 temp; uint256 sym; uint256 lines; xtypes[0] = 2750871777490806264085493004602956112481215626846361120; // Elon Musk is a poser xtypes[1] = 24031940146303221873185246330856176777890234172085460524828847635091787832103; xtypes[2] = 4369554406778136407906521031351492442121714090311337998835645029932110349922; xtypes[3] = 35339669699060465125668189898147169548632576962648599291375229098669428362322; xtypes[4] = 672238645676028630017590070904525; xtypes[11] = 37599700675902714367317740679304042296080055052422520140113640294389393350439; xtypes[12] = 38087302781903350862724587794493881498317283716547227642212787098338845152311; xtypes[13] = 1114275929128553399568145623741250323077119217211655860047041411166003561237; xtypes[14] = 44483940829496349223937135327653774303045114145795750475934727822431742908025; xtypes[15] = 1301031010810467202189960410466201454370628906584976487492660977313; xtypes[21] = 24511554605809013553427690817438832449166603887000346203695542442847542862631; xtypes[22] = 24712231507965098789272277915974614596914779217528115716846960336470200999989; xtypes[23] = 31779261119830188930260713981005416210882557915559935577937916313743035255330; xtypes[24] = 30845749996097297930742408311135328346981512733480170301818670564314058110498; xtypes[25] = 4393324743237794958108912339045511528520735357988065415454558326487042311245; xtypes[26] = 4383618393247594429327385840719100733921976757672061077695343950821928420434; xtypes[27] = 28260977779972716408629221197954496518888178178346784762024000144425; // I wrote that because I'm jealous of his billions xtypes[31] = 33981201337895841066299736423112852304759862823304893271895015697500599799591; xtypes[32] = 38092437674498035584450155165625035089506200894468052066380022772320589009972; xtypes[33] = 1002964437672768398493084675030519774534336229557529541653364574576256516854; xtypes[34] = 41202914189462662695915620887590875333337880836299726911136825280773640739640; xtypes[35] = 40993983140047288513282733679841254915488686784624912185639295148702690920129; xtypes[36] = 43462155136449166491448379421314888609432193428547199763947083681431896678423; xtypes[37] = 3091541931616987385254478349605488253295528003625843124585170727615066703541; xtypes[38] = 42893843881028951002600077923910138109116652418088673519145098082818520534773; xtypes[39] = 35790225028626312902234269550783631619805539570794490376389285434126321176320; xtypes[40] = 23946826271475684407; // and the fact that he's sexy xtypes[41] = 32696238382569806469557342148762393436204618157687364688486249358066242446087; xtypes[42] = 30829847781535805781250327403060765435737126585110613555906562372477089399884; xtypes[43] = 2322370439730553613354915887410243625117939153279733562435129926126979548749; xtypes[44] = 3077242879332650009073929722759956366751482431073885344923252432370954176881; xtypes[45] = 35126784166904065671947169645446477285741344117817602589955598641710815590065; xtypes[46] = 2978473281905248387737881203435264718697731825484007630263831601596209749570; xtypes[47] = 542357; bytes memory buffer = new bytes(500); temp = xtypes[1]; pos=0; for(lines=1;lines<=10;lines++) { if (xtypes[10*(num-1) + lines] == 0) break; temp = xtypes[10*(num-1) + lines]; for(i=0;i<=50;i++) { if (temp==0) break; sym = temp%32; temp /= 32; buffer[pos++] = bytes1(uint8((xtypes[0]/(128**sym))%128)); } } bytes memory buffer2 = new bytes(pos); for(i=0;i<pos;i++) buffer2[i] = buffer[i]; return string(buffer2); } // programmers are the coolest people. function getDune1(uint256 num) internal pure returns (string memory) { string[2] memory dune; dune[0] = 'M-68,1082l1157,6l-19-577c0,0-39-6-117-6 s-102,8-185,16s-118,8-183,8s-181-21-331-21s-286,42-286,42 L-68,1082z'; dune[1] = 'M1089,1015l-1157,5l19-478c0,0,42-15,119-22 c77-6,173-8,255,0c82,9,159,12,225,12s188-14,338-14 s165,33,165,33L1089,1015z'; return dune[num-1]; } // and humble. function getDune2(uint256 num) internal pure returns (string memory) { string[4] memory dune; dune[0] = 'M-39,1013l1181,40c0,0-18-502-77-485 c-185,52-250-23-416-5c-77,8-148,29-324-22S-61,574-61,614 L-39,1013z'; dune[1] = 'M1140,1013l-1181,40c0,0-37-507,23-496c189,34,315-4,482,13 c77,8,205,51,391-21c170-66,270,61,273,69L1140,1013z'; dune[2] = 'M-39,1016l1181,40c0,0-18-502-77-485 c-185,52-211-40-377-22c-77,8-203,37-380,25 c-182-12-327,14-330,22L-39,1016z'; dune[3] = 'M1142,1016l-1181,40c0,0-66-554-9-530 c181,77,299,26,464,33c77,3,207,45,382,14 c180-32,327,14,330,22L1142,1016z'; return dune[num-1]; } function tokenURI(uint256 tokenId) pure public override(ERC721) returns (string memory) { uint256[17] memory xtypes; string[5] memory colors; string[4] memory dune3; string[4] memory dune31; string[4] memory dune32; string[27] memory parts; uint256[12] memory params; string[6] memory obj1; string[6] memory obj2; uint256 pos; uint256 rand = random(string(abi.encodePacked('Sand',toString(tokenId)))); params[0] = 1 + ((rand/10) % 5);// camel= params[1] = 1 + ((rand/1000) % 33); // pallette= params[2] = 1 + ((rand/10000) % 4); // dune main params[3] = 1 + ((rand/10000) % 2); // dune top params[4] = 1 + ((rand/100000) % 4); // dune bottom params[5] = 1 + ((rand/1000000000) % 4); // pyr= params[6] = 1 + ((rand/10000000000) % 5); // obj= params[7] = 1 + ((rand/100000000) % 5); // sun obj1[0] = 'M128,897c4,1,8,6,15,7 c8-5,15-11,20-17c0-2,1-5,1-6c0-0,0-0,0-0 c0-0,0-0,0-0c2-3,5-4,7-3c0-0,0-1,1-1 c-2-2-8-1-12,4c-3,5-6,6-6,6c-2,0-3,0-4,0 c-0-0-0-0-0-0c-0-2-3-4-6-4l-0-2l-3,1l0,2 c-2,1-3,4-2,7c0,0,0,0,0,0c-4,1-11,2-16,2 c-8-0-8,6-8,6l9-2C125,896,127,896,128,897z'; obj1[1] = 'M177,903 214,864 186,888 177,872 181,892 167,904 160,889 168,880 158,885 140,842 152,878 134,874 154,884 164,915 171,915 175,905 190,903'; obj1[2] = 'M173,924l-2-9l-8-4l-5-9 l-0,11l-7,3l-0,3l-16,13l2,3l6-0l10-0l2-2l3,1l7-1 l1-2l4-1l10,3L173,924z'; obj1[3] = 'M102,924c42,0,79-13,96-32 l-1-10l-19-6l-9,4l-6-6l-20-11l-11,3l-1,37l-8,5l-6-2 l-8,2l-5,17C100,924,101,924,102,924z'; obj1[4] = 'M196,909l-27-60l2-3l-2-2 l2-1l-7-3l0,6l-14,16l1,11l0-9l13-11l2,0l2,5 l-2,44l3-7l0,3l2-30l0,1c0,7,2,21,2,21 c0-0,0-9,0-14l13,34L196,909z'; obj2[0] = 'M176,873c0,0-92,25-89,38 c3,13,43,1,56-8C157,895,176,873,176,873z'; obj2[1] = 'M135,907 164,913 164,915 171,915 145,929 112,932 145,925 160,916 151,912 145,914 147,911'; obj2[2] = 'M164,927 159,927 155,929 155,931 141,931 140,930 150,922 139,929 138,929 133,933 137,932 134,935 155,931 155,932 158,934 163,932 166,930'; obj2[3] = 'M188,900l-14-21l-4,1 c0,0,7,19,7,20c-0,0-6,1-6,1l-18-6l-2-17l-3,13l-8-21 l-3,2l0,13l-43,12l-6,9l-43,6l-6,6l67,1l9-0 C142,922,170,913,188,900z'; obj2[4]= 'M189,905 100,921 96,944 107,925 196,909'; // Frank Herbert is a genius. dune3[0] = 'M789.651,612.665c-75.205-13.229-180.045,29.189-247.215,32.078c-67.168,2.892-214.902-55.596-254.981-57.02c-80.609-2.861-205.862,94.49-292.672,100.213c-15.255,1.007-30.625-0.204-46.191-2.981v364.425l1091.444-8.328V687.689C964.066,678.827,883.855,629.24,789.651,612.665z'; dune3[1] = 'M-132,707c93-1,328-89,431-72 c102,17,188,72,270,68c81-4,199-87,275-85s268,142,268,142 v254H-98L-132,707z'; dune3[2] = 'M1231.049,614.778c-106.1-3.109-270.963,102.704-385.223,108.925c-114.258,6.229-233.418-65.354-377.06-87.139c-99.948-15.158-239.281,33.44-328.552,36.751c-89.269,3.313-285.609-63.696-338.877-65.326c-107.132-3.277-14.89,534.698-14.89,534.698l1120.001-20.622C906.449,1122.064,1337.147,617.889,1231.049,614.778z'; dune3[3] = 'M-47.384,729.587l16.5,334.482H1082.06l-7.499-400.48c0,0-143.994,46.509-293.986,48.009c-138.278,1.383-269.985-73.507-410.979-102.005S-47.384,729.587-47.384,729.587'; dune31[0] = 'M730.696,695.521c-14.66-64.234,54.479-83.549,53.738-83.668c-74.773-10.486-176.365,30.068-241.998,32.891c-65.18,2.806-206.219-52.184-251.139-56.739c10.547,3.674,18.777,12.776,20.959,31.223c5.711,48.342-25.114,246.768-200.632,410.215l572.048,6.992h0.246c157.754-55.303,336.631-126.377,336.631-164.342C1020.549,804.177,747.467,768.968,730.696,695.521z'; dune31[1] = 'M569,702 c-81,4-167-51-270-68c-90-14-282,51-391,68l-6,301l0,8h750 C841,871,874,687,868,644c-2-15-9-23-19-26c-1-0-2-0-3-0 C769,615,651,698,569,702z'; dune31[2] = 'M390.417,731.489c-19.484-73.591,72.4-95.72,71.42-95.854c-99.376-12.017-234.395,34.446-321.621,37.682c-54.263,2.01-148.083-21.957-225.287-41.429c5.73,98.433,58.558,405.557,495.521,392.111c96.733-2.977,150.2,2.841,173.166,14.275c110.086-40.351,192.021-78.959,192.021-104.494C775.637,855.974,412.705,815.635,390.417,731.489z'; dune31[3] = 'M1143.557,771.596C842.766,774.434,590.294,994.69,563.871,1018.5H281.277c219.414-27.692,269.289-134.762,270.71-200.116c1.5-68.996-181.491-76.496-295.484-116.994c-107.063-38.035,57.096-89.3,77.455-95.395C186.829,603.571-47.384,729.587-47.384,729.587l14.307,321.913l1176.634,27.58C1143.557,1079.08,1461.541,768.596,1143.557,771.596z'; dune32[0] = 'M312.256,619.224c-2.186-18.486-10.448-27.592-21.027-31.25c-1.286-0.119-2.543-0.203-3.773-0.246c-80.611-2.863-205.862,94.489-292.671,100.211c-15.255,1.007-30.627-0.204-46.193-2.981v369.479H83.292C283.871,886.871,318.262,670.06,312.256,619.224z'; dune32[1] = 'M296,634 c-104-14-335,72-428,73l33,306h296c150-49,320-113,320-147 c0-60-259-92-275-158C229,651,283,636,296,634z'; dune32[2] = ''; dune32[3] = ''; // His War of the Worlds is a masterpiece. xtypes[0] = 438473426514619468937593363674906600980101972218980261389738755026321310; xtypes[1] = 1528428735494740386746687706769036728542265312936553054402188188078571243; xtypes[2] = 1576159433658212066304323894815932062177799089437395523990699050641915806; xtypes[3] = 1638277479168345925933593678264841420808332802796276121428815506753716126; xtypes[4] = 1482277213785937432487838137602393875317079519468030334287176488800222955; xtypes[5] = 569254049910285240562266942057277174170434705955446158280559749706542294; xtypes[6] = 695961355261660318153968727586838433117983201812599465335857818068058111; xtypes[7] = 1499951127606893309180610179916526153806597374206025036948893607141571007; xtypes[8] = 1487975643258097207966143169235216509055880303550960490725369271497513569; xtypes[9] = 893871907223691020346594411790439061317907470229888515211998968157829111; xtypes[10] = 1456322660702981972363882139452691332072845879862426480408917545756655090; xtypes[11] = 1414100953265237643112910920600703942226523030837917351177428632577495874; xtypes[12] = 1412526850302830771701738382967853559447456676243931652623233627352724185; xtypes[13] = 956176030089680310714094738241368283497248873645169781803481032958345082; xtypes[14] = 407203048447432245888292259364249687668615656070679106091707478370827939; xtypes[15] = 720473443048720196433395035253138729115353664155452813862022957330631299; xtypes[16] = 1219326055746586710817491577091388615; pos = (params[1]-1) * 5; colors[0] = toHashCode(xtypes[pos/10] / (16777216 ** (pos%10)) % 16777216); pos = (params[1]-1) * 5 + 1; colors[1] = toHashCode(xtypes[pos/10] / (16777216 ** (pos%10)) % 16777216); pos = (params[1]-1) * 5 + 2; colors[2] = toHashCode(xtypes[pos/10] / (16777216 ** (pos%10)) % 16777216); pos = (params[1]-1) * 5 + 3; colors[3] = toHashCode(xtypes[pos/10] / (16777216 ** (pos%10)) % 16777216); pos = (params[1]-1) * 5 + 4; colors[4] = toHashCode(xtypes[pos/10] / (16777216 ** (pos%10)) % 16777216); // Who's stronger, the camel or the Bedouin? parts[0] = '<svg version="1.1" id="Layer_2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="1000px" height="1000px" viewBox="0 0 1000 1000" enable-background="new 0 0 1000 1000" xml:space="preserve"> <linearGradient id="mainGradient" gradientUnits="userSpaceOnUse" x1="-162.3992" y1="118.0994" x2="-162.3993" y2="1117.9104" gradientTransform="matrix(1 0 0 -1 662.3999 1118.0991)"> <stop offset="0.64" style="stop-color:#'; // 2 parts[1] = '"/> <stop offset="1" style="stop-color:#'; // 3 parts[2] = '"/> </linearGradient> <rect x="0.001" y="0.189" fill="url(#mainGradient)" width="1000" height="1000"/> <circle opacity="0.1" fill="#'; // 1 parts[3] = string(abi.encodePacked('" cx="44" cy="823" r="99"/> <radialGradient id="sunGradient" ',getSun(params[7]*2-2),' gradientUnits="userSpaceOnUse"> <stop offset="0.7" style="stop-color:#')); // 1 parts[4] = '"/> <stop offset="1" style="stop-color:#'; // 2 parts[5] = string(abi.encodePacked('"/> </radialGradient> <circle opacity="0.8" fill="url(#sunGradient)" ',getSun(params[7]*2-2),'/>')); // 1 parts[6] = ''; // 1 parts[7] = ''; // 2 parts[8] = ''; // 1 parts[9] = ''; // 1 parts[10] = ''; // 2 parts[11] = ''; // 1 parts[12] = ''; // 1 parts[13] = ''; // 2 parts[14] = '<g> <path opacity="0.11" fill="#'; // 1 parts[15] = '" d="M668,423c0,0,313-0,303-28 c-10-28-397-48,15-46c301,2,196,46,460,43 c258-3,484-60,485-17c1,43-290,24-290,50s288,9,478,12 c189,3,341-83,535-26c194,56,322,32,517,5 c194-27,140,0,427,0c287,0,1180,0,1180,0v-31H3607c0,0-137-11-283-10 c-146,0-162,33-394-7c-232-41-312-43-420-24 c-107,18-255,68-395,74s-397,18-398,7c-1-10,447-26,446-65 c-1-38-176-42-391-25c-215,16-395-14-568-19 c-172-4-626-8-627,25s323,25,322,50c-0,9-593,3-593,3H-36v27 h478C442,421,553,423,668,423z"/> <path opacity="0.11" fill="#'; // 1 parts[16] = '" d="M668,404c0,0,322,12,312-15 c-10-28-804-56,8-62c301-2,239,37,503,34 c258-3,565-42,569,1c2,29-381,32-417,61 c-23,18,273,12,470,7c189-5,513-94,714-52 c212,44,184,46,379,18c194-27,188,1,475,1c287,0,1096,0,1096,0 v-20c0,0-1102,0-1175,0s-137-13-284-13c-146,0-161,25-393-16 c-232-41-315-31-422-12c-107,18-250,68-389,74s-432,24-432,13 c0-13,458-25,473-71c12-37-172-54-387-38 c-215,16-395-14-568-19c-172-4-620,7-621,41 c-1,34,319,32,321,51c0,9-598-12-598-12H-36v27h478 C442,403,553,404,668,404z"/> <animateMotion path="M 0 0 L -3750 40 Z" dur="250s" repeatCount="indefinite" /> </g> <path opacity="0.25" fill="#'; // 5 parts[17] = string(abi.encodePacked('" d="',getFarObject(params[5]),'"/> <path fill="#')); // 5 parts[18] = string(abi.encodePacked('" d="',getDune1(params[3]),'"/> <g> <path fill="#')); // 4 parts[19] = string(abi.encodePacked('" d="',getCamel(params[0]),'"/> <animateMotion path="m 0 0 h -5000" dur="2500s" repeatCount="indefinite" /> </g> <path fill="#')); // 4 parts[20] = string(abi.encodePacked('" d="',getDune2(params[4]),'"/> <path fill="#')); // 2 parts[21] = string(abi.encodePacked('" d="',dune3[params[2]-1],'"/> <linearGradient id="sandGradient" gradientUnits="userSpaceOnUse" x1="-1424" y1="658" x2="-456" y2="658" gradientTransform="matrix(1 0 0 1 1324.7998 158.1992)"> <stop offset="0" style="stop-color:#')); // 2 parts[22] = '"/> <stop offset="0.8" style="stop-color:#'; // 3 parts[23] = string(abi.encodePacked('"/> </linearGradient> <path opacity="0.35" fill="url(#sandGradient)" d="',dune31[params[2]-1],'"/> <path opacity="0.35" fill="#')); // 3 parts[24] = string(abi.encodePacked('" d="',dune32[params[2]-1],'"/> <path opacity="0.1" fill="#')); // 3 parts[25] = string(abi.encodePacked('" d="',obj2[params[6]-1],'"/> <path opacity="0.4" fill="#')); // 3 parts[26] = string(abi.encodePacked('" d="',obj1[params[6]-1],'"/> </svg> ')); // Stronger is the earthworm. string memory output = string(abi.encodePacked(parts[0],colors[1],parts[1],colors[2],parts[2])); output = string(abi.encodePacked(output,colors[0],parts[3],colors[0],parts[4],colors[1] )); output = string(abi.encodePacked(output,parts[5],colors[0],parts[6],colors[0] )); output = string(abi.encodePacked(output,parts[7],colors[1],parts[8],colors[0])); output = string(abi.encodePacked(output,parts[9],colors[0],parts[10],colors[1] )); output = string(abi.encodePacked(output,parts[11],colors[0],parts[12],colors[0])); output = string(abi.encodePacked(output,parts[13],colors[1],parts[14],colors[0] )); output = string(abi.encodePacked(output,parts[15],colors[0],parts[16],colors[4])); output = string(abi.encodePacked(output,parts[17],colors[4],parts[18],colors[3] )); output = string(abi.encodePacked(output,parts[19],colors[3],parts[20],colors[1])); output = string(abi.encodePacked(output,parts[21],colors[1],parts[22],colors[2])); output = string(abi.encodePacked(output,parts[23],colors[2],parts[24],colors[2])); output = string(abi.encodePacked(output,parts[25],colors[2],parts[26])); // please don't scold me for the quality of my code, I've been programming in PHP for 10 years string[11] memory aparts; aparts[0] = '[{ "trait_type": "Main", "value": "'; aparts[1] = toString(params[0]); aparts[2] = '" }, { "trait_type": "Palette", "value": "'; aparts[3] = toString(params[1]); aparts[4] = '" }, { "trait_type": "Near Object", "value": "'; aparts[5] = toString(params[6]); aparts[6] = '" }, { "trait_type": "Far Object", "value": "'; aparts[7] = toString(params[5]); aparts[8] = '" }, { "trait_type": "Sun", "value": "'; aparts[9] = toString(params[7]); aparts[10] = '" }]'; // they're going to make me squeeze Doom into the next collection // help... string memory strparams = string(abi.encodePacked(aparts[0], aparts[1], aparts[2], aparts[3], aparts[4], aparts[5])); strparams = string(abi.encodePacked(strparams, aparts[6], aparts[7], aparts[8], aparts[9], aparts[10])); // they made me write this code string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "OnChain Sands", "description": "Beautiful views, completely generated OnChain","attributes":', strparams, ', "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } function claimdQw4w9WgXcQ() public { require(_tokenIdCounter.current() <= 500, "Tokens number to mint exceeds number of public tokens"); _safeMint(msg.sender, _tokenIdCounter.current()); _tokenIdCounter.increment(); } // why are you reading this? is there something between us? function withdraw() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } // they won't fall for it a second time function buySands(uint tokensNumber) public payable { require(tokensNumber > 0, "Wrong amount"); require(tokensNumber <= maxTokensPerTransaction, "Max tokens per transaction number exceeded"); require(_tokenIdCounter.current().add(tokensNumber) <= nftsPublicNumber, "Tokens number to mint exceeds number of public tokens"); require(tokenPrice.mul(tokensNumber) <= msg.value, "Ether value sent is too low"); for(uint i = 0; i < tokensNumber; i++) { _safeMint(msg.sender, _tokenIdCounter.current()); _tokenIdCounter.increment(); } } } /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <[email protected]> library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT 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 "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./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 String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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); }
Inspired by OraclizeAPI's implementation - MIT license https:github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); }
599,747
[ 1, 382, 1752, 2921, 635, 531, 354, 830, 554, 2557, 1807, 4471, 300, 490, 1285, 8630, 2333, 30, 6662, 18, 832, 19, 280, 10150, 554, 19, 546, 822, 379, 17, 2425, 19, 10721, 19, 70, 9452, 27879, 70, 20, 4449, 71, 27, 72, 26, 1340, 3437, 8204, 5193, 26, 71, 30234, 3247, 26, 4366, 29, 73, 11180, 4848, 73, 28, 19, 280, 10150, 554, 2557, 67, 20, 18, 24, 18, 2947, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 377, 445, 1762, 12, 11890, 5034, 460, 13, 2713, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 203, 3639, 309, 261, 1132, 422, 374, 13, 288, 203, 5411, 327, 315, 20, 14432, 203, 3639, 289, 203, 3639, 2254, 5034, 1906, 273, 460, 31, 203, 3639, 2254, 5034, 6815, 31, 203, 3639, 1323, 261, 5814, 480, 374, 13, 288, 203, 5411, 6815, 9904, 31, 203, 5411, 1906, 9531, 1728, 31, 203, 3639, 289, 203, 3639, 1731, 3778, 1613, 273, 394, 1731, 12, 16649, 1769, 203, 3639, 1323, 261, 1132, 480, 374, 13, 288, 203, 5411, 6815, 3947, 404, 31, 203, 5411, 1613, 63, 16649, 65, 273, 1731, 21, 12, 11890, 28, 12, 8875, 397, 2254, 5034, 12, 1132, 738, 1728, 3719, 1769, 203, 5411, 460, 9531, 1728, 31, 203, 3639, 289, 203, 3639, 327, 533, 12, 4106, 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 ]
pragma solidity ^0.5.5; import "./ERC20Basic.sol"; import "./SafeMath.sol"; /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender], "The balance of account is insufficient."); require(_to != address(0), "Recipient address is zero address(0). Check the address again."); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } pragma solidity ^0.5.5; import "./DoDreamChainBase.sol"; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @title DoDreamChain */ contract DoDreamChain is DoDreamChainBase { event TransferedToDRMDapp( address indexed owner, address indexed spender, address indexed to, uint256 value, DRMReceiver.DRMReceiveType receiveType); string public constant name = "DoDreamChain"; string public constant symbol = "DRM"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 250 * 1000 * 1000 * (10 ** uint256(decimals)); // 250,000,000 DRM /** * @dev Constructor 생성자에게 DRM토큰을 보냅니다. */ constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(address(0), msg.sender, INITIAL_SUPPLY); } function drmTransfer(address _to, uint256 _value, string memory _note) public returns (bool ret) { ret = super.drmTransfer(_to, _value, _note); postTransfer(msg.sender, msg.sender, _to, _value, DRMReceiver.DRMReceiveType.DRM_TRANSFER); } function drmTransferFrom(address _from, address _to, uint256 _value, string memory _note) public returns (bool ret) { ret = super.drmTransferFrom(_from, _to, _value, _note); postTransfer(_from, msg.sender, _to, _value, DRMReceiver.DRMReceiveType.DRM_TRANSFER); } function postTransfer(address owner, address spender, address to, uint256 value, DRMReceiver.DRMReceiveType receiveType) internal returns (bool) { if (Address.isContract(to)) { (bool callOk, bytes memory data) = address(to).call(abi.encodeWithSignature("onDRMReceived(address,address,uint256,uint8)", owner, spender, value, receiveType)); if (callOk) { emit TransferedToDRMDapp(owner, spender, to, value, receiveType); } } return true; } function drmMintTo(address to, uint256 amount, string memory note) public onlyOwner returns (bool ret) { ret = super.drmMintTo(to, amount, note); postTransfer(address(0), msg.sender, to, amount, DRMReceiver.DRMReceiveType.DRM_MINT); } function drmBurnFrom(address from, uint256 value, string memory note) public onlyOwner returns (bool ret) { ret = super.drmBurnFrom(from, value, note); postTransfer(address(0), msg.sender, from, value, DRMReceiver.DRMReceiveType.DRM_BURN); } } /** * @title DRM Receiver */ contract DRMReceiver { enum DRMReceiveType { DRM_TRANSFER, DRM_MINT, DRM_BURN } function onDRMReceived(address owner, address spender, uint256 value, DRMReceiveType receiveType) public returns (bool); } pragma solidity ^0.5.5; import "./LockableToken.sol"; /** * @title DRMBaseToken * dev 트랜잭션 실행 시 메모를 남길 수 있다. */ contract DoDreamChainBase is LockableToken { event DRMTransfer(address indexed from, address indexed to, uint256 value, string note); event DRMTransferFrom(address indexed owner, address indexed spender, address indexed to, uint256 value, string note); event DRMApproval(address indexed owner, address indexed spender, uint256 value, string note); event DRMMintTo(address indexed controller, address indexed to, uint256 amount, string note); event DRMBurnFrom(address indexed controller, address indexed from, uint256 value, string note); event DRMTransferToTeam(address indexed owner, address indexed spender, address indexed to, uint256 value, string note); event DRMTransferToPartner(address indexed owner, address indexed spender, address indexed to, uint256 value, string note); event DRMTransferToEcosystem(address indexed owner, address indexed spender, address indexed to , uint256 value, uint256 processIdHash, uint256 userIdHash, string note); // ERC20 함수들을 오버라이딩 작업 > drm~ 함수를 타게 한다. function transfer(address to, uint256 value) public returns (bool ret) { return drmTransfer(to, value, "transfer"); } function drmTransfer(address to, uint256 value, string memory note) public returns (bool ret) { require(to != address(this), "The receive address is the Contact Address of DoDreamChain."); ret = super.transfer(to, value); emit DRMTransfer(msg.sender, to, value, note); } function transferFrom(address from, address to, uint256 value) public returns (bool) { return drmTransferFrom(from, to, value, ""); } function drmTransferFrom(address from, address to, uint256 value, string memory note) public returns (bool ret) { require(to != address(this), "The receive address is the Contact Address of DoDreamChain."); ret = super.transferFrom(from, to, value); emit DRMTransferFrom(from, msg.sender, to, value, note); } function approve(address spender, uint256 value) public returns (bool) { return drmApprove(spender, value, ""); } function drmApprove(address spender, uint256 value, string memory note) public returns (bool ret) { ret = super.approve(spender, value); emit DRMApproval(msg.sender, spender, value, note); } function increaseApproval(address spender, uint256 addedValue) public returns (bool) { return drmIncreaseApproval(spender, addedValue, ""); } function drmIncreaseApproval(address spender, uint256 addedValue, string memory note) public returns (bool ret) { ret = super.increaseApproval(spender, addedValue); emit DRMApproval(msg.sender, spender, allowed[msg.sender][spender], note); } function decreaseApproval(address spender, uint256 subtractedValue) public returns (bool) { return drmDecreaseApproval(spender, subtractedValue, ""); } function drmDecreaseApproval(address spender, uint256 subtractedValue, string memory note) public returns (bool ret) { ret = super.decreaseApproval(spender, subtractedValue); emit DRMApproval(msg.sender, spender, allowed[msg.sender][spender], note); } /** * dev 신규 발행시 반드시 주석을 남길수 있도록한다. */ function mintTo(address to, uint256 amount) internal returns (bool) { require(to != address(0x0), "This address to be set is zero address(0). Check the input address."); totalSupply_ = totalSupply_.add(amount); balances[to] = balances[to].add(amount); emit Transfer(address(0), to, amount); return true; } function drmMintTo(address to, uint256 amount, string memory note) public onlyOwner returns (bool ret) { ret = mintTo(to, amount); emit DRMMintTo(msg.sender, to, amount, note); } /** * dev 화폐 소각시 반드시 주석을 남길수 있도록한다. */ function burnFrom(address from, uint256 value) internal returns (bool) { require(value <= balances[from], "Your balance is insufficient."); balances[from] = balances[from].sub(value); totalSupply_ = totalSupply_.sub(value); emit Transfer(from, address(0), value); return true; } function drmBurnFrom(address from, uint256 value, string memory note) public onlyOwner returns (bool ret) { ret = burnFrom(from, value); emit DRMBurnFrom(msg.sender, from, value, note); } /** * dev DRM 팀에게 전송하는 경우 */ function drmTransferToTeam( address from, address to, uint256 value, string memory note ) public onlyOwner returns (bool ret) { require(to != address(this), "The receive address is the Contact Address of DoDreamChain."); ret = super.transferFrom(from, to, value); emit DRMTransferToTeam(from, msg.sender, to, value, note); return ret; } /** * dev 파트너(어드바이저)에게 전송하는 경우 */ function drmTransferToPartner( address from, address to, uint256 value, string memory note ) public onlyOwner returns (bool ret) { require(to != address(this), "The receive address is the Contact Address of DoDreamChain."); ret = super.transferFrom(from, to, value); emit DRMTransferToPartner(from, msg.sender, to, value, note); } /** * dev 보상을 DRM 지급 * dev EOA가 트랜잭션을 일으켜서 처리 * 여러개 계좌를 기준으로 한다. (가스비 아끼기 위함) */ function drmBatchTransferToEcosystem( address from, address[] memory to, uint256[] memory values, uint256 processIdHash, uint256[] memory userIdHash, string memory note ) public onlyOwner returns (bool ret) { uint256 length = to.length; require(length == values.length, "The sizes of \'to\' and \'values\' arrays are different."); require(length == userIdHash.length, "The sizes of \'to\' and \'userIdHash\' arrays are different."); ret = true; for (uint256 i = 0; i < length; i++) { require(to[i] != address(this), "The receive address is the Contact Address of DoDreamChain."); ret = ret && super.transferFrom(from, to[i], values[i]); emit DRMTransferToEcosystem(from, msg.sender, to[i], values[i], processIdHash, userIdHash[i], note); } } function destroy() public onlyRoot { selfdestruct(msg.sender); } } pragma solidity ^0.5.5; import "./ERC20Basic.sol"; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } pragma solidity ^0.5.5; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } pragma solidity ^0.5.5; import "./StandardToken.sol"; import "./MultiOwnable.sol"; /** * @title Lockable token */ contract LockableToken is StandardToken, MultiOwnable { bool public locked = true; /** * dev 락 = TRUE 이여도 거래 가능한 언락 계정 */ mapping(address => bool) public unlockAddrs; /** * dev - 계정마다 lockValue만큼 락이 걸린다. * dev - lockValue = 0 > limit이 없음 */ mapping(address => uint256) public lockValues; event Locked(bool locked, string note); event LockedTo(address indexed addr, bool locked, string note); event SetLockValue(address indexed addr, uint256 value, string note); constructor() public { unlockTo(msg.sender, ""); } modifier checkUnlock (address addr, uint256 value) { require(!locked || unlockAddrs[addr], "The account is currently locked."); require(balances[addr].sub(value) >= lockValues[addr], "Transferable limit exceeded. Check the status of the lock value."); _; } function lock(string memory note) public onlyOwner { locked = true; emit Locked(locked, note); } function unlock(string memory note) public onlyOwner { locked = false; emit Locked(locked, note); } function lockTo(address addr, string memory note) public onlyOwner { setLockValue(addr, balanceOf(addr), note); unlockAddrs[addr] = false; emit LockedTo(addr, true, note); } function unlockTo(address addr, string memory note) public onlyOwner { setLockValue(addr, 0, note); unlockAddrs[addr] = true; emit LockedTo(addr, false, note); } function setLockValue(address addr, uint256 value, string memory note) public onlyOwner { lockValues[addr] = value; if(value == 0){ unlockAddrs[addr] = true; }else{ unlockAddrs[addr] = false; } emit SetLockValue(addr, value, note); } /** * dev 이체 가능 금액 체크 */ function getMyUnlockValue() public view returns (uint256) { address addr = msg.sender; if ((!locked || unlockAddrs[addr]) ) return balances[addr].sub(lockValues[addr]); else return 0; } function transfer(address to, uint256 value) public checkUnlock(msg.sender, value) returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public checkUnlock(from, value) returns (bool) { return super.transferFrom(from, to, value); } } pragma solidity ^0.5.5; /** * @title MultiOwnable */ contract MultiOwnable { address public root; mapping (address => address) public owners; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { root = msg.sender; owners[root] = root; } /** * @dev check owner */ modifier onlyOwner() { require(owners[msg.sender] != address(0), "permission error[onlyOwner]"); _; } modifier onlyRoot() { require(msg.sender == root, "permission error[onlyRoot]"); _; } /** * @dev add new owner */ function newOwner(address _owner) external onlyOwner returns (bool) { require(_owner != address(0), "Invalid address."); require(owners[_owner] == address(0), "permission error[onlyOwner]"); owners[_owner] = msg.sender; return true; } /** * @dev delete owner */ function deleteOwner(address _owner) external onlyOwner returns (bool) { owners[_owner] = address(0); return true; } } pragma solidity ^0.5.5; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.5; import "./BasicToken.sol"; import "./ERC20.sol"; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from], "Not enough balance."); require(_value <= allowed[_from][msg.sender], "Not allowed."); require(_to != address(0), "Invalid address."); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } pragma solidity ^0.5.5; import "./ERC20Basic.sol"; import "./SafeMath.sol"; /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender], "The balance of account is insufficient."); require(_to != address(0), "Recipient address is zero address(0). Check the address again."); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } pragma solidity ^0.5.5; import "./DoDreamChainBase.sol"; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @title DoDreamChain */ contract DoDreamChain is DoDreamChainBase { event TransferedToDRMDapp( address indexed owner, address indexed spender, address indexed to, uint256 value, DRMReceiver.DRMReceiveType receiveType); string public constant name = "DoDreamChain"; string public constant symbol = "DRM"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 250 * 1000 * 1000 * (10 ** uint256(decimals)); // 250,000,000 DRM /** * @dev Constructor 생성자에게 DRM토큰을 보냅니다. */ constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(address(0), msg.sender, INITIAL_SUPPLY); } function drmTransfer(address _to, uint256 _value, string memory _note) public returns (bool ret) { ret = super.drmTransfer(_to, _value, _note); postTransfer(msg.sender, msg.sender, _to, _value, DRMReceiver.DRMReceiveType.DRM_TRANSFER); } function drmTransferFrom(address _from, address _to, uint256 _value, string memory _note) public returns (bool ret) { ret = super.drmTransferFrom(_from, _to, _value, _note); postTransfer(_from, msg.sender, _to, _value, DRMReceiver.DRMReceiveType.DRM_TRANSFER); } function postTransfer(address owner, address spender, address to, uint256 value, DRMReceiver.DRMReceiveType receiveType) internal returns (bool) { if (Address.isContract(to)) { (bool callOk, bytes memory data) = address(to).call(abi.encodeWithSignature("onDRMReceived(address,address,uint256,uint8)", owner, spender, value, receiveType)); if (callOk) { emit TransferedToDRMDapp(owner, spender, to, value, receiveType); } } return true; } function drmMintTo(address to, uint256 amount, string memory note) public onlyOwner returns (bool ret) { ret = super.drmMintTo(to, amount, note); postTransfer(address(0), msg.sender, to, amount, DRMReceiver.DRMReceiveType.DRM_MINT); } function drmBurnFrom(address from, uint256 value, string memory note) public onlyOwner returns (bool ret) { ret = super.drmBurnFrom(from, value, note); postTransfer(address(0), msg.sender, from, value, DRMReceiver.DRMReceiveType.DRM_BURN); } } /** * @title DRM Receiver */ contract DRMReceiver { enum DRMReceiveType { DRM_TRANSFER, DRM_MINT, DRM_BURN } function onDRMReceived(address owner, address spender, uint256 value, DRMReceiveType receiveType) public returns (bool); } pragma solidity ^0.5.5; import "./LockableToken.sol"; /** * @title DRMBaseToken * dev 트랜잭션 실행 시 메모를 남길 수 있다. */ contract DoDreamChainBase is LockableToken { event DRMTransfer(address indexed from, address indexed to, uint256 value, string note); event DRMTransferFrom(address indexed owner, address indexed spender, address indexed to, uint256 value, string note); event DRMApproval(address indexed owner, address indexed spender, uint256 value, string note); event DRMMintTo(address indexed controller, address indexed to, uint256 amount, string note); event DRMBurnFrom(address indexed controller, address indexed from, uint256 value, string note); event DRMTransferToTeam(address indexed owner, address indexed spender, address indexed to, uint256 value, string note); event DRMTransferToPartner(address indexed owner, address indexed spender, address indexed to, uint256 value, string note); event DRMTransferToEcosystem(address indexed owner, address indexed spender, address indexed to , uint256 value, uint256 processIdHash, uint256 userIdHash, string note); // ERC20 함수들을 오버라이딩 작업 > drm~ 함수를 타게 한다. function transfer(address to, uint256 value) public returns (bool ret) { return drmTransfer(to, value, "transfer"); } function drmTransfer(address to, uint256 value, string memory note) public returns (bool ret) { require(to != address(this), "The receive address is the Contact Address of DoDreamChain."); ret = super.transfer(to, value); emit DRMTransfer(msg.sender, to, value, note); } function transferFrom(address from, address to, uint256 value) public returns (bool) { return drmTransferFrom(from, to, value, ""); } function drmTransferFrom(address from, address to, uint256 value, string memory note) public returns (bool ret) { require(to != address(this), "The receive address is the Contact Address of DoDreamChain."); ret = super.transferFrom(from, to, value); emit DRMTransferFrom(from, msg.sender, to, value, note); } function approve(address spender, uint256 value) public returns (bool) { return drmApprove(spender, value, ""); } function drmApprove(address spender, uint256 value, string memory note) public returns (bool ret) { ret = super.approve(spender, value); emit DRMApproval(msg.sender, spender, value, note); } function increaseApproval(address spender, uint256 addedValue) public returns (bool) { return drmIncreaseApproval(spender, addedValue, ""); } function drmIncreaseApproval(address spender, uint256 addedValue, string memory note) public returns (bool ret) { ret = super.increaseApproval(spender, addedValue); emit DRMApproval(msg.sender, spender, allowed[msg.sender][spender], note); } function decreaseApproval(address spender, uint256 subtractedValue) public returns (bool) { return drmDecreaseApproval(spender, subtractedValue, ""); } function drmDecreaseApproval(address spender, uint256 subtractedValue, string memory note) public returns (bool ret) { ret = super.decreaseApproval(spender, subtractedValue); emit DRMApproval(msg.sender, spender, allowed[msg.sender][spender], note); } /** * dev 신규 발행시 반드시 주석을 남길수 있도록한다. */ function mintTo(address to, uint256 amount) internal returns (bool) { require(to != address(0x0), "This address to be set is zero address(0). Check the input address."); totalSupply_ = totalSupply_.add(amount); balances[to] = balances[to].add(amount); emit Transfer(address(0), to, amount); return true; } function drmMintTo(address to, uint256 amount, string memory note) public onlyOwner returns (bool ret) { ret = mintTo(to, amount); emit DRMMintTo(msg.sender, to, amount, note); } /** * dev 화폐 소각시 반드시 주석을 남길수 있도록한다. */ function burnFrom(address from, uint256 value) internal returns (bool) { require(value <= balances[from], "Your balance is insufficient."); balances[from] = balances[from].sub(value); totalSupply_ = totalSupply_.sub(value); emit Transfer(from, address(0), value); return true; } function drmBurnFrom(address from, uint256 value, string memory note) public onlyOwner returns (bool ret) { ret = burnFrom(from, value); emit DRMBurnFrom(msg.sender, from, value, note); } /** * dev DRM 팀에게 전송하는 경우 */ function drmTransferToTeam( address from, address to, uint256 value, string memory note ) public onlyOwner returns (bool ret) { require(to != address(this), "The receive address is the Contact Address of DoDreamChain."); ret = super.transferFrom(from, to, value); emit DRMTransferToTeam(from, msg.sender, to, value, note); return ret; } /** * dev 파트너(어드바이저)에게 전송하는 경우 */ function drmTransferToPartner( address from, address to, uint256 value, string memory note ) public onlyOwner returns (bool ret) { require(to != address(this), "The receive address is the Contact Address of DoDreamChain."); ret = super.transferFrom(from, to, value); emit DRMTransferToPartner(from, msg.sender, to, value, note); } /** * dev 보상을 DRM 지급 * dev EOA가 트랜잭션을 일으켜서 처리 * 여러개 계좌를 기준으로 한다. (가스비 아끼기 위함) */ function drmBatchTransferToEcosystem( address from, address[] memory to, uint256[] memory values, uint256 processIdHash, uint256[] memory userIdHash, string memory note ) public onlyOwner returns (bool ret) { uint256 length = to.length; require(length == values.length, "The sizes of \'to\' and \'values\' arrays are different."); require(length == userIdHash.length, "The sizes of \'to\' and \'userIdHash\' arrays are different."); ret = true; for (uint256 i = 0; i < length; i++) { require(to[i] != address(this), "The receive address is the Contact Address of DoDreamChain."); ret = ret && super.transferFrom(from, to[i], values[i]); emit DRMTransferToEcosystem(from, msg.sender, to[i], values[i], processIdHash, userIdHash[i], note); } } function destroy() public onlyRoot { selfdestruct(msg.sender); } } pragma solidity ^0.5.5; import "./ERC20Basic.sol"; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } pragma solidity ^0.5.5; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } pragma solidity ^0.5.5; import "./StandardToken.sol"; import "./MultiOwnable.sol"; /** * @title Lockable token */ contract LockableToken is StandardToken, MultiOwnable { bool public locked = true; /** * dev 락 = TRUE 이여도 거래 가능한 언락 계정 */ mapping(address => bool) public unlockAddrs; /** * dev - 계정마다 lockValue만큼 락이 걸린다. * dev - lockValue = 0 > limit이 없음 */ mapping(address => uint256) public lockValues; event Locked(bool locked, string note); event LockedTo(address indexed addr, bool locked, string note); event SetLockValue(address indexed addr, uint256 value, string note); constructor() public { unlockTo(msg.sender, ""); } modifier checkUnlock (address addr, uint256 value) { require(!locked || unlockAddrs[addr], "The account is currently locked."); require(balances[addr].sub(value) >= lockValues[addr], "Transferable limit exceeded. Check the status of the lock value."); _; } function lock(string memory note) public onlyOwner { locked = true; emit Locked(locked, note); } function unlock(string memory note) public onlyOwner { locked = false; emit Locked(locked, note); } function lockTo(address addr, string memory note) public onlyOwner { setLockValue(addr, balanceOf(addr), note); unlockAddrs[addr] = false; emit LockedTo(addr, true, note); } function unlockTo(address addr, string memory note) public onlyOwner { setLockValue(addr, 0, note); unlockAddrs[addr] = true; emit LockedTo(addr, false, note); } function setLockValue(address addr, uint256 value, string memory note) public onlyOwner { lockValues[addr] = value; if(value == 0){ unlockAddrs[addr] = true; }else{ unlockAddrs[addr] = false; } emit SetLockValue(addr, value, note); } /** * dev 이체 가능 금액 체크 */ function getMyUnlockValue() public view returns (uint256) { address addr = msg.sender; if ((!locked || unlockAddrs[addr]) ) return balances[addr].sub(lockValues[addr]); else return 0; } function transfer(address to, uint256 value) public checkUnlock(msg.sender, value) returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public checkUnlock(from, value) returns (bool) { return super.transferFrom(from, to, value); } } pragma solidity ^0.5.5; /** * @title MultiOwnable */ contract MultiOwnable { address public root; mapping (address => address) public owners; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { root = msg.sender; owners[root] = root; } /** * @dev check owner */ modifier onlyOwner() { require(owners[msg.sender] != address(0), "permission error[onlyOwner]"); _; } modifier onlyRoot() { require(msg.sender == root, "permission error[onlyRoot]"); _; } /** * @dev add new owner */ function newOwner(address _owner) external onlyOwner returns (bool) { require(_owner != address(0), "Invalid address."); require(owners[_owner] == address(0), "permission error[onlyOwner]"); owners[_owner] = msg.sender; return true; } /** * @dev delete owner */ function deleteOwner(address _owner) external onlyOwner returns (bool) { owners[_owner] = address(0); return true; } } pragma solidity ^0.5.5; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.5; import "./BasicToken.sol"; import "./ERC20.sol"; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from], "Not enough balance."); require(_value <= allowed[_from][msg.sender], "Not allowed."); require(_to != address(0), "Invalid address."); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } pragma solidity ^0.5.5; import "./ERC20Basic.sol"; import "./SafeMath.sol"; /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender], "The balance of account is insufficient."); require(_to != address(0), "Recipient address is zero address(0). Check the address again."); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } pragma solidity ^0.5.5; import "./DoDreamChainBase.sol"; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @title DoDreamChain */ contract DoDreamChain is DoDreamChainBase { event TransferedToDRMDapp( address indexed owner, address indexed spender, address indexed to, uint256 value, DRMReceiver.DRMReceiveType receiveType); string public constant name = "DoDreamChain"; string public constant symbol = "DRM"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 250 * 1000 * 1000 * (10 ** uint256(decimals)); // 250,000,000 DRM /** * @dev Constructor 생성자에게 DRM토큰을 보냅니다. */ constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(address(0), msg.sender, INITIAL_SUPPLY); } function drmTransfer(address _to, uint256 _value, string memory _note) public returns (bool ret) { ret = super.drmTransfer(_to, _value, _note); postTransfer(msg.sender, msg.sender, _to, _value, DRMReceiver.DRMReceiveType.DRM_TRANSFER); } function drmTransferFrom(address _from, address _to, uint256 _value, string memory _note) public returns (bool ret) { ret = super.drmTransferFrom(_from, _to, _value, _note); postTransfer(_from, msg.sender, _to, _value, DRMReceiver.DRMReceiveType.DRM_TRANSFER); } function postTransfer(address owner, address spender, address to, uint256 value, DRMReceiver.DRMReceiveType receiveType) internal returns (bool) { if (Address.isContract(to)) { (bool callOk, bytes memory data) = address(to).call(abi.encodeWithSignature("onDRMReceived(address,address,uint256,uint8)", owner, spender, value, receiveType)); if (callOk) { emit TransferedToDRMDapp(owner, spender, to, value, receiveType); } } return true; } function drmMintTo(address to, uint256 amount, string memory note) public onlyOwner returns (bool ret) { ret = super.drmMintTo(to, amount, note); postTransfer(address(0), msg.sender, to, amount, DRMReceiver.DRMReceiveType.DRM_MINT); } function drmBurnFrom(address from, uint256 value, string memory note) public onlyOwner returns (bool ret) { ret = super.drmBurnFrom(from, value, note); postTransfer(address(0), msg.sender, from, value, DRMReceiver.DRMReceiveType.DRM_BURN); } } /** * @title DRM Receiver */ contract DRMReceiver { enum DRMReceiveType { DRM_TRANSFER, DRM_MINT, DRM_BURN } function onDRMReceived(address owner, address spender, uint256 value, DRMReceiveType receiveType) public returns (bool); } pragma solidity ^0.5.5; import "./LockableToken.sol"; /** * @title DRMBaseToken * dev 트랜잭션 실행 시 메모를 남길 수 있다. */ contract DoDreamChainBase is LockableToken { event DRMTransfer(address indexed from, address indexed to, uint256 value, string note); event DRMTransferFrom(address indexed owner, address indexed spender, address indexed to, uint256 value, string note); event DRMApproval(address indexed owner, address indexed spender, uint256 value, string note); event DRMMintTo(address indexed controller, address indexed to, uint256 amount, string note); event DRMBurnFrom(address indexed controller, address indexed from, uint256 value, string note); event DRMTransferToTeam(address indexed owner, address indexed spender, address indexed to, uint256 value, string note); event DRMTransferToPartner(address indexed owner, address indexed spender, address indexed to, uint256 value, string note); event DRMTransferToEcosystem(address indexed owner, address indexed spender, address indexed to , uint256 value, uint256 processIdHash, uint256 userIdHash, string note); // ERC20 함수들을 오버라이딩 작업 > drm~ 함수를 타게 한다. function transfer(address to, uint256 value) public returns (bool ret) { return drmTransfer(to, value, "transfer"); } function drmTransfer(address to, uint256 value, string memory note) public returns (bool ret) { require(to != address(this), "The receive address is the Contact Address of DoDreamChain."); ret = super.transfer(to, value); emit DRMTransfer(msg.sender, to, value, note); } function transferFrom(address from, address to, uint256 value) public returns (bool) { return drmTransferFrom(from, to, value, ""); } function drmTransferFrom(address from, address to, uint256 value, string memory note) public returns (bool ret) { require(to != address(this), "The receive address is the Contact Address of DoDreamChain."); ret = super.transferFrom(from, to, value); emit DRMTransferFrom(from, msg.sender, to, value, note); } function approve(address spender, uint256 value) public returns (bool) { return drmApprove(spender, value, ""); } function drmApprove(address spender, uint256 value, string memory note) public returns (bool ret) { ret = super.approve(spender, value); emit DRMApproval(msg.sender, spender, value, note); } function increaseApproval(address spender, uint256 addedValue) public returns (bool) { return drmIncreaseApproval(spender, addedValue, ""); } function drmIncreaseApproval(address spender, uint256 addedValue, string memory note) public returns (bool ret) { ret = super.increaseApproval(spender, addedValue); emit DRMApproval(msg.sender, spender, allowed[msg.sender][spender], note); } function decreaseApproval(address spender, uint256 subtractedValue) public returns (bool) { return drmDecreaseApproval(spender, subtractedValue, ""); } function drmDecreaseApproval(address spender, uint256 subtractedValue, string memory note) public returns (bool ret) { ret = super.decreaseApproval(spender, subtractedValue); emit DRMApproval(msg.sender, spender, allowed[msg.sender][spender], note); } /** * dev 신규 발행시 반드시 주석을 남길수 있도록한다. */ function mintTo(address to, uint256 amount) internal returns (bool) { require(to != address(0x0), "This address to be set is zero address(0). Check the input address."); totalSupply_ = totalSupply_.add(amount); balances[to] = balances[to].add(amount); emit Transfer(address(0), to, amount); return true; } function drmMintTo(address to, uint256 amount, string memory note) public onlyOwner returns (bool ret) { ret = mintTo(to, amount); emit DRMMintTo(msg.sender, to, amount, note); } /** * dev 화폐 소각시 반드시 주석을 남길수 있도록한다. */ function burnFrom(address from, uint256 value) internal returns (bool) { require(value <= balances[from], "Your balance is insufficient."); balances[from] = balances[from].sub(value); totalSupply_ = totalSupply_.sub(value); emit Transfer(from, address(0), value); return true; } function drmBurnFrom(address from, uint256 value, string memory note) public onlyOwner returns (bool ret) { ret = burnFrom(from, value); emit DRMBurnFrom(msg.sender, from, value, note); } /** * dev DRM 팀에게 전송하는 경우 */ function drmTransferToTeam( address from, address to, uint256 value, string memory note ) public onlyOwner returns (bool ret) { require(to != address(this), "The receive address is the Contact Address of DoDreamChain."); ret = super.transferFrom(from, to, value); emit DRMTransferToTeam(from, msg.sender, to, value, note); return ret; } /** * dev 파트너(어드바이저)에게 전송하는 경우 */ function drmTransferToPartner( address from, address to, uint256 value, string memory note ) public onlyOwner returns (bool ret) { require(to != address(this), "The receive address is the Contact Address of DoDreamChain."); ret = super.transferFrom(from, to, value); emit DRMTransferToPartner(from, msg.sender, to, value, note); } /** * dev 보상을 DRM 지급 * dev EOA가 트랜잭션을 일으켜서 처리 * 여러개 계좌를 기준으로 한다. (가스비 아끼기 위함) */ function drmBatchTransferToEcosystem( address from, address[] memory to, uint256[] memory values, uint256 processIdHash, uint256[] memory userIdHash, string memory note ) public onlyOwner returns (bool ret) { uint256 length = to.length; require(length == values.length, "The sizes of \'to\' and \'values\' arrays are different."); require(length == userIdHash.length, "The sizes of \'to\' and \'userIdHash\' arrays are different."); ret = true; for (uint256 i = 0; i < length; i++) { require(to[i] != address(this), "The receive address is the Contact Address of DoDreamChain."); ret = ret && super.transferFrom(from, to[i], values[i]); emit DRMTransferToEcosystem(from, msg.sender, to[i], values[i], processIdHash, userIdHash[i], note); } } function destroy() public onlyRoot { selfdestruct(msg.sender); } } pragma solidity ^0.5.5; import "./ERC20Basic.sol"; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } pragma solidity ^0.5.5; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } pragma solidity ^0.5.5; import "./StandardToken.sol"; import "./MultiOwnable.sol"; /** * @title Lockable token */ contract LockableToken is StandardToken, MultiOwnable { bool public locked = true; /** * dev 락 = TRUE 이여도 거래 가능한 언락 계정 */ mapping(address => bool) public unlockAddrs; /** * dev - 계정마다 lockValue만큼 락이 걸린다. * dev - lockValue = 0 > limit이 없음 */ mapping(address => uint256) public lockValues; event Locked(bool locked, string note); event LockedTo(address indexed addr, bool locked, string note); event SetLockValue(address indexed addr, uint256 value, string note); constructor() public { unlockTo(msg.sender, ""); } modifier checkUnlock (address addr, uint256 value) { require(!locked || unlockAddrs[addr], "The account is currently locked."); require(balances[addr].sub(value) >= lockValues[addr], "Transferable limit exceeded. Check the status of the lock value."); _; } function lock(string memory note) public onlyOwner { locked = true; emit Locked(locked, note); } function unlock(string memory note) public onlyOwner { locked = false; emit Locked(locked, note); } function lockTo(address addr, string memory note) public onlyOwner { setLockValue(addr, balanceOf(addr), note); unlockAddrs[addr] = false; emit LockedTo(addr, true, note); } function unlockTo(address addr, string memory note) public onlyOwner { setLockValue(addr, 0, note); unlockAddrs[addr] = true; emit LockedTo(addr, false, note); } function setLockValue(address addr, uint256 value, string memory note) public onlyOwner { lockValues[addr] = value; if(value == 0){ unlockAddrs[addr] = true; }else{ unlockAddrs[addr] = false; } emit SetLockValue(addr, value, note); } /** * dev 이체 가능 금액 체크 */ function getMyUnlockValue() public view returns (uint256) { address addr = msg.sender; if ((!locked || unlockAddrs[addr]) ) return balances[addr].sub(lockValues[addr]); else return 0; } function transfer(address to, uint256 value) public checkUnlock(msg.sender, value) returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public checkUnlock(from, value) returns (bool) { return super.transferFrom(from, to, value); } } pragma solidity ^0.5.5; /** * @title MultiOwnable */ contract MultiOwnable { address public root; mapping (address => address) public owners; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { root = msg.sender; owners[root] = root; } /** * @dev check owner */ modifier onlyOwner() { require(owners[msg.sender] != address(0), "permission error[onlyOwner]"); _; } modifier onlyRoot() { require(msg.sender == root, "permission error[onlyRoot]"); _; } /** * @dev add new owner */ function newOwner(address _owner) external onlyOwner returns (bool) { require(_owner != address(0), "Invalid address."); require(owners[_owner] == address(0), "permission error[onlyOwner]"); owners[_owner] = msg.sender; return true; } /** * @dev delete owner */ function deleteOwner(address _owner) external onlyOwner returns (bool) { owners[_owner] = address(0); return true; } } pragma solidity ^0.5.5; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.5; import "./BasicToken.sol"; import "./ERC20.sol"; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from], "Not enough balance."); require(_value <= allowed[_from][msg.sender], "Not allowed."); require(_to != address(0), "Invalid address."); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
* dev DRM 팀에게 전송하는 경우/
function drmTransferToTeam( address from, address to, uint256 value, string memory note ) public onlyOwner returns (bool ret) { require(to != address(this), "The receive address is the Contact Address of DoDreamChain."); ret = super.transferFrom(from, to, value); emit DRMTransferToTeam(from, msg.sender, to, value, note); return ret; }
921,601
[ 1, 5206, 463, 8717, 225, 174, 239, 227, 173, 250, 243, 171, 115, 239, 225, 173, 259, 231, 173, 233, 99, 174, 248, 251, 172, 237, 247, 225, 171, 115, 126, 173, 253, 113, 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, 445, 5081, 81, 5912, 774, 8689, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 460, 16, 203, 3639, 533, 3778, 4721, 203, 565, 262, 1071, 1338, 5541, 1135, 261, 6430, 325, 13, 288, 203, 3639, 2583, 12, 869, 480, 1758, 12, 2211, 3631, 315, 1986, 6798, 1758, 353, 326, 13329, 5267, 434, 2256, 40, 793, 3893, 1199, 1769, 203, 203, 3639, 325, 273, 2240, 18, 13866, 1265, 12, 2080, 16, 358, 16, 460, 1769, 203, 3639, 3626, 463, 8717, 5912, 774, 8689, 12, 2080, 16, 1234, 18, 15330, 16, 358, 16, 460, 16, 4721, 1769, 203, 3639, 327, 325, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.13; library Sets { // address set struct addressSet { address[] members; mapping (address => bool) memberExists; mapping (address => uint) memberIndex; } function insert(addressSet storage self, address other) { if (!self.memberExists[other]) { self.memberExists[other] = true; self.memberIndex[other] = self.members.length; self.members.push(other); } } function remove(addressSet storage self, address other) { if (self.memberExists[other]) { self.memberExists[other] = false; uint index = self.memberIndex[other]; // change index of last value to index of other self.memberIndex[self.members[self.members.length - 1]] = index; // copy last value over other and decrement length self.members[index] = self.members[self.members.length - 1]; self.members.length--; } } function contains(addressSet storage self, address other) returns (bool) { return self.memberExists[other]; } function length(addressSet storage self) returns (uint256) { return self.members.length; } // uint set struct uintSet { uint[] members; mapping (uint => bool) memberExists; mapping (uint => uint) memberIndex; } function insert(uintSet storage self, uint other) { if (!self.memberExists[other]) { self.memberExists[other] = true; self.memberIndex[other] = self.members.length; self.members.push(other); } } function remove(uintSet storage self, uint other) { if (self.memberExists[other]) { self.memberExists[other] = false; uint index = self.memberIndex[other]; // change index of last value to index of other self.memberIndex[self.members[self.members.length - 1]] = index; // copy last value over other and decrement length self.members[index] = self.members[self.members.length - 1]; self.members.length--; } } function contains(uintSet storage self, uint other) returns (bool) { return self.memberExists[other]; } function length(uintSet storage self) returns (uint256) { return self.members.length; } // uint8 set struct uint8Set { uint8[] members; mapping (uint8 => bool) memberExists; mapping (uint8 => uint) memberIndex; } function insert(uint8Set storage self, uint8 other) { if (!self.memberExists[other]) { self.memberExists[other] = true; self.memberIndex[other] = self.members.length; self.members.push(other); } } function remove(uint8Set storage self, uint8 other) { if (self.memberExists[other]) { self.memberExists[other] = false; uint index = self.memberIndex[other]; // change index of last value to index of other self.memberIndex[self.members[self.members.length - 1]] = index; // copy last value over other and decrement length self.members[index] = self.members[self.members.length - 1]; self.members.length--; } } function contains(uint8Set storage self, uint8 other) returns (bool) { return self.memberExists[other]; } function length(uint8Set storage self) returns (uint256) { return self.members.length; } // int set struct intSet { int[] members; mapping (int => bool) memberExists; mapping (int => uint) memberIndex; } function insert(intSet storage self, int other) { if (!self.memberExists[other]) { self.memberExists[other] = true; self.memberIndex[other] = self.members.length; self.members.push(other); } } function remove(intSet storage self, int other) { if (self.memberExists[other]) { self.memberExists[other] = false; uint index = self.memberIndex[other]; // change index of last value to index of other self.memberIndex[self.members[self.members.length - 1]] = index; // copy last value over other and decrement length self.members[index] = self.members[self.members.length - 1]; self.members.length--; } } function contains(intSet storage self, int other) returns (bool) { return self.memberExists[other]; } function length(intSet storage self) returns (uint256) { return self.members.length; } // int8 set struct int8Set { int8[] members; mapping (int8 => bool) memberExists; mapping (int8 => uint) memberIndex; } function insert(int8Set storage self, int8 other) { if (!self.memberExists[other]) { self.memberExists[other] = true; self.memberIndex[other] = self.members.length; self.members.push(other); } } function remove(int8Set storage self, int8 other) { if (self.memberExists[other]) { self.memberExists[other] = false; uint index = self.memberIndex[other]; // change index of last value to index of other self.memberIndex[self.members[self.members.length - 1]] = index; // copy last value over other and decrement length self.members[index] = self.members[self.members.length - 1]; self.members.length--; } } function contains(int8Set storage self, int8 other) returns (bool) { return self.memberExists[other]; } function length(int8Set storage self) returns (uint256) { return self.members.length; } // byte set struct byteSet { byte[] members; mapping (byte => bool) memberExists; mapping (byte => uint) memberIndex; } function insert(byteSet storage self, byte other) { if (!self.memberExists[other]) { self.memberExists[other] = true; self.memberIndex[other] = self.members.length; self.members.push(other); } } function remove(byteSet storage self, byte other) { if (self.memberExists[other]) { self.memberExists[other] = false; uint index = self.memberIndex[other]; // change index of last value to index of other self.memberIndex[self.members[self.members.length - 1]] = index; // copy last value over other and decrement length self.members[index] = self.members[self.members.length - 1]; self.members.length--; } } function contains(byteSet storage self, byte other) returns (bool) { return self.memberExists[other]; } function length(byteSet storage self) returns (uint256) { return self.members.length; } // bytes32 set struct bytes32Set { bytes32[] members; mapping (bytes32 => bool) memberExists; mapping (bytes32 => uint) memberIndex; } function insert(bytes32Set storage self, bytes32 other) { if (!self.memberExists[other]) { self.memberExists[other] = true; self.memberIndex[other] = self.members.length; self.members.push(other); } } function remove(bytes32Set storage self, bytes32 other) { if (self.memberExists[other]) { self.memberExists[other] = false; uint index = self.memberIndex[other]; // change index of last value to index of other self.memberIndex[self.members[self.members.length - 1]] = index; // copy last value over other and decrement length self.members[index] = self.members[self.members.length - 1]; self.members.length--; } } function contains(bytes32Set storage self, bytes32 other) returns (bool) { return self.memberExists[other]; } function length(bytes32Set storage self) returns (uint256) { return self.members.length; } } contract Prover { // attach library using Sets for *; // storage vars address owner; Sets.addressSet internal users; mapping (address => UserAccount) internal ledger; // structs struct UserAccount { Sets.bytes32Set hashes; mapping (bytes32 => Entry) entries; } struct Entry { uint256 time; uint256 value; } // constructor function Prover() { owner = msg.sender; } // fallback: unmatched transactions will be returned function () { revert(); } // modifier to check if sender has an account modifier hasAccount() { assert(ledger[msg.sender].hashes.length() >= 1); _; } // external functions // proving function proveIt(address target, bytes32 dataHash) external constant returns (bool proved, uint256 time, uint256 value) { return status(target, dataHash); } function proveIt(address target, string dataString) external constant returns (bool proved, uint256 time, uint256 value) { return status(target, sha3(dataString)); } // allow access to our structs via functions with convenient return values function usersGetter() public constant returns (uint256 number_unique_addresses, address[] unique_addresses) { return (users.length(), users.members); } function userEntries(address target) external constant returns (bytes32[]) { return ledger[target].hashes.members; } // public functions // adding entries function addEntry(bytes32 dataHash) payable { _addEntry(dataHash); } function addEntry(string dataString) payable { _addEntry(sha3(dataString)); } // deleting entries function deleteEntry(bytes32 dataHash) hasAccount { _deleteEntry(dataHash); } function deleteEntry(string dataString) hasAccount { _deleteEntry(sha3(dataString)); } // allow owner to delete contract if no accounts exist function selfDestruct() { if ((msg.sender == owner) && (users.length() == 0)) { selfdestruct(owner); } } // internal functions function _addEntry(bytes32 dataHash) internal { // ensure the entry doesn&#39;t exist assert(!ledger[msg.sender].hashes.contains(dataHash)); // update UserAccount (hashes then entries) ledger[msg.sender].hashes.insert(dataHash); ledger[msg.sender].entries[dataHash] = Entry(now, msg.value); // add sender to userlist users.insert(msg.sender); } function _deleteEntry(bytes32 dataHash) internal { // ensure the entry does exist assert(ledger[msg.sender].hashes.contains(dataHash)); uint256 rebate = ledger[msg.sender].entries[dataHash].value; // update UserAccount (hashes then entries) ledger[msg.sender].hashes.remove(dataHash); delete ledger[msg.sender].entries[dataHash]; // send the rebate if (rebate > 0) { msg.sender.transfer(rebate); } // delete from userlist if this was the user&#39;s last entry if (ledger[msg.sender].hashes.length() == 0) { users.remove(msg.sender); } } // return status of arbitrary address and dataHash function status(address target, bytes32 dataHash) internal constant returns (bool proved, uint256 time, uint256 value) { return (ledger[msg.sender].hashes.contains(dataHash), ledger[target].entries[dataHash].time, ledger[target].entries[dataHash].value); } }
fallback: unmatched transactions will be returned
function () { revert(); }
6,718,893
[ 1, 16471, 30, 24863, 8938, 903, 506, 2106, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1832, 288, 203, 3639, 15226, 5621, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Twitter Account: twitter.com/gobbletoken Gobble Gobble (@GobbleToken) $GOBBLE *Telegram Account: t.me/GobbleTokenOfficial *Website: https://gobblegobble.io * / /** *Submitted for verification at Etherscan.io on 2021-05-11 */ /** *Submitted for verification at Etherscan.io on 2021-05-11 */ // 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 virtual view returns (address payable) { return msg.sender; } function _msgData() internal virtual view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function ceil(uint256 a, uint256 m) internal pure returns (uint256) { uint256 c = add(a,m); uint256 d = sub(c,1); return mul(div(d,m),m); } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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 { _owner =0xD2cc2E3EaA321837535d5aDCb942b8E177156346; 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(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Pair { function sync() external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; 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; } contract GOBBLE_GOBBLE is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; string private _name = "GOBBLE GOBBLE"; string private _symbol = "GOBBLE"; uint8 private _decimals = 18; mapping(address => uint256) internal _reflectionBalance; mapping(address => uint256) internal _balanceLimit; mapping(address => uint256) internal _tokenBalance; mapping (address => bool) public _blackList; mapping (address => bool) public _maxAmount; mapping (address => bool) public _maxWallet; mapping(address => mapping(address => uint256)) internal _allowances; uint256 private constant MAX = ~uint256(0); uint256 internal _tokenTotal = 1_000_000_000_000_000e18; uint256 internal _reflectionTotal = (MAX - (MAX % _tokenTotal)); mapping(address => bool) isTaxless; mapping(address => bool) internal _isExcluded; address[] internal _excluded; uint256 public _feeDecimal = 2; // do not change this value... uint256 public _taxFee = 200; // means 2% which distribute to all holders reflection fee uint256 public _marketingFee=200;// meanse 2% eth to marketing Wallet uint256 public _liquidityFee = 200; // means 2% uint256 public _burnFee = 200; // means 2% uint256 public _SelltaxFee = 200; // means 2% which distribute to all holders reflection fee uint256 public _SellmarketingFee=200;// meanse 2% uint256 public _SelllLiquidityFee = 200; // means 2% uint256 public _SellBurnFee = 600; // means 6% address private marketingAddress=0xDa85D0cFC0fbd5AC164F5D5cDdD83948fFC02E8c; address DEAD = 0x000000000000000000000000000000000000dEaD; uint256 public _taxFeeTotal; uint256 public _burnFeeTotal; uint256 public _liquidityFeeTotal; bool public isFeeActive = true; // should be true bool private inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; bool private tradingEnable = true; //Max tx Amount uint256 public maxTxAmount = _tokenTotal; // //max Wallet Holdings 1% of totalSupply uint256 public _maxWalletToken =10_000_000_000_000e18; uint256 public minTokensBeforeSwap = 100_00_000e18; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify(uint256 tokensSwapped,uint256 ethReceived, uint256 tokensIntoLiqudity); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() public { //IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); // for BSC Pncake v2 // IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506); // for SushiSwap IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // for Ethereum uniswap v2 uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; isTaxless[owner()] = true; isTaxless[address(this)] = true; //Exempt maxTxAmount from Onwer and Contract _maxAmount[owner()] = true; _maxAmount[address(this)] = true; _maxAmount[marketingAddress] =true; //Exempt maxWalletAmount from Owner ,Contract,marketingAddress _maxWallet[owner()] = true; _maxWallet[DEAD] = true; _maxWallet[marketingAddress] = true; // exlcude pair address from tax rewards _isExcluded[address(uniswapV2Pair)] = true; _excluded.push(address(uniswapV2Pair)); _isExcluded[DEAD]=true; _excluded.push(DEAD); _reflectionBalance[owner()] = _reflectionTotal; emit Transfer(address(0),owner(), _tokenTotal); } 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 override view returns (uint256) { return _tokenTotal; } function balanceOf(address account) public override view returns (uint256) { if (_isExcluded[account]) return _tokenBalance[account]; return tokenFromReflection(_reflectionBalance[account]); } function transfer(address recipient, uint256 amount) public override virtual returns (bool) { _transfer(_msgSender(),recipient,amount); return true; } function allowance(address owner, address spender) public override view 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 virtual returns (bool) { _transfer(sender,recipient,amount); _approve(sender,_msgSender(),_allowances[sender][_msgSender()].sub( amount,"ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function reflectionFromToken(uint256 tokenAmount, bool deductTransferFee) public view returns (uint256) { require(tokenAmount <= _tokenTotal, "Amount must be less than supply"); if (!deductTransferFee) { return tokenAmount.mul(_getReflectionRate()); } else { return tokenAmount.sub(tokenAmount.mul(_taxFee).div(10** _feeDecimal + 2)).mul( _getReflectionRate() ); } } function tokenFromReflection(uint256 reflectionAmount) public view returns (uint256) { require( reflectionAmount <= _reflectionTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getReflectionRate(); return reflectionAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require( account != address(uniswapV2Router), "ERC20: We can not exclude Uniswap router." ); require(!_isExcluded[account], "ERC20: Account is already excluded"); if (_reflectionBalance[account] > 0) { _tokenBalance[account] = tokenFromReflection( _reflectionBalance[account] ); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "ERC20: Account is already included"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tokenBalance[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(amount <= maxTxAmount || _maxAmount[sender], "Transfer Limit Exceeds"); require(!_blackList[sender],"Address is blackListed"); require(tradingEnable,"trading is disable"); uint256 transferAmount = amount; uint256 rate = _getReflectionRate(); uint256 constractBal=balanceOf(address(this)); bool overMinTokenBalance = constractBal >= minTokensBeforeSwap; if(!inSwapAndLiquify && overMinTokenBalance && sender != uniswapV2Pair && swapAndLiquifyEnabled) { swapAndLiquify(constractBal); } if(sender == uniswapV2Pair) { if(!_maxWallet[recipient] && recipient != address(this) && recipient != address(0) && recipient != marketingAddress){ uint256 heldTokens = balanceOf(recipient); require((heldTokens + amount) <= _maxWalletToken,"Total Holding is currently limited, you can not buy that much.");} if(!isTaxless[sender] && !isTaxless[recipient] && !inSwapAndLiquify){ transferAmount = collectBuyFee(sender,amount,rate); } //transfer reflection _reflectionBalance[sender] = _reflectionBalance[sender].sub(amount.mul(rate)); _reflectionBalance[recipient] = _reflectionBalance[recipient].add(transferAmount.mul(rate)); //if any account belongs to the excludedAccount transfer token if (_isExcluded[sender]) { _tokenBalance[sender] = _tokenBalance[sender].sub(amount); } if (_isExcluded[recipient]) { _tokenBalance[recipient] = _tokenBalance[recipient].add(transferAmount); } emit Transfer(sender, recipient, transferAmount); return; } if(recipient == uniswapV2Pair){ if(!isTaxless[sender] && !isTaxless[recipient] && !inSwapAndLiquify){ transferAmount = collectSellFee(sender,amount,rate); } //transfer reflection _reflectionBalance[sender] = _reflectionBalance[sender].sub(amount.mul(rate)); _reflectionBalance[recipient] = _reflectionBalance[recipient].add(transferAmount.mul(rate)); //if any account belongs to the excludedAccount transfer token if (_isExcluded[sender]) { _tokenBalance[sender] = _tokenBalance[sender].sub(amount); } if (_isExcluded[recipient]) { _tokenBalance[recipient] = _tokenBalance[recipient].add(transferAmount); } emit Transfer(sender, recipient, transferAmount); return; } //transfer reflection _reflectionBalance[sender] = _reflectionBalance[sender].sub(amount.mul(rate)); _reflectionBalance[recipient] = _reflectionBalance[recipient].add(transferAmount.mul(rate)); //if any account belongs to the excludedAccount transfer token if (_isExcluded[sender]) { _tokenBalance[sender] = _tokenBalance[sender].sub(amount); } if (_isExcluded[recipient]) { _tokenBalance[recipient] = _tokenBalance[recipient].add(transferAmount); } emit Transfer(sender, recipient, transferAmount); } function collectBuyFee(address account, uint256 amount, uint256 rate) private returns (uint256) { uint256 transferAmount = amount; //@dev tax fee if(_taxFee != 0){ uint256 taxFee = amount.mul(_taxFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(taxFee); _reflectionTotal = _reflectionTotal.sub(taxFee.mul(rate)); _taxFeeTotal = _taxFeeTotal.add(taxFee); } //@dev burn fee if(_marketingFee != 0){ uint256 marketingFee = amount.mul(_marketingFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(marketingFee); _reflectionBalance[marketingAddress] = _reflectionBalance[marketingAddress].add(marketingFee.mul(rate)); if(_isExcluded[marketingAddress]){ _tokenBalance[marketingAddress] = _tokenBalance[marketingAddress].add(marketingFee); } emit Transfer(account,marketingAddress,marketingFee); } if(_liquidityFee != 0){ uint256 liquidityFee = amount.mul(_liquidityFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(liquidityFee); _reflectionBalance[address(this)] = _reflectionBalance[address(this)].add(liquidityFee.mul(rate)); if(_isExcluded[address(this)]){ _tokenBalance[address(this)] = _tokenBalance[address(this)].add(liquidityFee); } emit Transfer(account,address(this),liquidityFee); } if(_burnFee != 0){ uint256 burnFee = amount.mul(_burnFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(burnFee); _reflectionBalance[DEAD] = _reflectionBalance[DEAD].add(burnFee.mul(rate)); if(_isExcluded[DEAD]){ _tokenBalance[DEAD] = _tokenBalance[DEAD].add(burnFee); } emit Transfer(account,DEAD,burnFee); } return transferAmount; } function collectSellFee(address account, uint256 amount, uint256 rate) private returns (uint256) { uint256 transferAmount = amount; //@dev tax fee if(_SelltaxFee != 0){ uint256 taxFee = amount.mul(_SelltaxFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(taxFee); _reflectionTotal = _reflectionTotal.sub(taxFee.mul(rate)); _taxFeeTotal = _taxFeeTotal.add(taxFee); } //@dev burn fee if(_SellmarketingFee != 0){ uint256 marketingFee = amount.mul(_SellmarketingFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(marketingFee); _reflectionBalance[marketingAddress] = _reflectionBalance[marketingAddress].add(marketingFee.mul(rate)); if(_isExcluded[marketingAddress]){ _tokenBalance[marketingAddress] = _tokenBalance[marketingAddress].add(marketingFee); } emit Transfer(account,marketingAddress,marketingFee); } if(_SelllLiquidityFee != 0){ uint256 liquidityFee = amount.mul(_SelllLiquidityFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(liquidityFee); _reflectionBalance[address(this)] = _reflectionBalance[address(this)].add(liquidityFee.mul(rate)); if(_isExcluded[address(this)]){ _tokenBalance[address(this)] = _tokenBalance[address(this)].add(liquidityFee); } emit Transfer(account,address(this),liquidityFee); } if(_SellBurnFee != 0){ uint256 burnFee = amount.mul(_SellBurnFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(burnFee); _reflectionBalance[DEAD] = _reflectionBalance[DEAD].add(burnFee.mul(rate)); if(_isExcluded[DEAD]){ _tokenBalance[DEAD] = _tokenBalance[DEAD].add(burnFee); } emit Transfer(account,DEAD,burnFee); } return transferAmount; } function _getReflectionRate() private view returns (uint256) { uint256 reflectionSupply = _reflectionTotal; uint256 tokenSupply = _tokenTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _reflectionBalance[_excluded[i]] > reflectionSupply || _tokenBalance[_excluded[i]] > tokenSupply ) return _reflectionTotal.div(_tokenTotal); reflectionSupply = reflectionSupply.sub( _reflectionBalance[_excluded[i]] ); tokenSupply = tokenSupply.sub(_tokenBalance[_excluded[i]]); } if (reflectionSupply < _reflectionTotal.div(_tokenTotal)) return _reflectionTotal.div(_tokenTotal); return reflectionSupply.div(tokenSupply); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { if(contractTokenBalance > maxTxAmount){ contractTokenBalance = maxTxAmount; } // split the contract balance into halves uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(this), block.timestamp ); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function setPair(address pair) external onlyOwner { uniswapV2Pair = pair; } function setTaxless(address account, bool value) external onlyOwner { isTaxless[account] = value; } function setSwapAndLiquifyEnabled(bool enabled) external onlyOwner { swapAndLiquifyEnabled = enabled; SwapAndLiquifyEnabledUpdated(enabled); } function setFeeActive(bool value) external onlyOwner { isFeeActive = value; } function setBuyFee(uint256 marketingFee,uint256 burnFee,uint256 liquidityFee,uint256 taxFee) external onlyOwner { _marketingFee=marketingFee; _liquidityFee=liquidityFee; _burnFee=burnFee; _taxFee=taxFee; } function setSellFee(uint256 marketingFee,uint256 burnFee,uint256 liquidityFee,uint256 taxFee) external onlyOwner { _SellmarketingFee=marketingFee; _SelllLiquidityFee=liquidityFee; _SelltaxFee=taxFee; _SellBurnFee=burnFee; } function setWalletAddress(address _marketingAddress) external onlyOwner{ marketingAddress=_marketingAddress; } function setBlackList (address add,bool value) external onlyOwner { _blackList[add]=value; } function setTrading(bool value) external onlyOwner { tradingEnable= value; } function exemptMaxTxAmountAddress(address _address,bool value) external onlyOwner { _maxAmount[_address] = value; } function exemptMaxWalletAmountAddress(address _address,bool value) external onlyOwner { _maxWallet[_address] =value; } function setMaxWalletAmount(uint256 amount) external onlyOwner { _maxWalletToken = amount; } function setMaxTxAmount(uint256 amount) external onlyOwner { maxTxAmount = amount; } function setMinTokensBeforeSwap(uint256 amount) external onlyOwner { minTokensBeforeSwap = amount; } receive() external payable {} }
means 2% which distribute to all holders reflection fee
uint256 public _taxFee = 200;
466,806
[ 1, 18408, 576, 9, 1492, 25722, 358, 777, 366, 4665, 5463, 14036, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 1071, 389, 8066, 14667, 273, 4044, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/7700/0x9B2a63F27661A468E2da22226b64A4914144f195/sources/contracts/mixins/StorageLayout.sol
Pool -> Position -> Week -> Claimed
mapping(bytes32 => mapping(bytes32 => mapping(uint32 => bool))) ambLiquidityRewardsClaimed_;
4,651,428
[ 1, 2864, 317, 11010, 317, 10527, 317, 18381, 329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 12, 3890, 1578, 516, 2874, 12, 3890, 1578, 516, 2874, 12, 11890, 1578, 516, 1426, 20349, 13232, 48, 18988, 24237, 17631, 14727, 9762, 329, 67, 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 ]
// Сочетаемость глаголов (и отглагольных частей речи) с предложным // паттерном. // LC->07.08.2018 facts гл_предл language=Russian { arity=3 //violation_score=-5 generic return=boolean } #define ГЛ_ИНФ(v) инфинитив:v{}, глагол:v{} #region Предлог_В // ------------------- С ПРЕДЛОГОМ 'В' --------------------------- #region Предложный // Глаголы и отглагольные части речи, присоединяющие // предложное дополнение с предлогом В и сущ. в предложном падеже. wordentry_set Гл_В_Предл = { rus_verbs:взорваться{}, // В Дагестане взорвался автомобиль // вернуть после перекомпиляции rus_verbs:подорожать{}, // В Дагестане подорожал хлеб rus_verbs:воевать{}, // Воевал во Франции. rus_verbs:устать{}, // Устали в дороге? rus_verbs:изнывать{}, // В Лондоне Черчилль изнывал от нетерпения. rus_verbs:решить{}, // Что решат в правительстве? rus_verbs:выскакивать{}, // Один из бойцов на улицу выскакивает. rus_verbs:обстоять{}, // В действительности же дело обстояло не так. rus_verbs:подыматься{}, rus_verbs:поехать{}, // поедем в такси! rus_verbs:уехать{}, // он уехал в такси rus_verbs:прибыть{}, // они прибыли в качестве независимых наблюдателей rus_verbs:ОБЛАЧИТЬ{}, rus_verbs:ОБЛАЧАТЬ{}, rus_verbs:ОБЛАЧИТЬСЯ{}, rus_verbs:ОБЛАЧАТЬСЯ{}, rus_verbs:НАРЯДИТЬСЯ{}, rus_verbs:НАРЯЖАТЬСЯ{}, rus_verbs:ПОВАЛЯТЬСЯ{}, // повалявшись в снегу, бежать обратно в тепло. rus_verbs:ПОКРЫВАТЬ{}, // Во многих местах ее покрывали трещины, наросты и довольно плоские выступы. (ПОКРЫВАТЬ) rus_verbs:ПРОЖИГАТЬ{}, // Синий луч искрился белыми пятнами и прожигал в земле дымящуюся борозду. (ПРОЖИГАТЬ) rus_verbs:МЫЧАТЬ{}, // В огромной куче тел жалобно мычали задавленные трупами и раненые бизоны. (МЫЧАТЬ) rus_verbs:РАЗБОЙНИЧАТЬ{}, // Эти существа обычно разбойничали в трехстах милях отсюда (РАЗБОЙНИЧАТЬ) rus_verbs:МАЯЧИТЬ{}, // В отдалении маячили огромные серые туши мастодонтов и мамонтов с изогнутыми бивнями. (МАЯЧИТЬ/ЗАМАЯЧИТЬ) rus_verbs:ЗАМАЯЧИТЬ{}, rus_verbs:НЕСТИСЬ{}, // Кони неслись вперед в свободном и легком галопе (НЕСТИСЬ) rus_verbs:ДОБЫТЬ{}, // Они надеялись застать "медвежий народ" врасплох и добыть в бою голову величайшего из воинов. (ДОБЫТЬ) rus_verbs:СПУСТИТЬ{}, // Время от времени грохот или вопль объявляли о спущенной где-то во дворце ловушке. (СПУСТИТЬ) rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Она сузила глаза, на лице ее стала образовываться маска безумия. (ОБРАЗОВЫВАТЬСЯ) rus_verbs:КИШЕТЬ{}, // в этом районе кишмя кишели разбойники и драконы. (КИШЕТЬ) rus_verbs:ДЫШАТЬ{}, // Она тяжело дышала в тисках гнева (ДЫШАТЬ) rus_verbs:ЗАДЕВАТЬ{}, // тот задевал в нем какую-то струну (ЗАДЕВАТЬ) rus_verbs:УСТУПИТЬ{}, // Так что теперь уступи мне в этом. (УСТУПИТЬ) rus_verbs:ТЕРЯТЬ{}, // Хотя он хорошо питался, он терял в весе (ТЕРЯТЬ/ПОТЕРЯТЬ) rus_verbs:ПоТЕРЯТЬ{}, rus_verbs:УТЕРЯТЬ{}, rus_verbs:РАСТЕРЯТЬ{}, rus_verbs:СМЫКАТЬСЯ{}, // Словно медленно смыкающийся во сне глаз, отверстие медленно закрывалось. (СМЫКАТЬСЯ/СОМКНУТЬСЯ, + оборот с СЛОВНО/БУДТО + вин.п.) rus_verbs:СОМКНУТЬСЯ{}, rus_verbs:РАЗВОРОШИТЬ{}, // Вольф не узнал никаких отдельных слов, но звуки и взаимодействующая высота тонов разворошили что-то в его памяти. (РАЗВОРОШИТЬ) rus_verbs:ПРОСТОЯТЬ{}, // Он поднялся и некоторое время простоял в задумчивости. (ПРОСТОЯТЬ,ВЫСТОЯТЬ,ПОСТОЯТЬ) rus_verbs:ВЫСТОЯТЬ{}, rus_verbs:ПОСТОЯТЬ{}, rus_verbs:ВЗВЕСИТЬ{}, // Он поднял и взвесил в руке один из рогов изобилия. (ВЗВЕСИТЬ/ВЗВЕШИВАТЬ) rus_verbs:ВЗВЕШИВАТЬ{}, rus_verbs:ДРЕЙФОВАТЬ{}, // Он и тогда не упадет, а будет дрейфовать в отбрасываемой диском тени. (ДРЕЙФОВАТЬ) прилагательное:быстрый{}, // Кисель быстр в приготовлении rus_verbs:призвать{}, // В День Воли белорусов призвали побороть страх и лень rus_verbs:призывать{}, rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // этими деньгами смогу воспользоваться в отпуске (ВОСПОЛЬЗОВАТЬСЯ) rus_verbs:КОНКУРИРОВАТЬ{}, // Наши клубы могли бы в Англии конкурировать с лидерами (КОНКУРИРОВАТЬ) rus_verbs:ПОЗВАТЬ{}, // Американскую телеведущую позвали замуж в прямом эфире (ПОЗВАТЬ) rus_verbs:ВЫХОДИТЬ{}, // Районные газеты Вологодчины будут выходить в цвете и новом формате (ВЫХОДИТЬ) rus_verbs:РАЗВОРАЧИВАТЬСЯ{}, // Сюжет фэнтези разворачивается в двух мирах (РАЗВОРАЧИВАТЬСЯ) rus_verbs:ОБСУДИТЬ{}, // В Самаре обсудили перспективы информатизации ветеринарии (ОБСУДИТЬ) rus_verbs:ВЗДРОГНУТЬ{}, // она сильно вздрогнула во сне (ВЗДРОГНУТЬ) rus_verbs:ПРЕДСТАВЛЯТЬ{}, // Сенаторы, представляющие в Комитете по разведке обе партии, поддержали эту просьбу (ПРЕДСТАВЛЯТЬ) rus_verbs:ДОМИНИРОВАТЬ{}, // в химическом составе одной из планет доминирует метан (ДОМИНИРОВАТЬ) rus_verbs:ОТКРЫТЬ{}, // Крым открыл в Москве собственный туристический офис (ОТКРЫТЬ) rus_verbs:ПОКАЗАТЬ{}, // В Пушкинском музее показали золото инков (ПОКАЗАТЬ) rus_verbs:наблюдать{}, // Наблюдаемый в отражении цвет излучения rus_verbs:ПРОЛЕТЕТЬ{}, // Крупный астероид пролетел в непосредственной близости от Земли (ПРОЛЕТЕТЬ) rus_verbs:РАССЛЕДОВАТЬ{}, // В Дагестане расследуют убийство федерального судьи (РАССЛЕДОВАТЬ) rus_verbs:ВОЗОБНОВИТЬСЯ{}, // В Кемеровской области возобновилось движение по трассам международного значения (ВОЗОБНОВИТЬСЯ) rus_verbs:ИЗМЕНИТЬСЯ{}, // изменилась она во всем (ИЗМЕНИТЬСЯ) rus_verbs:СВЕРКАТЬ{}, // за широким окном комнаты город сверкал во тьме разноцветными огнями (СВЕРКАТЬ) rus_verbs:СКОНЧАТЬСЯ{}, // В Риме скончался режиссёр знаменитого сериала «Спрут» (СКОНЧАТЬСЯ) rus_verbs:ПРЯТАТЬСЯ{}, // Cкрытые спутники прячутся в кольцах Сатурна (ПРЯТАТЬСЯ) rus_verbs:ВЫЗЫВАТЬ{}, // этот человек всегда вызывал во мне восхищение (ВЫЗЫВАТЬ) rus_verbs:ВЫПУСТИТЬ{}, // Избирательные бюллетени могут выпустить в форме брошюры (ВЫПУСТИТЬ) rus_verbs:НАЧИНАТЬСЯ{}, // В Москве начинается «марш в защиту детей» (НАЧИНАТЬСЯ) rus_verbs:ЗАСТРЕЛИТЬ{}, // В Дагестане застрелили преподавателя медресе (ЗАСТРЕЛИТЬ) rus_verbs:УРАВНЯТЬ{}, // Госзаказчиков уравняют в правах с поставщиками (УРАВНЯТЬ) rus_verbs:промахнуться{}, // в первой половине невероятным образом промахнулся экс-форвард московского ЦСКА rus_verbs:ОБЫГРАТЬ{}, // "Рубин" сенсационно обыграл в Мадриде вторую команду Испании (ОБЫГРАТЬ) rus_verbs:ВКЛЮЧИТЬ{}, // В Челябинской области включен аварийный роуминг (ВКЛЮЧИТЬ) rus_verbs:УЧАСТИТЬСЯ{}, // В селах Балаковского района участились случаи поджогов стогов сена (УЧАСТИТЬСЯ) rus_verbs:СПАСТИ{}, // В Австралии спасли повисшего на проводе коршуна (СПАСТИ) rus_verbs:ВЫПАСТЬ{}, // Отдельные фрагменты достигли земли, выпав в виде метеоритного дождя (ВЫПАСТЬ) rus_verbs:НАГРАДИТЬ{}, // В Лондоне наградили лауреатов премии Brit Awards (НАГРАДИТЬ) rus_verbs:ОТКРЫТЬСЯ{}, // в Москве открылся первый международный кинофестиваль rus_verbs:ПОДНИМАТЬСЯ{}, // во мне поднималось раздражение rus_verbs:ЗАВЕРШИТЬСЯ{}, // В Италии завершился традиционный Венецианский карнавал (ЗАВЕРШИТЬСЯ) инфинитив:проводить{ вид:несоверш }, // Кузбасские депутаты проводят в Кемерове прием граждан глагол:проводить{ вид:несоверш }, деепричастие:проводя{}, rus_verbs:отсутствовать{}, // Хозяйка квартиры в этот момент отсутствовала rus_verbs:доложить{}, // об итогах своего визита он намерен доложить в американском сенате и Белом доме (ДОЛОЖИТЬ ОБ, В предл) rus_verbs:ИЗДЕВАТЬСЯ{}, // В Эйлате издеваются над туристами (ИЗДЕВАТЬСЯ В предл) rus_verbs:НАРУШИТЬ{}, // В нескольких регионах нарушено наземное транспортное сообщение (НАРУШИТЬ В предл) rus_verbs:БЕЖАТЬ{}, // далеко внизу во тьме бежала невидимая река (БЕЖАТЬ В предл) rus_verbs:СОБРАТЬСЯ{}, // Дмитрий оглядел собравшихся во дворе мальчишек (СОБРАТЬСЯ В предл) rus_verbs:ПОСЛЫШАТЬСЯ{}, // далеко вверху во тьме послышался ответ (ПОСЛЫШАТЬСЯ В предл) rus_verbs:ПОКАЗАТЬСЯ{}, // во дворе показалась высокая фигура (ПОКАЗАТЬСЯ В предл) rus_verbs:УЛЫБНУТЬСЯ{}, // Дмитрий горько улыбнулся во тьме (УЛЫБНУТЬСЯ В предл) rus_verbs:ТЯНУТЬСЯ{}, // убежища тянулись во всех направлениях (ТЯНУТЬСЯ В предл) rus_verbs:РАНИТЬ{}, // В американском университете ранили человека (РАНИТЬ В предл) rus_verbs:ЗАХВАТИТЬ{}, // Пираты освободили корабль, захваченный в Гвинейском заливе (ЗАХВАТИТЬ В предл) rus_verbs:РАЗБЕГАТЬСЯ{}, // люди разбегались во всех направлениях (РАЗБЕГАТЬСЯ В предл) rus_verbs:ПОГАСНУТЬ{}, // во всем доме погас свет (ПОГАСНУТЬ В предл) rus_verbs:ПОШЕВЕЛИТЬСЯ{}, // Дмитрий пошевелился во сне (ПОШЕВЕЛИТЬСЯ В предл) rus_verbs:ЗАСТОНАТЬ{}, // раненый застонал во сне (ЗАСТОНАТЬ В предл) прилагательное:ВИНОВАТЫЙ{}, // во всем виновато вино (ВИНОВАТЫЙ В) rus_verbs:ОСТАВЛЯТЬ{}, // США оставляют в районе Персидского залива только один авианосец (ОСТАВЛЯТЬ В предл) rus_verbs:ОТКАЗЫВАТЬСЯ{}, // В России отказываются от планов авиагруппы в Арктике (ОТКАЗЫВАТЬСЯ В предл) rus_verbs:ЛИКВИДИРОВАТЬ{}, // В Кабардино-Балкарии ликвидирован подпольный завод по переработке нефти (ЛИКВИДИРОВАТЬ В предл) rus_verbs:РАЗОБЛАЧИТЬ{}, // В США разоблачили крупнейшую махинацию с кредитками (РАЗОБЛАЧИТЬ В предл) rus_verbs:СХВАТИТЬ{}, // их схватили во сне (СХВАТИТЬ В предл) rus_verbs:НАЧАТЬ{}, // В Белгороде начали сбор подписей за отставку мэра (НАЧАТЬ В предл) rus_verbs:РАСТИ{}, // Cамая маленькая муха растёт в голове муравья (РАСТИ В предл) rus_verbs:похитить{}, // Двое россиян, похищенных террористами в Сирии, освобождены (похитить в предл) rus_verbs:УЧАСТВОВАТЬ{}, // были застрелены два испанских гражданских гвардейца , участвовавших в слежке (УЧАСТВОВАТЬ В) rus_verbs:УСЫНОВИТЬ{}, // Американцы забирают усыновленных в России детей (УСЫНОВИТЬ В) rus_verbs:ПРОИЗВЕСТИ{}, // вы не увидите мясо или молоко , произведенное в районе (ПРОИЗВЕСТИ В предл) rus_verbs:ОРИЕНТИРОВАТЬСЯ{}, // призван помочь госслужащему правильно ориентироваться в сложных нравственных коллизиях (ОРИЕНТИРОВАТЬСЯ В) rus_verbs:ПОВРЕДИТЬ{}, // В зале игровых автоматов повреждены стены и потолок (ПОВРЕДИТЬ В предл) rus_verbs:ИЗЪЯТЬ{}, // В настоящее время в детском учреждении изъяты суточные пробы пищи (ИЗЪЯТЬ В предл) rus_verbs:СОДЕРЖАТЬСЯ{}, // осужденных , содержащихся в помещениях штрафного изолятора (СОДЕРЖАТЬСЯ В) rus_verbs:ОТЧИСЛИТЬ{}, // был отчислен за неуспеваемость в 2007 году (ОТЧИСЛИТЬ В предл) rus_verbs:проходить{}, // находился на санкционированном митинге , проходившем в рамках празднования Дня народного единства (проходить в предл) rus_verbs:ПОДУМЫВАТЬ{}, // сейчас в правительстве Приамурья подумывают о создании специального пункта помощи туристам (ПОДУМЫВАТЬ В) rus_verbs:ОТРАПОРТОВЫВАТЬ{}, // главы субъектов не просто отрапортовывали в Москве (ОТРАПОРТОВЫВАТЬ В предл) rus_verbs:ВЕСТИСЬ{}, // в городе ведутся работы по установке праздничной иллюминации (ВЕСТИСЬ В) rus_verbs:ОДОБРИТЬ{}, // Одобренным в первом чтении законопроектом (ОДОБРИТЬ В) rus_verbs:ЗАМЫЛИТЬСЯ{}, // ему легче исправлять , то , что замылилось в глазах предыдущего руководства (ЗАМЫЛИТЬСЯ В) rus_verbs:АВТОРИЗОВАТЬСЯ{}, // потом имеют право авторизоваться в системе Международного бакалавриата (АВТОРИЗОВАТЬСЯ В) rus_verbs:ОПУСТИТЬСЯ{}, // Россия опустилась в списке на шесть позиций (ОПУСТИТЬСЯ В предл) rus_verbs:СГОРЕТЬ{}, // Совладелец сгоревшего в Бразилии ночного клуба сдался полиции (СГОРЕТЬ В) частица:нет{}, // В этом нет сомнения. частица:нету{}, // В этом нету сомнения. rus_verbs:поджечь{}, // Поджегший себя в Москве мужчина оказался ветераном-афганцем rus_verbs:ввести{}, // В Молдавии введен запрет на амнистию или помилование педофилов. прилагательное:ДОСТУПНЫЙ{}, // Наиболее интересные таблички доступны в основной экспозиции музея (ДОСТУПНЫЙ В) rus_verbs:ПОВИСНУТЬ{}, // вопрос повис в мглистом демократическом воздухе (ПОВИСНУТЬ В) rus_verbs:ВЗОРВАТЬ{}, // В Ираке смертник взорвал в мечети группу туркменов (ВЗОРВАТЬ В) rus_verbs:ОТНЯТЬ{}, // В Финляндии у россиянки, прибывшей по туристической визе, отняли детей (ОТНЯТЬ В) rus_verbs:НАЙТИ{}, // Я недавно посетил врача и у меня в глазах нашли какую-то фигню (НАЙТИ В предл) rus_verbs:ЗАСТРЕЛИТЬСЯ{}, // Девушка, застрелившаяся в центре Киева, была замешана в скандале с влиятельными людьми (ЗАСТРЕЛИТЬСЯ В) rus_verbs:стартовать{}, // В Страсбурге сегодня стартует зимняя сессия Парламентской ассамблеи Совета Европы (стартовать в) rus_verbs:ЗАКЛАДЫВАТЬСЯ{}, // Отношение к деньгам закладывается в детстве (ЗАКЛАДЫВАТЬСЯ В) rus_verbs:НАПИВАТЬСЯ{}, // Депутатам помешают напиваться в здании Госдумы (НАПИВАТЬСЯ В) rus_verbs:ВЫПРАВИТЬСЯ{}, // Прежде всего было заявлено, что мировая экономика каким-то образом сама выправится в процессе бизнес-цикла (ВЫПРАВИТЬСЯ В) rus_verbs:ЯВЛЯТЬСЯ{}, // она являлась ко мне во всех моих снах (ЯВЛЯТЬСЯ В) rus_verbs:СТАЖИРОВАТЬСЯ{}, // сейчас я стажируюсь в одной компании (СТАЖИРОВАТЬСЯ В) rus_verbs:ОБСТРЕЛЯТЬ{}, // Уроженцы Чечни, обстрелявшие полицейских в центре Москвы, арестованы (ОБСТРЕЛЯТЬ В) rus_verbs:РАСПРОСТРАНИТЬ{}, // Воски — распространённые в растительном и животном мире сложные эфиры высших жирных кислот и высших высокомолекулярных спиртов (РАСПРОСТРАНИТЬ В) rus_verbs:ПРИВЕСТИ{}, // Сравнительная фугасность некоторых взрывчатых веществ приведена в следующей таблице (ПРИВЕСТИ В) rus_verbs:ЗАПОДОЗРИТЬ{}, // Чиновников Минкультуры заподозрили в афере с заповедными землями (ЗАПОДОЗРИТЬ В) rus_verbs:НАСТУПАТЬ{}, // В Гренландии стали наступать ледники (НАСТУПАТЬ В) rus_verbs:ВЫДЕЛЯТЬСЯ{}, // В истории Земли выделяются следующие ледниковые эры (ВЫДЕЛЯТЬСЯ В) rus_verbs:ПРЕДСТАВИТЬ{}, // Данные представлены в хронологическом порядке (ПРЕДСТАВИТЬ В) rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА) rus_verbs:ПОДАВАТЬ{}, // Готовые компоты подают в столовых и кафе (ПОДАВАТЬ В) rus_verbs:ГОТОВИТЬ{}, // Сегодня компот готовят в домашних условиях из сухофруктов или замороженных фруктов и ягод (ГОТОВИТЬ В) rus_verbs:ВОЗДЕЛЫВАТЬСЯ{}, // в настоящее время он повсеместно возделывается в огородах (ВОЗДЕЛЫВАТЬСЯ В) rus_verbs:РАСКЛАДЫВАТЬ{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА) rus_verbs:РАСКЛАДЫВАТЬСЯ{}, rus_verbs:СОБИРАТЬСЯ{}, // Обыкновенно огурцы собираются в полуспелом состоянии (СОБИРАТЬСЯ В) rus_verbs:ПРОГРЕМЕТЬ{}, // В торговом центре Ижевска прогремел взрыв (ПРОГРЕМЕТЬ В) rus_verbs:СНЯТЬ{}, // чтобы снять их во всей красоте. (СНЯТЬ В) rus_verbs:ЯВИТЬСЯ{}, // она явилась к нему во сне. (ЯВИТЬСЯ В) rus_verbs:ВЕРИТЬ{}, // мы же во всем верили капитану. (ВЕРИТЬ В предл) rus_verbs:выдержать{}, // Игра выдержана в научно-фантастическом стиле. (ВЫДЕРЖАННЫЙ В) rus_verbs:ПРЕОДОЛЕТЬ{}, // мы пытались преодолеть ее во многих местах. (ПРЕОДОЛЕТЬ В) инфинитив:НАПИСАТЬ{ aux stress="напис^ать" }, // Программа, написанная в спешке, выполнила недопустимую операцию. (НАПИСАТЬ В) глагол:НАПИСАТЬ{ aux stress="напис^ать" }, прилагательное:НАПИСАННЫЙ{}, rus_verbs:ЕСТЬ{}, // ты даже во сне ел. (ЕСТЬ/кушать В) rus_verbs:УСЕСТЬСЯ{}, // Он удобно уселся в кресле. (УСЕСТЬСЯ В) rus_verbs:ТОРГОВАТЬ{}, // Он торгует в палатке. (ТОРГОВАТЬ В) rus_verbs:СОВМЕСТИТЬ{}, // Он совместил в себе писателя и художника. (СОВМЕСТИТЬ В) rus_verbs:ЗАБЫВАТЬ{}, // об этом нельзя забывать даже во сне. (ЗАБЫВАТЬ В) rus_verbs:поговорить{}, // Давайте поговорим об этом в присутствии адвоката rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ) rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА) rus_verbs:раскрыть{}, // В России раскрыли крупнейшую в стране сеть фальшивомонетчиков (РАСКРЫТЬ В) rus_verbs:соединить{}, // соединить в себе (СОЕДИНИТЬ В предл) rus_verbs:избрать{}, // В Южной Корее избран новый президент (ИЗБРАТЬ В предл) rus_verbs:проводиться{}, // Обыски проводятся в воронежском Доме прав человека (ПРОВОДИТЬСЯ В) безлич_глагол:хватает{}, // В этой статье не хватает ссылок на источники информации. (БЕЗЛИЧ хватать в) rus_verbs:наносить{}, // В ближнем бою наносит мощные удары своим костлявым кулаком. (НАНОСИТЬ В + предл.) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) прилагательное:известный{}, // В Европе сахар был известен ещё римлянам. (ИЗВЕСТНЫЙ В) rus_verbs:выработать{}, // Способы, выработанные во Франции, перешли затем в Германию и другие страны Европы. (ВЫРАБОТАТЬ В) rus_verbs:КУЛЬТИВИРОВАТЬСЯ{}, // Культивируется в регионах с умеренным климатом с умеренным количеством осадков и требует плодородной почвы. (КУЛЬТИВИРОВАТЬСЯ В) rus_verbs:чаять{}, // мама души не чаяла в своих детях (ЧАЯТЬ В) rus_verbs:улыбаться{}, // Вадим улыбался во сне. (УЛЫБАТЬСЯ В) rus_verbs:растеряться{}, // Приезжие растерялись в бетонном лабиринте улиц (РАСТЕРЯТЬСЯ В) rus_verbs:выть{}, // выли волки где-то в лесу (ВЫТЬ В) rus_verbs:ЗАВЕРИТЬ{}, // выступавший заверил нас в намерении выполнить обещание (ЗАВЕРИТЬ В) rus_verbs:ИСЧЕЗНУТЬ{}, // звери исчезли во мраке. (ИСЧЕЗНУТЬ В) rus_verbs:ВСТАТЬ{}, // встать во главе человечества. (ВСТАТЬ В) rus_verbs:УПОТРЕБЛЯТЬ{}, // В Тибете употребляют кирпичный зелёный чай. (УПОТРЕБЛЯТЬ В) rus_verbs:ПОДАВАТЬСЯ{}, // Напиток охлаждается и подаётся в холодном виде. (ПОДАВАТЬСЯ В) rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // в игре используются текстуры большего разрешения (ИСПОЛЬЗОВАТЬСЯ В) rus_verbs:объявить{}, // В газете объявили о конкурсе. rus_verbs:ВСПЫХНУТЬ{}, // во мне вспыхнул гнев. (ВСПЫХНУТЬ В) rus_verbs:КРЫТЬСЯ{}, // В его словах кроется угроза. (КРЫТЬСЯ В) rus_verbs:подняться{}, // В классе вдруг поднялся шум. (подняться в) rus_verbs:наступить{}, // В классе наступила полная тишина. (наступить в) rus_verbs:кипеть{}, // В нём кипит злоба. (кипеть в) rus_verbs:соединиться{}, // В нём соединились храбрость и великодушие. (соединиться в) инфинитив:ПАРИТЬ{ aux stress="пар^ить"}, // Высоко в небе парит орёл, плавно описывая круги. (ПАРИТЬ В) глагол:ПАРИТЬ{ aux stress="пар^ить"}, деепричастие:паря{ aux stress="пар^я" }, прилагательное:ПАРЯЩИЙ{}, прилагательное:ПАРИВШИЙ{}, rus_verbs:СИЯТЬ{}, // Главы собора сияли в лучах солнца. (СИЯТЬ В) rus_verbs:РАСПОЛОЖИТЬ{}, // Гостиница расположена глубоко в горах. (РАСПОЛОЖИТЬ В) rus_verbs:развиваться{}, // Действие в комедии развивается в двух планах. (развиваться в) rus_verbs:ПОСАДИТЬ{}, // Дети посадили у нас во дворе цветы. (ПОСАДИТЬ В) rus_verbs:ИСКОРЕНЯТЬ{}, // Дурные привычки следует искоренять в самом начале. (ИСКОРЕНЯТЬ В) rus_verbs:ВОССТАНОВИТЬ{}, // Его восстановили в правах. (ВОССТАНОВИТЬ В) rus_verbs:ПОЛАГАТЬСЯ{}, // мы полагаемся на него в этих вопросах (ПОЛАГАТЬСЯ В) rus_verbs:УМИРАТЬ{}, // они умирали во сне. (УМИРАТЬ В) rus_verbs:ПРИБАВИТЬ{}, // Она сильно прибавила в весе. (ПРИБАВИТЬ В) rus_verbs:посмотреть{}, // Посмотрите в списке. (посмотреть в) rus_verbs:производиться{}, // Выдача новых паспортов будет производиться в следующем порядке (производиться в) rus_verbs:принять{}, // Документ принят в следующей редакции (принять в) rus_verbs:сверкнуть{}, // меч его сверкнул во тьме. (сверкнуть в) rus_verbs:ВЫРАБАТЫВАТЬ{}, // ты должен вырабатывать в себе силу воли (ВЫРАБАТЫВАТЬ В) rus_verbs:достать{}, // Эти сведения мы достали в Волгограде. (достать в) rus_verbs:звучать{}, // в доме звучала музыка (звучать в) rus_verbs:колебаться{}, // колеблется в выборе (колебаться в) rus_verbs:мешать{}, // мешать в кастрюле суп (мешать в) rus_verbs:нарастать{}, // во мне нарастал гнев (нарастать в) rus_verbs:отбыть{}, // Вадим отбыл в неизвестном направлении (отбыть в) rus_verbs:светиться{}, // во всем доме светилось только окно ее спальни. (светиться в) rus_verbs:вычитывать{}, // вычитывать в книге rus_verbs:гудеть{}, // У него в ушах гудит. rus_verbs:давать{}, // В этой лавке дают в долг? rus_verbs:поблескивать{}, // Красивое стеклышко поблескивало в пыльной траве у дорожки. rus_verbs:разойтись{}, // Они разошлись в темноте. rus_verbs:прибежать{}, // Мальчик прибежал в слезах. rus_verbs:биться{}, // Она билась в истерике. rus_verbs:регистрироваться{}, // регистрироваться в системе rus_verbs:считать{}, // я буду считать в уме rus_verbs:трахаться{}, // трахаться в гамаке rus_verbs:сконцентрироваться{}, // сконцентрироваться в одной точке rus_verbs:разрушать{}, // разрушать в дробилке rus_verbs:засидеться{}, // засидеться в гостях rus_verbs:засиживаться{}, // засиживаться в гостях rus_verbs:утопить{}, // утопить лодку в реке (утопить в реке) rus_verbs:навестить{}, // навестить в доме престарелых rus_verbs:запомнить{}, // запомнить в кэше rus_verbs:убивать{}, // убивать в помещении полиции (-score убивать неодуш. дом.) rus_verbs:базироваться{}, // установка базируется в черте города (ngram черта города - проверить что есть проверка) rus_verbs:покупать{}, // Чаще всего россияне покупают в интернете бытовую технику. rus_verbs:ходить{}, // ходить в пальто (сделать ХОДИТЬ + в + ОДЕЖДА предл.п.) rus_verbs:заложить{}, // диверсанты заложили в помещении бомбу rus_verbs:оглядываться{}, // оглядываться в зеркале rus_verbs:нарисовать{}, // нарисовать в тетрадке rus_verbs:пробить{}, // пробить отверствие в стене rus_verbs:повертеть{}, // повертеть в руке rus_verbs:вертеть{}, // Я вертел в руках rus_verbs:рваться{}, // Веревка рвется в месте надреза rus_verbs:распространяться{}, // распространяться в среде наркоманов rus_verbs:попрощаться{}, // попрощаться в здании морга rus_verbs:соображать{}, // соображать в уме инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, // просыпаться в чужой кровати rus_verbs:заехать{}, // Коля заехал в гости (в гости - устойчивый наречный оборот) rus_verbs:разобрать{}, // разобрать в гараже rus_verbs:помереть{}, // помереть в пути rus_verbs:различить{}, // различить в темноте rus_verbs:рисовать{}, // рисовать в графическом редакторе rus_verbs:проследить{}, // проследить в записях камер слежения rus_verbs:совершаться{}, // Правосудие совершается в суде rus_verbs:задремать{}, // задремать в кровати rus_verbs:ругаться{}, // ругаться в комнате rus_verbs:зазвучать{}, // зазвучать в радиоприемниках rus_verbs:задохнуться{}, // задохнуться в воде rus_verbs:порождать{}, // порождать в неокрепших умах rus_verbs:отдыхать{}, // отдыхать в санатории rus_verbs:упоминаться{}, // упоминаться в предыдущем сообщении rus_verbs:образовать{}, // образовать в пробирке темную взвесь rus_verbs:отмечать{}, // отмечать в списке rus_verbs:подчеркнуть{}, // подчеркнуть в блокноте rus_verbs:плясать{}, // плясать в откружении незнакомых людей rus_verbs:повысить{}, // повысить в звании rus_verbs:поджидать{}, // поджидать в подъезде rus_verbs:отказать{}, // отказать в пересмотре дела rus_verbs:раствориться{}, // раствориться в бензине rus_verbs:отражать{}, // отражать в стихах rus_verbs:дремать{}, // дремать в гамаке rus_verbs:применяться{}, // применяться в домашних условиях rus_verbs:присниться{}, // присниться во сне rus_verbs:трястись{}, // трястись в драндулете rus_verbs:сохранять{}, // сохранять в неприкосновенности rus_verbs:расстрелять{}, // расстрелять в ложбине rus_verbs:рассчитать{}, // рассчитать в программе rus_verbs:перебирать{}, // перебирать в руке rus_verbs:разбиться{}, // разбиться в аварии rus_verbs:поискать{}, // поискать в углу rus_verbs:мучиться{}, // мучиться в тесной клетке rus_verbs:замелькать{}, // замелькать в телевизоре rus_verbs:грустить{}, // грустить в одиночестве rus_verbs:крутить{}, // крутить в банке rus_verbs:объявиться{}, // объявиться в городе rus_verbs:подготовить{}, // подготовить в тайне rus_verbs:различать{}, // различать в смеси rus_verbs:обнаруживать{}, // обнаруживать в крови rus_verbs:киснуть{}, // киснуть в захолустье rus_verbs:оборваться{}, // оборваться в начале фразы rus_verbs:запутаться{}, // запутаться в веревках rus_verbs:общаться{}, // общаться в интимной обстановке rus_verbs:сочинить{}, // сочинить в ресторане rus_verbs:изобрести{}, // изобрести в домашней лаборатории rus_verbs:прокомментировать{}, // прокомментировать в своем блоге rus_verbs:давить{}, // давить в зародыше rus_verbs:повториться{}, // повториться в новом обличье rus_verbs:отставать{}, // отставать в общем зачете rus_verbs:разработать{}, // разработать в лаборатории rus_verbs:качать{}, // качать в кроватке rus_verbs:заменить{}, // заменить в двигателе rus_verbs:задыхаться{}, // задыхаться в душной и влажной атмосфере rus_verbs:забегать{}, // забегать в спешке rus_verbs:наделать{}, // наделать в решении ошибок rus_verbs:исказиться{}, // исказиться в кривом зеркале rus_verbs:тушить{}, // тушить в помещении пожар rus_verbs:охранять{}, // охранять в здании входы rus_verbs:приметить{}, // приметить в кустах rus_verbs:скрыть{}, // скрыть в складках одежды rus_verbs:удерживать{}, // удерживать в заложниках rus_verbs:увеличиваться{}, // увеличиваться в размере rus_verbs:красоваться{}, // красоваться в новом платье rus_verbs:сохраниться{}, // сохраниться в тепле rus_verbs:лечить{}, // лечить в стационаре rus_verbs:смешаться{}, // смешаться в баке rus_verbs:прокатиться{}, // прокатиться в троллейбусе rus_verbs:договариваться{}, // договариваться в закрытом кабинете rus_verbs:опубликовать{}, // опубликовать в официальном блоге rus_verbs:охотиться{}, // охотиться в прериях rus_verbs:отражаться{}, // отражаться в окне rus_verbs:понизить{}, // понизить в должности rus_verbs:обедать{}, // обедать в ресторане rus_verbs:посидеть{}, // посидеть в тени rus_verbs:сообщаться{}, // сообщаться в оппозиционной газете rus_verbs:свершиться{}, // свершиться в суде rus_verbs:ночевать{}, // ночевать в гостинице rus_verbs:темнеть{}, // темнеть в воде rus_verbs:гибнуть{}, // гибнуть в застенках rus_verbs:усиливаться{}, // усиливаться в направлении главного удара rus_verbs:расплыться{}, // расплыться в улыбке rus_verbs:превышать{}, // превышать в несколько раз rus_verbs:проживать{}, // проживать в отдельной коморке rus_verbs:голубеть{}, // голубеть в тепле rus_verbs:исследовать{}, // исследовать в естественных условиях rus_verbs:обитать{}, // обитать в лесу rus_verbs:скучать{}, // скучать в одиночестве rus_verbs:сталкиваться{}, // сталкиваться в воздухе rus_verbs:таиться{}, // таиться в глубине rus_verbs:спасать{}, // спасать в море rus_verbs:заблудиться{}, // заблудиться в лесу rus_verbs:создаться{}, // создаться в новом виде rus_verbs:пошарить{}, // пошарить в кармане rus_verbs:планировать{}, // планировать в программе rus_verbs:отбить{}, // отбить в нижней части rus_verbs:отрицать{}, // отрицать в суде свою вину rus_verbs:основать{}, // основать в пустыне новый город rus_verbs:двоить{}, // двоить в глазах rus_verbs:устоять{}, // устоять в лодке rus_verbs:унять{}, // унять в ногах дрожь rus_verbs:отзываться{}, // отзываться в обзоре rus_verbs:притормозить{}, // притормозить в траве rus_verbs:читаться{}, // читаться в глазах rus_verbs:житься{}, // житься в деревне rus_verbs:заиграть{}, // заиграть в жилах rus_verbs:шевелить{}, // шевелить в воде rus_verbs:зазвенеть{}, // зазвенеть в ушах rus_verbs:зависнуть{}, // зависнуть в библиотеке rus_verbs:затаить{}, // затаить в душе обиду rus_verbs:сознаться{}, // сознаться в совершении rus_verbs:протекать{}, // протекать в легкой форме rus_verbs:выясняться{}, // выясняться в ходе эксперимента rus_verbs:скрестить{}, // скрестить в неволе rus_verbs:наводить{}, // наводить в комнате порядок rus_verbs:значиться{}, // значиться в документах rus_verbs:заинтересовать{}, // заинтересовать в получении результатов rus_verbs:познакомить{}, // познакомить в непринужденной обстановке rus_verbs:рассеяться{}, // рассеяться в воздухе rus_verbs:грохнуть{}, // грохнуть в подвале rus_verbs:обвинять{}, // обвинять в вымогательстве rus_verbs:столпиться{}, // столпиться в фойе rus_verbs:порыться{}, // порыться в сумке rus_verbs:ослабить{}, // ослабить в верхней части rus_verbs:обнаруживаться{}, // обнаруживаться в кармане куртки rus_verbs:спастись{}, // спастись в хижине rus_verbs:прерваться{}, // прерваться в середине фразы rus_verbs:применять{}, // применять в повседневной работе rus_verbs:строиться{}, // строиться в зоне отчуждения rus_verbs:путешествовать{}, // путешествовать в самолете rus_verbs:побеждать{}, // побеждать в честной битве rus_verbs:погубить{}, // погубить в себе артиста rus_verbs:рассматриваться{}, // рассматриваться в следующей главе rus_verbs:продаваться{}, // продаваться в специализированном магазине rus_verbs:разместиться{}, // разместиться в аудитории rus_verbs:повидать{}, // повидать в жизни rus_verbs:настигнуть{}, // настигнуть в пригородах rus_verbs:сгрудиться{}, // сгрудиться в центре загона rus_verbs:укрыться{}, // укрыться в доме rus_verbs:расплакаться{}, // расплакаться в суде rus_verbs:пролежать{}, // пролежать в канаве rus_verbs:замерзнуть{}, // замерзнуть в ледяной воде rus_verbs:поскользнуться{}, // поскользнуться в коридоре rus_verbs:таскать{}, // таскать в руках rus_verbs:нападать{}, // нападать в вольере rus_verbs:просматривать{}, // просматривать в браузере rus_verbs:обдумать{}, // обдумать в дороге rus_verbs:обвинить{}, // обвинить в измене rus_verbs:останавливать{}, // останавливать в дверях rus_verbs:теряться{}, // теряться в догадках rus_verbs:погибать{}, // погибать в бою rus_verbs:обозначать{}, // обозначать в списке rus_verbs:запрещать{}, // запрещать в парке rus_verbs:долететь{}, // долететь в вертолёте rus_verbs:тесниться{}, // тесниться в каморке rus_verbs:уменьшаться{}, // уменьшаться в размере rus_verbs:издавать{}, // издавать в небольшом издательстве rus_verbs:хоронить{}, // хоронить в море rus_verbs:перемениться{}, // перемениться в лице rus_verbs:установиться{}, // установиться в северных областях rus_verbs:прикидывать{}, // прикидывать в уме rus_verbs:затаиться{}, // затаиться в траве rus_verbs:раздобыть{}, // раздобыть в аптеке rus_verbs:перебросить{}, // перебросить в товарном составе rus_verbs:погружаться{}, // погружаться в батискафе rus_verbs:поживать{}, // поживать в одиночестве rus_verbs:признаваться{}, // признаваться в любви rus_verbs:захватывать{}, // захватывать в здании rus_verbs:покачиваться{}, // покачиваться в лодке rus_verbs:крутиться{}, // крутиться в колесе rus_verbs:помещаться{}, // помещаться в ящике rus_verbs:питаться{}, // питаться в столовой rus_verbs:отдохнуть{}, // отдохнуть в пансионате rus_verbs:кататься{}, // кататься в коляске rus_verbs:поработать{}, // поработать в цеху rus_verbs:подразумевать{}, // подразумевать в задании rus_verbs:ограбить{}, // ограбить в подворотне rus_verbs:преуспеть{}, // преуспеть в бизнесе rus_verbs:заерзать{}, // заерзать в кресле rus_verbs:разъяснить{}, // разъяснить в другой статье rus_verbs:продвинуться{}, // продвинуться в изучении rus_verbs:поколебаться{}, // поколебаться в начале rus_verbs:засомневаться{}, // засомневаться в честности rus_verbs:приникнуть{}, // приникнуть в уме rus_verbs:скривить{}, // скривить в усмешке rus_verbs:рассечь{}, // рассечь в центре опухоли rus_verbs:перепутать{}, // перепутать в роддоме rus_verbs:посмеяться{}, // посмеяться в перерыве rus_verbs:отмечаться{}, // отмечаться в полицейском участке rus_verbs:накопиться{}, // накопиться в отстойнике rus_verbs:уносить{}, // уносить в руках rus_verbs:навещать{}, // навещать в больнице rus_verbs:остыть{}, // остыть в проточной воде rus_verbs:запереться{}, // запереться в комнате rus_verbs:обогнать{}, // обогнать в первом круге rus_verbs:убеждаться{}, // убеждаться в неизбежности rus_verbs:подбирать{}, // подбирать в магазине rus_verbs:уничтожать{}, // уничтожать в полете rus_verbs:путаться{}, // путаться в показаниях rus_verbs:притаиться{}, // притаиться в темноте rus_verbs:проплывать{}, // проплывать в лодке rus_verbs:засесть{}, // засесть в окопе rus_verbs:подцепить{}, // подцепить в баре rus_verbs:насчитать{}, // насчитать в диктанте несколько ошибок rus_verbs:оправдаться{}, // оправдаться в суде rus_verbs:созреть{}, // созреть в естественных условиях rus_verbs:раскрываться{}, // раскрываться в подходящих условиях rus_verbs:ожидаться{}, // ожидаться в верхней части rus_verbs:одеваться{}, // одеваться в дорогих бутиках rus_verbs:упрекнуть{}, // упрекнуть в недостатке опыта rus_verbs:грабить{}, // грабить в подворотне rus_verbs:ужинать{}, // ужинать в ресторане rus_verbs:гонять{}, // гонять в жилах rus_verbs:уверить{}, // уверить в безопасности rus_verbs:потеряться{}, // потеряться в лесу rus_verbs:устанавливаться{}, // устанавливаться в комнате rus_verbs:предоставлять{}, // предоставлять в суде rus_verbs:протянуться{}, // протянуться в стене rus_verbs:допрашивать{}, // допрашивать в бункере rus_verbs:проработать{}, // проработать в кабинете rus_verbs:сосредоточить{}, // сосредоточить в своих руках rus_verbs:утвердить{}, // утвердить в должности rus_verbs:сочинять{}, // сочинять в дороге rus_verbs:померкнуть{}, // померкнуть в глазах rus_verbs:показываться{}, // показываться в окошке rus_verbs:похудеть{}, // похудеть в талии rus_verbs:проделывать{}, // проделывать в стене rus_verbs:прославиться{}, // прославиться в интернете rus_verbs:сдохнуть{}, // сдохнуть в нищете rus_verbs:раскинуться{}, // раскинуться в степи rus_verbs:развить{}, // развить в себе способности rus_verbs:уставать{}, // уставать в цеху rus_verbs:укрепить{}, // укрепить в земле rus_verbs:числиться{}, // числиться в списке rus_verbs:образовывать{}, // образовывать в смеси rus_verbs:екнуть{}, // екнуть в груди rus_verbs:одобрять{}, // одобрять в своей речи rus_verbs:запить{}, // запить в одиночестве rus_verbs:забыться{}, // забыться в тяжелом сне rus_verbs:чернеть{}, // чернеть в кислой среде rus_verbs:размещаться{}, // размещаться в гараже rus_verbs:соорудить{}, // соорудить в гараже rus_verbs:развивать{}, // развивать в себе rus_verbs:пастись{}, // пастись в пойме rus_verbs:формироваться{}, // формироваться в верхних слоях атмосферы rus_verbs:ослабнуть{}, // ослабнуть в сочленении rus_verbs:таить{}, // таить в себе инфинитив:пробегать{ вид:несоверш }, глагол:пробегать{ вид:несоверш }, // пробегать в спешке rus_verbs:приостановиться{}, // приостановиться в конце rus_verbs:топтаться{}, // топтаться в грязи rus_verbs:громить{}, // громить в финале rus_verbs:заменять{}, // заменять в основном составе rus_verbs:подъезжать{}, // подъезжать в колясках rus_verbs:вычислить{}, // вычислить в уме rus_verbs:заказывать{}, // заказывать в магазине rus_verbs:осуществить{}, // осуществить в реальных условиях rus_verbs:обосноваться{}, // обосноваться в дупле rus_verbs:пытать{}, // пытать в камере rus_verbs:поменять{}, // поменять в магазине rus_verbs:совершиться{}, // совершиться в суде rus_verbs:пролетать{}, // пролетать в вертолете rus_verbs:сбыться{}, // сбыться во сне rus_verbs:разговориться{}, // разговориться в отделении rus_verbs:преподнести{}, // преподнести в красивой упаковке rus_verbs:напечатать{}, // напечатать в типографии rus_verbs:прорвать{}, // прорвать в центре rus_verbs:раскачиваться{}, // раскачиваться в кресле rus_verbs:задерживаться{}, // задерживаться в дверях rus_verbs:угощать{}, // угощать в кафе rus_verbs:проступать{}, // проступать в глубине rus_verbs:шарить{}, // шарить в математике rus_verbs:увеличивать{}, // увеличивать в конце rus_verbs:расцвести{}, // расцвести в оранжерее rus_verbs:закипеть{}, // закипеть в баке rus_verbs:подлететь{}, // подлететь в вертолете rus_verbs:рыться{}, // рыться в куче rus_verbs:пожить{}, // пожить в гостинице rus_verbs:добираться{}, // добираться в попутном транспорте rus_verbs:перекрыть{}, // перекрыть в коридоре rus_verbs:продержаться{}, // продержаться в барокамере rus_verbs:разыскивать{}, // разыскивать в толпе rus_verbs:освобождать{}, // освобождать в зале суда rus_verbs:подметить{}, // подметить в человеке rus_verbs:передвигаться{}, // передвигаться в узкой юбке rus_verbs:продумать{}, // продумать в уме rus_verbs:извиваться{}, // извиваться в траве rus_verbs:процитировать{}, // процитировать в статье rus_verbs:прогуливаться{}, // прогуливаться в парке rus_verbs:защемить{}, // защемить в двери rus_verbs:увеличиться{}, // увеличиться в объеме rus_verbs:проявиться{}, // проявиться в результатах rus_verbs:заскользить{}, // заскользить в ботинках rus_verbs:пересказать{}, // пересказать в своем выступлении rus_verbs:протестовать{}, // протестовать в здании парламента rus_verbs:указываться{}, // указываться в путеводителе rus_verbs:копошиться{}, // копошиться в песке rus_verbs:проигнорировать{}, // проигнорировать в своей работе rus_verbs:купаться{}, // купаться в речке rus_verbs:подсчитать{}, // подсчитать в уме rus_verbs:разволноваться{}, // разволноваться в классе rus_verbs:придумывать{}, // придумывать в своем воображении rus_verbs:предусмотреть{}, // предусмотреть в программе rus_verbs:завертеться{}, // завертеться в колесе rus_verbs:зачерпнуть{}, // зачерпнуть в ручье rus_verbs:очистить{}, // очистить в химической лаборатории rus_verbs:прозвенеть{}, // прозвенеть в коридорах rus_verbs:уменьшиться{}, // уменьшиться в размере rus_verbs:колыхаться{}, // колыхаться в проточной воде rus_verbs:ознакомиться{}, // ознакомиться в автобусе rus_verbs:ржать{}, // ржать в аудитории rus_verbs:раскинуть{}, // раскинуть в микрорайоне rus_verbs:разлиться{}, // разлиться в воде rus_verbs:сквозить{}, // сквозить в словах rus_verbs:задушить{}, // задушить в объятиях rus_verbs:осудить{}, // осудить в особом порядке rus_verbs:разгромить{}, // разгромить в честном поединке rus_verbs:подслушать{}, // подслушать в кулуарах rus_verbs:проповедовать{}, // проповедовать в сельских районах rus_verbs:озарить{}, // озарить во сне rus_verbs:потирать{}, // потирать в предвкушении rus_verbs:описываться{}, // описываться в статье rus_verbs:качаться{}, // качаться в кроватке rus_verbs:усилить{}, // усилить в центре rus_verbs:прохаживаться{}, // прохаживаться в новом костюме rus_verbs:полечить{}, // полечить в больничке rus_verbs:сниматься{}, // сниматься в римейке rus_verbs:сыскать{}, // сыскать в наших краях rus_verbs:поприветствовать{}, // поприветствовать в коридоре rus_verbs:подтвердиться{}, // подтвердиться в эксперименте rus_verbs:плескаться{}, // плескаться в теплой водичке rus_verbs:расширяться{}, // расширяться в первом сегменте rus_verbs:мерещиться{}, // мерещиться в тумане rus_verbs:сгущаться{}, // сгущаться в воздухе rus_verbs:храпеть{}, // храпеть во сне rus_verbs:подержать{}, // подержать в руках rus_verbs:накинуться{}, // накинуться в подворотне rus_verbs:планироваться{}, // планироваться в закрытом режиме rus_verbs:пробудить{}, // пробудить в себе rus_verbs:побриться{}, // побриться в ванной rus_verbs:сгинуть{}, // сгинуть в пучине rus_verbs:окрестить{}, // окрестить в церкви инфинитив:резюмировать{ вид:соверш }, глагол:резюмировать{ вид:соверш }, // резюмировать в конце выступления rus_verbs:замкнуться{}, // замкнуться в себе rus_verbs:прибавлять{}, // прибавлять в весе rus_verbs:проплыть{}, // проплыть в лодке rus_verbs:растворяться{}, // растворяться в тумане rus_verbs:упрекать{}, // упрекать в небрежности rus_verbs:затеряться{}, // затеряться в лабиринте rus_verbs:перечитывать{}, // перечитывать в поезде rus_verbs:перелететь{}, // перелететь в вертолете rus_verbs:оживать{}, // оживать в теплой воде rus_verbs:заглохнуть{}, // заглохнуть в полете rus_verbs:кольнуть{}, // кольнуть в боку rus_verbs:копаться{}, // копаться в куче rus_verbs:развлекаться{}, // развлекаться в клубе rus_verbs:отливать{}, // отливать в кустах rus_verbs:зажить{}, // зажить в деревне rus_verbs:одолжить{}, // одолжить в соседнем кабинете rus_verbs:заклинать{}, // заклинать в своей речи rus_verbs:различаться{}, // различаться в мелочах rus_verbs:печататься{}, // печататься в типографии rus_verbs:угадываться{}, // угадываться в контурах rus_verbs:обрывать{}, // обрывать в начале rus_verbs:поглаживать{}, // поглаживать в кармане rus_verbs:подписывать{}, // подписывать в присутствии понятых rus_verbs:добывать{}, // добывать в разломе rus_verbs:скопиться{}, // скопиться в воротах rus_verbs:повстречать{}, // повстречать в бане rus_verbs:совпасть{}, // совпасть в упрощенном виде rus_verbs:разрываться{}, // разрываться в точке спайки rus_verbs:улавливать{}, // улавливать в датчике rus_verbs:повстречаться{}, // повстречаться в лифте rus_verbs:отразить{}, // отразить в отчете rus_verbs:пояснять{}, // пояснять в примечаниях rus_verbs:накормить{}, // накормить в столовке rus_verbs:поужинать{}, // поужинать в ресторане инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть в суде инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш }, rus_verbs:топить{}, // топить в молоке rus_verbs:освоить{}, // освоить в работе rus_verbs:зародиться{}, // зародиться в голове rus_verbs:отплыть{}, // отплыть в старой лодке rus_verbs:отстаивать{}, // отстаивать в суде rus_verbs:осуждать{}, // осуждать в своем выступлении rus_verbs:переговорить{}, // переговорить в перерыве rus_verbs:разгораться{}, // разгораться в сердце rus_verbs:укрыть{}, // укрыть в шалаше rus_verbs:томиться{}, // томиться в застенках rus_verbs:клубиться{}, // клубиться в воздухе rus_verbs:сжигать{}, // сжигать в топке rus_verbs:позавтракать{}, // позавтракать в кафешке rus_verbs:функционировать{}, // функционировать в лабораторных условиях rus_verbs:смять{}, // смять в руке rus_verbs:разместить{}, // разместить в интернете rus_verbs:пронести{}, // пронести в потайном кармане rus_verbs:руководствоваться{}, // руководствоваться в работе rus_verbs:нашарить{}, // нашарить в потемках rus_verbs:закрутить{}, // закрутить в вихре rus_verbs:просматриваться{}, // просматриваться в дальней перспективе rus_verbs:распознать{}, // распознать в незнакомце rus_verbs:повеситься{}, // повеситься в камере rus_verbs:обшарить{}, // обшарить в поисках наркотиков rus_verbs:наполняться{}, // наполняется в карьере rus_verbs:засвистеть{}, // засвистеть в воздухе rus_verbs:процветать{}, // процветать в мягком климате rus_verbs:шуршать{}, // шуршать в простенке rus_verbs:подхватывать{}, // подхватывать в полете инфинитив:роиться{}, глагол:роиться{}, // роиться в воздухе прилагательное:роившийся{}, прилагательное:роящийся{}, // деепричастие:роясь{ aux stress="ро^ясь" }, rus_verbs:преобладать{}, // преобладать в тексте rus_verbs:посветлеть{}, // посветлеть в лице rus_verbs:игнорировать{}, // игнорировать в рекомендациях rus_verbs:обсуждаться{}, // обсуждаться в кулуарах rus_verbs:отказывать{}, // отказывать в визе rus_verbs:ощупывать{}, // ощупывать в кармане rus_verbs:разливаться{}, // разливаться в цеху rus_verbs:расписаться{}, // расписаться в получении rus_verbs:учинить{}, // учинить в казарме rus_verbs:плестись{}, // плестись в хвосте rus_verbs:объявляться{}, // объявляться в группе rus_verbs:повышаться{}, // повышаться в первой части rus_verbs:напрягать{}, // напрягать в паху rus_verbs:разрабатывать{}, // разрабатывать в студии rus_verbs:хлопотать{}, // хлопотать в мэрии rus_verbs:прерывать{}, // прерывать в самом начале rus_verbs:каяться{}, // каяться в грехах rus_verbs:освоиться{}, // освоиться в кабине rus_verbs:подплыть{}, // подплыть в лодке rus_verbs:замигать{}, // замигать в темноте rus_verbs:оскорблять{}, // оскорблять в выступлении rus_verbs:торжествовать{}, // торжествовать в душе rus_verbs:поправлять{}, // поправлять в прологе rus_verbs:угадывать{}, // угадывать в размытом изображении rus_verbs:потоптаться{}, // потоптаться в прихожей rus_verbs:переправиться{}, // переправиться в лодочке rus_verbs:увериться{}, // увериться в невиновности rus_verbs:забрезжить{}, // забрезжить в конце тоннеля rus_verbs:утвердиться{}, // утвердиться во мнении rus_verbs:завывать{}, // завывать в трубе rus_verbs:заварить{}, // заварить в заварнике rus_verbs:скомкать{}, // скомкать в руке rus_verbs:перемещаться{}, // перемещаться в капсуле инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться в первом поле rus_verbs:праздновать{}, // праздновать в баре rus_verbs:мигать{}, // мигать в темноте rus_verbs:обучить{}, // обучить в мастерской rus_verbs:орудовать{}, // орудовать в кладовке rus_verbs:упорствовать{}, // упорствовать в заблуждении rus_verbs:переминаться{}, // переминаться в прихожей rus_verbs:подрасти{}, // подрасти в теплице rus_verbs:предписываться{}, // предписываться в законе rus_verbs:приписать{}, // приписать в конце rus_verbs:задаваться{}, // задаваться в своей статье rus_verbs:чинить{}, // чинить в домашних условиях rus_verbs:раздеваться{}, // раздеваться в пляжной кабинке rus_verbs:пообедать{}, // пообедать в ресторанчике rus_verbs:жрать{}, // жрать в чуланчике rus_verbs:исполняться{}, // исполняться в антракте rus_verbs:гнить{}, // гнить в тюрьме rus_verbs:глодать{}, // глодать в конуре rus_verbs:прослушать{}, // прослушать в дороге rus_verbs:истратить{}, // истратить в кабаке rus_verbs:стареть{}, // стареть в одиночестве rus_verbs:разжечь{}, // разжечь в сердце rus_verbs:совещаться{}, // совещаться в кабинете rus_verbs:покачивать{}, // покачивать в кроватке rus_verbs:отсидеть{}, // отсидеть в одиночке rus_verbs:формировать{}, // формировать в умах rus_verbs:захрапеть{}, // захрапеть во сне rus_verbs:петься{}, // петься в хоре rus_verbs:объехать{}, // объехать в автобусе rus_verbs:поселить{}, // поселить в гостинице rus_verbs:предаться{}, // предаться в книге rus_verbs:заворочаться{}, // заворочаться во сне rus_verbs:напрятать{}, // напрятать в карманах rus_verbs:очухаться{}, // очухаться в незнакомом месте rus_verbs:ограничивать{}, // ограничивать в движениях rus_verbs:завертеть{}, // завертеть в руках rus_verbs:печатать{}, // печатать в редакторе rus_verbs:теплиться{}, // теплиться в сердце rus_verbs:увязнуть{}, // увязнуть в зыбучем песке rus_verbs:усмотреть{}, // усмотреть в обращении rus_verbs:отыскаться{}, // отыскаться в запасах rus_verbs:потушить{}, // потушить в горле огонь rus_verbs:поубавиться{}, // поубавиться в размере rus_verbs:зафиксировать{}, // зафиксировать в постоянной памяти rus_verbs:смыть{}, // смыть в ванной rus_verbs:заместить{}, // заместить в кресле rus_verbs:угасать{}, // угасать в одиночестве rus_verbs:сразить{}, // сразить в споре rus_verbs:фигурировать{}, // фигурировать в бюллетене rus_verbs:расплываться{}, // расплываться в глазах rus_verbs:сосчитать{}, // сосчитать в уме rus_verbs:сгуститься{}, // сгуститься в воздухе rus_verbs:цитировать{}, // цитировать в своей статье rus_verbs:помяться{}, // помяться в давке rus_verbs:затрагивать{}, // затрагивать в процессе выполнения rus_verbs:обтереть{}, // обтереть в гараже rus_verbs:подстрелить{}, // подстрелить в пойме реки rus_verbs:растереть{}, // растереть в руке rus_verbs:подавлять{}, // подавлять в зародыше rus_verbs:смешиваться{}, // смешиваться в чане инфинитив:вычитать{ вид:соверш }, глагол:вычитать{ вид:соверш }, // вычитать в книжечке rus_verbs:сократиться{}, // сократиться в обхвате rus_verbs:занервничать{}, // занервничать в кабинете rus_verbs:соприкоснуться{}, // соприкоснуться в полете rus_verbs:обозначить{}, // обозначить в объявлении rus_verbs:обучаться{}, // обучаться в училище rus_verbs:снизиться{}, // снизиться в нижних слоях атмосферы rus_verbs:лелеять{}, // лелеять в сердце rus_verbs:поддерживаться{}, // поддерживаться в суде rus_verbs:уплыть{}, // уплыть в лодочке rus_verbs:резвиться{}, // резвиться в саду rus_verbs:поерзать{}, // поерзать в гамаке rus_verbs:оплатить{}, // оплатить в ресторане rus_verbs:похвастаться{}, // похвастаться в компании rus_verbs:знакомиться{}, // знакомиться в классе rus_verbs:приплыть{}, // приплыть в подводной лодке rus_verbs:зажигать{}, // зажигать в классе rus_verbs:смыслить{}, // смыслить в математике rus_verbs:закопать{}, // закопать в огороде rus_verbs:порхать{}, // порхать в зарослях rus_verbs:потонуть{}, // потонуть в бумажках rus_verbs:стирать{}, // стирать в холодной воде rus_verbs:подстерегать{}, // подстерегать в придорожных кустах rus_verbs:погулять{}, // погулять в парке rus_verbs:предвкушать{}, // предвкушать в воображении rus_verbs:ошеломить{}, // ошеломить в бою rus_verbs:удостовериться{}, // удостовериться в безопасности rus_verbs:огласить{}, // огласить в заключительной части rus_verbs:разбогатеть{}, // разбогатеть в деревне rus_verbs:грохотать{}, // грохотать в мастерской rus_verbs:реализоваться{}, // реализоваться в должности rus_verbs:красть{}, // красть в магазине rus_verbs:нарваться{}, // нарваться в коридоре rus_verbs:застывать{}, // застывать в неудобной позе rus_verbs:толкаться{}, // толкаться в тесной комнате rus_verbs:извлекать{}, // извлекать в аппарате rus_verbs:обжигать{}, // обжигать в печи rus_verbs:запечатлеть{}, // запечатлеть в кинохронике rus_verbs:тренироваться{}, // тренироваться в зале rus_verbs:поспорить{}, // поспорить в кабинете rus_verbs:рыскать{}, // рыскать в лесу rus_verbs:надрываться{}, // надрываться в шахте rus_verbs:сняться{}, // сняться в фильме rus_verbs:закружить{}, // закружить в танце rus_verbs:затонуть{}, // затонуть в порту rus_verbs:побыть{}, // побыть в гостях rus_verbs:почистить{}, // почистить в носу rus_verbs:сгорбиться{}, // сгорбиться в тесной конуре rus_verbs:подслушивать{}, // подслушивать в классе rus_verbs:сгорать{}, // сгорать в танке rus_verbs:разочароваться{}, // разочароваться в артисте инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать в кустиках rus_verbs:мять{}, // мять в руках rus_verbs:подраться{}, // подраться в классе rus_verbs:замести{}, // замести в прихожей rus_verbs:откладываться{}, // откладываться в печени rus_verbs:обозначаться{}, // обозначаться в перечне rus_verbs:просиживать{}, // просиживать в интернете rus_verbs:соприкасаться{}, // соприкасаться в точке rus_verbs:начертить{}, // начертить в тетрадке rus_verbs:уменьшать{}, // уменьшать в поперечнике rus_verbs:тормозить{}, // тормозить в облаке rus_verbs:затевать{}, // затевать в лаборатории rus_verbs:затопить{}, // затопить в бухте rus_verbs:задерживать{}, // задерживать в лифте rus_verbs:прогуляться{}, // прогуляться в лесу rus_verbs:прорубить{}, // прорубить во льду rus_verbs:очищать{}, // очищать в кислоте rus_verbs:полулежать{}, // полулежать в гамаке rus_verbs:исправить{}, // исправить в задании rus_verbs:предусматриваться{}, // предусматриваться в постановке задачи rus_verbs:замучить{}, // замучить в плену rus_verbs:разрушаться{}, // разрушаться в верхней части rus_verbs:ерзать{}, // ерзать в кресле rus_verbs:покопаться{}, // покопаться в залежах rus_verbs:раскаяться{}, // раскаяться в содеянном rus_verbs:пробежаться{}, // пробежаться в парке rus_verbs:полежать{}, // полежать в гамаке rus_verbs:позаимствовать{}, // позаимствовать в книге rus_verbs:снижать{}, // снижать в несколько раз rus_verbs:черпать{}, // черпать в поэзии rus_verbs:заверять{}, // заверять в своей искренности rus_verbs:проглядеть{}, // проглядеть в сумерках rus_verbs:припарковать{}, // припарковать во дворе rus_verbs:сверлить{}, // сверлить в стене rus_verbs:здороваться{}, // здороваться в аудитории rus_verbs:рожать{}, // рожать в воде rus_verbs:нацарапать{}, // нацарапать в тетрадке rus_verbs:затопать{}, // затопать в коридоре rus_verbs:прописать{}, // прописать в правилах rus_verbs:сориентироваться{}, // сориентироваться в обстоятельствах rus_verbs:снизить{}, // снизить в несколько раз rus_verbs:заблуждаться{}, // заблуждаться в своей теории rus_verbs:откопать{}, // откопать в отвалах rus_verbs:смастерить{}, // смастерить в лаборатории rus_verbs:замедлиться{}, // замедлиться в парафине rus_verbs:избивать{}, // избивать в участке rus_verbs:мыться{}, // мыться в бане rus_verbs:сварить{}, // сварить в кастрюльке rus_verbs:раскопать{}, // раскопать в снегу rus_verbs:крепиться{}, // крепиться в держателе rus_verbs:дробить{}, // дробить в мельнице rus_verbs:попить{}, // попить в ресторанчике rus_verbs:затронуть{}, // затронуть в душе rus_verbs:лязгнуть{}, // лязгнуть в тишине rus_verbs:заправлять{}, // заправлять в полете rus_verbs:размножаться{}, // размножаться в неволе rus_verbs:потопить{}, // потопить в Тихом Океане rus_verbs:кушать{}, // кушать в столовой rus_verbs:замолкать{}, // замолкать в замешательстве rus_verbs:измеряться{}, // измеряться в дюймах rus_verbs:сбываться{}, // сбываться в мечтах rus_verbs:задернуть{}, // задернуть в комнате rus_verbs:затихать{}, // затихать в темноте rus_verbs:прослеживаться{}, // прослеживается в журнале rus_verbs:прерываться{}, // прерывается в начале rus_verbs:изображаться{}, // изображается в любых фильмах rus_verbs:фиксировать{}, // фиксировать в данной точке rus_verbs:ослаблять{}, // ослаблять в поясе rus_verbs:зреть{}, // зреть в теплице rus_verbs:зеленеть{}, // зеленеть в огороде rus_verbs:критиковать{}, // критиковать в статье rus_verbs:облететь{}, // облететь в частном вертолете rus_verbs:разбросать{}, // разбросать в комнате rus_verbs:заразиться{}, // заразиться в людном месте rus_verbs:рассеять{}, // рассеять в бою rus_verbs:печься{}, // печься в духовке rus_verbs:поспать{}, // поспать в палатке rus_verbs:заступиться{}, // заступиться в драке rus_verbs:сплетаться{}, // сплетаться в середине rus_verbs:поместиться{}, // поместиться в мешке rus_verbs:спереть{}, // спереть в лавке // инфинитив:ликвидировать{ вид:несоверш }, глагол:ликвидировать{ вид:несоверш }, // ликвидировать в пригороде // инфинитив:ликвидировать{ вид:соверш }, глагол:ликвидировать{ вид:соверш }, rus_verbs:проваляться{}, // проваляться в постели rus_verbs:лечиться{}, // лечиться в стационаре rus_verbs:определиться{}, // определиться в честном бою rus_verbs:обработать{}, // обработать в растворе rus_verbs:пробивать{}, // пробивать в стене rus_verbs:перемешаться{}, // перемешаться в чане rus_verbs:чесать{}, // чесать в паху rus_verbs:пролечь{}, // пролечь в пустынной местности rus_verbs:скитаться{}, // скитаться в дальних странах rus_verbs:затрудняться{}, // затрудняться в выборе rus_verbs:отряхнуться{}, // отряхнуться в коридоре rus_verbs:разыгрываться{}, // разыгрываться в лотерее rus_verbs:помолиться{}, // помолиться в церкви rus_verbs:предписывать{}, // предписывать в рецепте rus_verbs:порваться{}, // порваться в слабом месте rus_verbs:греться{}, // греться в здании rus_verbs:опровергать{}, // опровергать в своем выступлении rus_verbs:помянуть{}, // помянуть в своем выступлении rus_verbs:допросить{}, // допросить в прокуратуре rus_verbs:материализоваться{}, // материализоваться в соседнем здании rus_verbs:рассеиваться{}, // рассеиваться в воздухе rus_verbs:перевозить{}, // перевозить в вагоне rus_verbs:отбывать{}, // отбывать в тюрьме rus_verbs:попахивать{}, // попахивать в отхожем месте rus_verbs:перечислять{}, // перечислять в заключении rus_verbs:зарождаться{}, // зарождаться в дебрях rus_verbs:предъявлять{}, // предъявлять в своем письме rus_verbs:распространять{}, // распространять в сети rus_verbs:пировать{}, // пировать в соседнем селе rus_verbs:начертать{}, // начертать в летописи rus_verbs:расцветать{}, // расцветать в подходящих условиях rus_verbs:царствовать{}, // царствовать в южной части материка rus_verbs:накопить{}, // накопить в буфере rus_verbs:закрутиться{}, // закрутиться в рутине rus_verbs:отработать{}, // отработать в забое rus_verbs:обокрасть{}, // обокрасть в автобусе rus_verbs:прокладывать{}, // прокладывать в снегу rus_verbs:ковырять{}, // ковырять в носу rus_verbs:копить{}, // копить в очереди rus_verbs:полечь{}, // полечь в степях rus_verbs:щебетать{}, // щебетать в кустиках rus_verbs:подчеркиваться{}, // подчеркиваться в сообщении rus_verbs:посеять{}, // посеять в огороде rus_verbs:разъезжать{}, // разъезжать в кабриолете rus_verbs:замечаться{}, // замечаться в лесу rus_verbs:просчитать{}, // просчитать в уме rus_verbs:маяться{}, // маяться в командировке rus_verbs:выхватывать{}, // выхватывать в тексте rus_verbs:креститься{}, // креститься в деревенской часовне rus_verbs:обрабатывать{}, // обрабатывать в растворе кислоты rus_verbs:настигать{}, // настигать в огороде rus_verbs:разгуливать{}, // разгуливать в роще rus_verbs:насиловать{}, // насиловать в квартире rus_verbs:побороть{}, // побороть в себе rus_verbs:учитывать{}, // учитывать в расчетах rus_verbs:искажать{}, // искажать в заметке rus_verbs:пропить{}, // пропить в кабаке rus_verbs:катать{}, // катать в лодочке rus_verbs:припрятать{}, // припрятать в кармашке rus_verbs:запаниковать{}, // запаниковать в бою rus_verbs:рассыпать{}, // рассыпать в траве rus_verbs:застревать{}, // застревать в ограде rus_verbs:зажигаться{}, // зажигаться в сумерках rus_verbs:жарить{}, // жарить в масле rus_verbs:накапливаться{}, // накапливаться в костях rus_verbs:распуститься{}, // распуститься в горшке rus_verbs:проголосовать{}, // проголосовать в передвижном пункте rus_verbs:странствовать{}, // странствовать в автомобиле rus_verbs:осматриваться{}, // осматриваться в хоромах rus_verbs:разворачивать{}, // разворачивать в спортзале rus_verbs:заскучать{}, // заскучать в самолете rus_verbs:напутать{}, // напутать в расчете rus_verbs:перекусить{}, // перекусить в столовой rus_verbs:спасаться{}, // спасаться в автономной капсуле rus_verbs:посовещаться{}, // посовещаться в комнате rus_verbs:доказываться{}, // доказываться в статье rus_verbs:познаваться{}, // познаваться в беде rus_verbs:загрустить{}, // загрустить в одиночестве rus_verbs:оживить{}, // оживить в памяти rus_verbs:переворачиваться{}, // переворачиваться в гробу rus_verbs:заприметить{}, // заприметить в лесу rus_verbs:отравиться{}, // отравиться в забегаловке rus_verbs:продержать{}, // продержать в клетке rus_verbs:выявить{}, // выявить в костях rus_verbs:заседать{}, // заседать в совете rus_verbs:расплачиваться{}, // расплачиваться в первой кассе rus_verbs:проломить{}, // проломить в двери rus_verbs:подражать{}, // подражать в мелочах rus_verbs:подсчитывать{}, // подсчитывать в уме rus_verbs:опережать{}, // опережать во всем rus_verbs:сформироваться{}, // сформироваться в облаке rus_verbs:укрепиться{}, // укрепиться в мнении rus_verbs:отстоять{}, // отстоять в очереди rus_verbs:развертываться{}, // развертываться в месте испытания rus_verbs:замерзать{}, // замерзать во льду rus_verbs:утопать{}, // утопать в снегу rus_verbs:раскаиваться{}, // раскаиваться в содеянном rus_verbs:организовывать{}, // организовывать в пионерлагере rus_verbs:перевестись{}, // перевестись в наших краях rus_verbs:смешивать{}, // смешивать в блендере rus_verbs:ютиться{}, // ютиться в тесной каморке rus_verbs:прождать{}, // прождать в аудитории rus_verbs:подыскивать{}, // подыскивать в женском общежитии rus_verbs:замочить{}, // замочить в сортире rus_verbs:мерзнуть{}, // мерзнуть в тонкой курточке rus_verbs:растирать{}, // растирать в ступке rus_verbs:замедлять{}, // замедлять в парафине rus_verbs:переспать{}, // переспать в палатке rus_verbs:рассекать{}, // рассекать в кабриолете rus_verbs:отыскивать{}, // отыскивать в залежах rus_verbs:опровергнуть{}, // опровергнуть в своем выступлении rus_verbs:дрыхнуть{}, // дрыхнуть в гамаке rus_verbs:укрываться{}, // укрываться в землянке rus_verbs:запечься{}, // запечься в золе rus_verbs:догорать{}, // догорать в темноте rus_verbs:застилать{}, // застилать в коридоре rus_verbs:сыскаться{}, // сыскаться в деревне rus_verbs:переделать{}, // переделать в мастерской rus_verbs:разъяснять{}, // разъяснять в своей лекции rus_verbs:селиться{}, // селиться в центре rus_verbs:оплачивать{}, // оплачивать в магазине rus_verbs:переворачивать{}, // переворачивать в закрытой банке rus_verbs:упражняться{}, // упражняться в остроумии rus_verbs:пометить{}, // пометить в списке rus_verbs:припомниться{}, // припомниться в завещании rus_verbs:приютить{}, // приютить в амбаре rus_verbs:натерпеться{}, // натерпеться в темнице rus_verbs:затеваться{}, // затеваться в клубе rus_verbs:уплывать{}, // уплывать в лодке rus_verbs:скиснуть{}, // скиснуть в бидоне rus_verbs:заколоть{}, // заколоть в боку rus_verbs:замерцать{}, // замерцать в темноте rus_verbs:фиксироваться{}, // фиксироваться в протоколе rus_verbs:запираться{}, // запираться в комнате rus_verbs:съезжаться{}, // съезжаться в каретах rus_verbs:толочься{}, // толочься в ступе rus_verbs:потанцевать{}, // потанцевать в клубе rus_verbs:побродить{}, // побродить в парке rus_verbs:назревать{}, // назревать в коллективе rus_verbs:дохнуть{}, // дохнуть в питомнике rus_verbs:крестить{}, // крестить в деревенской церквушке rus_verbs:рассчитаться{}, // рассчитаться в банке rus_verbs:припарковаться{}, // припарковаться во дворе rus_verbs:отхватить{}, // отхватить в магазинчике rus_verbs:остывать{}, // остывать в холодильнике rus_verbs:составляться{}, // составляться в атмосфере тайны rus_verbs:переваривать{}, // переваривать в тишине rus_verbs:хвастать{}, // хвастать в казино rus_verbs:отрабатывать{}, // отрабатывать в теплице rus_verbs:разлечься{}, // разлечься в кровати rus_verbs:прокручивать{}, // прокручивать в голове rus_verbs:очертить{}, // очертить в воздухе rus_verbs:сконфузиться{}, // сконфузиться в окружении незнакомых людей rus_verbs:выявлять{}, // выявлять в боевых условиях rus_verbs:караулить{}, // караулить в лифте rus_verbs:расставлять{}, // расставлять в бойницах rus_verbs:прокрутить{}, // прокрутить в голове rus_verbs:пересказывать{}, // пересказывать в первой главе rus_verbs:задавить{}, // задавить в зародыше rus_verbs:хозяйничать{}, // хозяйничать в холодильнике rus_verbs:хвалиться{}, // хвалиться в детском садике rus_verbs:оперировать{}, // оперировать в полевом госпитале rus_verbs:формулировать{}, // формулировать в следующей главе rus_verbs:застигнуть{}, // застигнуть в неприглядном виде rus_verbs:замурлыкать{}, // замурлыкать в тепле rus_verbs:поддакивать{}, // поддакивать в споре rus_verbs:прочертить{}, // прочертить в воздухе rus_verbs:отменять{}, // отменять в городе коменданский час rus_verbs:колдовать{}, // колдовать в лаборатории rus_verbs:отвозить{}, // отвозить в машине rus_verbs:трахать{}, // трахать в гамаке rus_verbs:повозиться{}, // повозиться в мешке rus_verbs:ремонтировать{}, // ремонтировать в центре rus_verbs:робеть{}, // робеть в гостях rus_verbs:перепробовать{}, // перепробовать в деле инфинитив:реализовать{ вид:соверш }, инфинитив:реализовать{ вид:несоверш }, // реализовать в новой версии глагол:реализовать{ вид:соверш }, глагол:реализовать{ вид:несоверш }, rus_verbs:покаяться{}, // покаяться в церкви rus_verbs:попрыгать{}, // попрыгать в бассейне rus_verbs:умалчивать{}, // умалчивать в своем докладе rus_verbs:ковыряться{}, // ковыряться в старой технике rus_verbs:расписывать{}, // расписывать в деталях rus_verbs:вязнуть{}, // вязнуть в песке rus_verbs:погрязнуть{}, // погрязнуть в скандалах rus_verbs:корениться{}, // корениться в неспособности выполнить поставленную задачу rus_verbs:зажимать{}, // зажимать в углу rus_verbs:стискивать{}, // стискивать в ладонях rus_verbs:практиковаться{}, // практиковаться в приготовлении соуса rus_verbs:израсходовать{}, // израсходовать в полете rus_verbs:клокотать{}, // клокотать в жерле rus_verbs:обвиняться{}, // обвиняться в растрате rus_verbs:уединиться{}, // уединиться в кладовке rus_verbs:подохнуть{}, // подохнуть в болоте rus_verbs:кипятиться{}, // кипятиться в чайнике rus_verbs:уродиться{}, // уродиться в лесу rus_verbs:продолжиться{}, // продолжиться в баре rus_verbs:расшифровать{}, // расшифровать в специальном устройстве rus_verbs:посапывать{}, // посапывать в кровати rus_verbs:скрючиться{}, // скрючиться в мешке rus_verbs:лютовать{}, // лютовать в отдаленных селах rus_verbs:расписать{}, // расписать в статье rus_verbs:публиковаться{}, // публиковаться в научном журнале rus_verbs:зарегистрировать{}, // зарегистрировать в комитете rus_verbs:прожечь{}, // прожечь в листе rus_verbs:переждать{}, // переждать в окопе rus_verbs:публиковать{}, // публиковать в журнале rus_verbs:морщить{}, // морщить в уголках глаз rus_verbs:спиться{}, // спиться в одиночестве rus_verbs:изведать{}, // изведать в гареме rus_verbs:обмануться{}, // обмануться в ожиданиях rus_verbs:сочетать{}, // сочетать в себе rus_verbs:подрабатывать{}, // подрабатывать в магазине rus_verbs:репетировать{}, // репетировать в студии rus_verbs:рябить{}, // рябить в глазах rus_verbs:намочить{}, // намочить в луже rus_verbs:скатать{}, // скатать в руке rus_verbs:одевать{}, // одевать в магазине rus_verbs:испечь{}, // испечь в духовке rus_verbs:сбрить{}, // сбрить в подмышках rus_verbs:зажужжать{}, // зажужжать в ухе rus_verbs:сберечь{}, // сберечь в тайном месте rus_verbs:согреться{}, // согреться в хижине инфинитив:дебютировать{ вид:несоверш }, инфинитив:дебютировать{ вид:соверш }, // дебютировать в спектакле глагол:дебютировать{ вид:несоверш }, глагол:дебютировать{ вид:соверш }, rus_verbs:переплыть{}, // переплыть в лодочке rus_verbs:передохнуть{}, // передохнуть в тени rus_verbs:отсвечивать{}, // отсвечивать в зеркалах rus_verbs:переправляться{}, // переправляться в лодках rus_verbs:накупить{}, // накупить в магазине rus_verbs:проторчать{}, // проторчать в очереди rus_verbs:проскальзывать{}, // проскальзывать в сообщениях rus_verbs:застукать{}, // застукать в солярии rus_verbs:наесть{}, // наесть в отпуске rus_verbs:подвизаться{}, // подвизаться в новом деле rus_verbs:вычистить{}, // вычистить в саду rus_verbs:кормиться{}, // кормиться в лесу rus_verbs:покурить{}, // покурить в саду rus_verbs:понизиться{}, // понизиться в ранге rus_verbs:зимовать{}, // зимовать в избушке rus_verbs:проверяться{}, // проверяться в службе безопасности rus_verbs:подпирать{}, // подпирать в первом забое rus_verbs:кувыркаться{}, // кувыркаться в постели rus_verbs:похрапывать{}, // похрапывать в постели rus_verbs:завязнуть{}, // завязнуть в песке rus_verbs:трактовать{}, // трактовать в исследовательской статье rus_verbs:замедляться{}, // замедляться в тяжелой воде rus_verbs:шастать{}, // шастать в здании rus_verbs:заночевать{}, // заночевать в пути rus_verbs:наметиться{}, // наметиться в исследованиях рака rus_verbs:освежить{}, // освежить в памяти rus_verbs:оспаривать{}, // оспаривать в суде rus_verbs:умещаться{}, // умещаться в ячейке rus_verbs:искупить{}, // искупить в бою rus_verbs:отсиживаться{}, // отсиживаться в тылу rus_verbs:мчать{}, // мчать в кабриолете rus_verbs:обличать{}, // обличать в своем выступлении rus_verbs:сгнить{}, // сгнить в тюряге rus_verbs:опробовать{}, // опробовать в деле rus_verbs:тренировать{}, // тренировать в зале rus_verbs:прославить{}, // прославить в академии rus_verbs:учитываться{}, // учитываться в дипломной работе rus_verbs:повеселиться{}, // повеселиться в лагере rus_verbs:поумнеть{}, // поумнеть в карцере rus_verbs:перестрелять{}, // перестрелять в воздухе rus_verbs:проведать{}, // проведать в больнице rus_verbs:измучиться{}, // измучиться в деревне rus_verbs:прощупать{}, // прощупать в глубине rus_verbs:изготовлять{}, // изготовлять в сарае rus_verbs:свирепствовать{}, // свирепствовать в популяции rus_verbs:иссякать{}, // иссякать в источнике rus_verbs:гнездиться{}, // гнездиться в дупле rus_verbs:разогнаться{}, // разогнаться в спортивной машине rus_verbs:опознавать{}, // опознавать в неизвестном rus_verbs:засвидетельствовать{}, // засвидетельствовать в суде rus_verbs:сконцентрировать{}, // сконцентрировать в своих руках rus_verbs:редактировать{}, // редактировать в редакторе rus_verbs:покупаться{}, // покупаться в магазине rus_verbs:промышлять{}, // промышлять в роще rus_verbs:растягиваться{}, // растягиваться в коридоре rus_verbs:приобретаться{}, // приобретаться в антикварных лавках инфинитив:подрезать{ вид:несоверш }, инфинитив:подрезать{ вид:соверш }, // подрезать в воде глагол:подрезать{ вид:несоверш }, глагол:подрезать{ вид:соверш }, rus_verbs:запечатлеться{}, // запечатлеться в мозгу rus_verbs:укрывать{}, // укрывать в подвале rus_verbs:закрепиться{}, // закрепиться в первой башне rus_verbs:освежать{}, // освежать в памяти rus_verbs:громыхать{}, // громыхать в ванной инфинитив:подвигаться{ вид:соверш }, инфинитив:подвигаться{ вид:несоверш }, // подвигаться в кровати глагол:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:несоверш }, rus_verbs:добываться{}, // добываться в шахтах rus_verbs:растворить{}, // растворить в кислоте rus_verbs:приплясывать{}, // приплясывать в гримерке rus_verbs:доживать{}, // доживать в доме престарелых rus_verbs:отпраздновать{}, // отпраздновать в ресторане rus_verbs:сотрясаться{}, // сотрясаться в конвульсиях rus_verbs:помыть{}, // помыть в проточной воде инфинитив:увязать{ вид:несоверш }, инфинитив:увязать{ вид:соверш }, // увязать в песке глагол:увязать{ вид:несоверш }, глагол:увязать{ вид:соверш }, прилагательное:увязавший{ вид:несоверш }, rus_verbs:наличествовать{}, // наличествовать в запаснике rus_verbs:нащупывать{}, // нащупывать в кармане rus_verbs:повествоваться{}, // повествоваться в рассказе rus_verbs:отремонтировать{}, // отремонтировать в техцентре rus_verbs:покалывать{}, // покалывать в правом боку rus_verbs:сиживать{}, // сиживать в саду rus_verbs:разрабатываться{}, // разрабатываться в секретных лабораториях rus_verbs:укрепляться{}, // укрепляться в мнении rus_verbs:разниться{}, // разниться во взглядах rus_verbs:сполоснуть{}, // сполоснуть в водичке rus_verbs:скупать{}, // скупать в магазине rus_verbs:почесывать{}, // почесывать в паху rus_verbs:оформлять{}, // оформлять в конторе rus_verbs:распускаться{}, // распускаться в садах rus_verbs:зарябить{}, // зарябить в глазах rus_verbs:загореть{}, // загореть в Испании rus_verbs:очищаться{}, // очищаться в баке rus_verbs:остудить{}, // остудить в холодной воде rus_verbs:разбомбить{}, // разбомбить в горах rus_verbs:издохнуть{}, // издохнуть в бедности rus_verbs:проехаться{}, // проехаться в новой машине rus_verbs:задействовать{}, // задействовать в анализе rus_verbs:произрастать{}, // произрастать в степи rus_verbs:разуться{}, // разуться в прихожей rus_verbs:сооружать{}, // сооружать в огороде rus_verbs:зачитывать{}, // зачитывать в суде rus_verbs:состязаться{}, // состязаться в остроумии rus_verbs:ополоснуть{}, // ополоснуть в молоке rus_verbs:уместиться{}, // уместиться в кармане rus_verbs:совершенствоваться{}, // совершенствоваться в управлении мотоциклом rus_verbs:стираться{}, // стираться в стиральной машине rus_verbs:искупаться{}, // искупаться в прохладной реке rus_verbs:курировать{}, // курировать в правительстве rus_verbs:закупить{}, // закупить в магазине rus_verbs:плодиться{}, // плодиться в подходящих условиях rus_verbs:горланить{}, // горланить в парке rus_verbs:першить{}, // першить в горле rus_verbs:пригрезиться{}, // пригрезиться во сне rus_verbs:исправлять{}, // исправлять в тетрадке rus_verbs:расслабляться{}, // расслабляться в гамаке rus_verbs:скапливаться{}, // скапливаться в нижней части rus_verbs:сплетничать{}, // сплетничают в комнате rus_verbs:раздевать{}, // раздевать в кабинке rus_verbs:окопаться{}, // окопаться в лесу rus_verbs:загорать{}, // загорать в Испании rus_verbs:подпевать{}, // подпевать в церковном хоре rus_verbs:прожужжать{}, // прожужжать в динамике rus_verbs:изучаться{}, // изучаться в дикой природе rus_verbs:заклубиться{}, // заклубиться в воздухе rus_verbs:подметать{}, // подметать в зале rus_verbs:подозреваться{}, // подозреваться в совершении кражи rus_verbs:обогащать{}, // обогащать в специальном аппарате rus_verbs:издаться{}, // издаться в другом издательстве rus_verbs:справить{}, // справить в кустах нужду rus_verbs:помыться{}, // помыться в бане rus_verbs:проскакивать{}, // проскакивать в словах rus_verbs:попивать{}, // попивать в кафе чай rus_verbs:оформляться{}, // оформляться в регистратуре rus_verbs:чирикать{}, // чирикать в кустах rus_verbs:скупить{}, // скупить в магазинах rus_verbs:переночевать{}, // переночевать в гостинице rus_verbs:концентрироваться{}, // концентрироваться в пробирке rus_verbs:одичать{}, // одичать в лесу rus_verbs:ковырнуть{}, // ковырнуть в ухе rus_verbs:затеплиться{}, // затеплиться в глубине души rus_verbs:разгрести{}, // разгрести в задачах залежи rus_verbs:застопориться{}, // застопориться в начале списка rus_verbs:перечисляться{}, // перечисляться во введении rus_verbs:покататься{}, // покататься в парке аттракционов rus_verbs:изловить{}, // изловить в поле rus_verbs:прославлять{}, // прославлять в стихах rus_verbs:промочить{}, // промочить в луже rus_verbs:поделывать{}, // поделывать в отпуске rus_verbs:просуществовать{}, // просуществовать в первобытном состоянии rus_verbs:подстеречь{}, // подстеречь в подъезде rus_verbs:прикупить{}, // прикупить в магазине rus_verbs:перемешивать{}, // перемешивать в кастрюле rus_verbs:тискать{}, // тискать в углу rus_verbs:купать{}, // купать в теплой водичке rus_verbs:завариться{}, // завариться в стакане rus_verbs:притулиться{}, // притулиться в углу rus_verbs:пострелять{}, // пострелять в тире rus_verbs:навесить{}, // навесить в больнице инфинитив:изолировать{ вид:соверш }, инфинитив:изолировать{ вид:несоверш }, // изолировать в камере глагол:изолировать{ вид:соверш }, глагол:изолировать{ вид:несоверш }, rus_verbs:нежиться{}, // нежится в постельке rus_verbs:притомиться{}, // притомиться в школе rus_verbs:раздвоиться{}, // раздвоиться в глазах rus_verbs:навалить{}, // навалить в углу rus_verbs:замуровать{}, // замуровать в склепе rus_verbs:поселяться{}, // поселяться в кроне дуба rus_verbs:потягиваться{}, // потягиваться в кровати rus_verbs:укачать{}, // укачать в поезде rus_verbs:отлеживаться{}, // отлеживаться в гамаке rus_verbs:разменять{}, // разменять в кассе rus_verbs:прополоскать{}, // прополоскать в чистой теплой воде rus_verbs:ржаветь{}, // ржаветь в воде rus_verbs:уличить{}, // уличить в плагиате rus_verbs:мутиться{}, // мутиться в голове rus_verbs:растворять{}, // растворять в бензоле rus_verbs:двоиться{}, // двоиться в глазах rus_verbs:оговорить{}, // оговорить в договоре rus_verbs:подделать{}, // подделать в документе rus_verbs:зарегистрироваться{}, // зарегистрироваться в социальной сети rus_verbs:растолстеть{}, // растолстеть в талии rus_verbs:повоевать{}, // повоевать в городских условиях rus_verbs:прибраться{}, // гнушаться прибраться в хлеву rus_verbs:поглощаться{}, // поглощаться в металлической фольге rus_verbs:ухать{}, // ухать в лесу rus_verbs:подписываться{}, // подписываться в петиции rus_verbs:покатать{}, // покатать в машинке rus_verbs:излечиться{}, // излечиться в клинике rus_verbs:трепыхаться{}, // трепыхаться в мешке rus_verbs:кипятить{}, // кипятить в кастрюле rus_verbs:понастроить{}, // понастроить в прибрежной зоне rus_verbs:перебывать{}, // перебывать во всех европейских столицах rus_verbs:оглашать{}, // оглашать в итоговой части rus_verbs:преуспевать{}, // преуспевать в новом бизнесе rus_verbs:консультироваться{}, // консультироваться в техподдержке rus_verbs:накапливать{}, // накапливать в печени rus_verbs:перемешать{}, // перемешать в контейнере rus_verbs:наследить{}, // наследить в коридоре rus_verbs:выявиться{}, // выявиться в результе rus_verbs:забулькать{}, // забулькать в болоте rus_verbs:отваривать{}, // отваривать в молоке rus_verbs:запутываться{}, // запутываться в веревках rus_verbs:нагреться{}, // нагреться в микроволновой печке rus_verbs:рыбачить{}, // рыбачить в открытом море rus_verbs:укорениться{}, // укорениться в сознании широких народных масс rus_verbs:умывать{}, // умывать в тазике rus_verbs:защекотать{}, // защекотать в носу rus_verbs:заходиться{}, // заходиться в плаче инфинитив:искупать{ вид:соверш }, инфинитив:искупать{ вид:несоверш }, // искупать в прохладной водичке глагол:искупать{ вид:соверш }, глагол:искупать{ вид:несоверш }, деепричастие:искупав{}, деепричастие:искупая{}, rus_verbs:заморозить{}, // заморозить в холодильнике rus_verbs:закреплять{}, // закреплять в металлическом держателе rus_verbs:расхватать{}, // расхватать в магазине rus_verbs:истязать{}, // истязать в тюремном подвале rus_verbs:заржаветь{}, // заржаветь во влажной атмосфере rus_verbs:обжаривать{}, // обжаривать в подсолнечном масле rus_verbs:умереть{}, // Ты, подлый предатель, умрешь в нищете rus_verbs:подогреть{}, // подогрей в микроволновке rus_verbs:подогревать{}, rus_verbs:затянуть{}, // Кузнечики, сверчки, скрипачи и медведки затянули в траве свою трескучую музыку rus_verbs:проделать{}, // проделать в стене дыру инфинитив:жениться{ вид:соверш }, // жениться в Техасе инфинитив:жениться{ вид:несоверш }, глагол:жениться{ вид:соверш }, глагол:жениться{ вид:несоверш }, деепричастие:женившись{}, деепричастие:женясь{}, прилагательное:женатый{}, прилагательное:женившийся{вид:соверш}, прилагательное:женящийся{}, rus_verbs:всхрапнуть{}, // всхрапнуть во сне rus_verbs:всхрапывать{}, // всхрапывать во сне rus_verbs:ворочаться{}, // Собака ворочается во сне rus_verbs:воссоздаваться{}, // воссоздаваться в памяти rus_verbs:акклиматизироваться{}, // альпинисты готовятся акклиматизироваться в горах инфинитив:атаковать{ вид:несоверш }, // взвод был атакован в лесу инфинитив:атаковать{ вид:соверш }, глагол:атаковать{ вид:несоверш }, глагол:атаковать{ вид:соверш }, прилагательное:атакованный{}, прилагательное:атаковавший{}, прилагательное:атакующий{}, инфинитив:аккумулировать{вид:несоверш}, // энергия была аккумулирована в печени инфинитив:аккумулировать{вид:соверш}, глагол:аккумулировать{вид:несоверш}, глагол:аккумулировать{вид:соверш}, прилагательное:аккумулированный{}, прилагательное:аккумулирующий{}, //прилагательное:аккумулировавший{ вид:несоверш }, прилагательное:аккумулировавший{ вид:соверш }, rus_verbs:врисовывать{}, // врисовывать нового персонажа в анимацию rus_verbs:вырасти{}, // Он вырос в глазах коллег. rus_verbs:иметь{}, // Он всегда имел в резерве острое словцо. rus_verbs:убить{}, // убить в себе зверя инфинитив:абсорбироваться{ вид:соверш }, // жидкость абсорбируется в поглощающей ткани инфинитив:абсорбироваться{ вид:несоверш }, глагол:абсорбироваться{ вид:соверш }, глагол:абсорбироваться{ вид:несоверш }, rus_verbs:поставить{}, // поставить в углу rus_verbs:сжимать{}, // сжимать в кулаке rus_verbs:готовиться{}, // альпинисты готовятся акклиматизироваться в горах rus_verbs:аккумулироваться{}, // энергия аккумулируется в жировых отложениях инфинитив:активизироваться{ вид:несоверш }, // в горах активизировались повстанцы инфинитив:активизироваться{ вид:соверш }, глагол:активизироваться{ вид:несоверш }, глагол:активизироваться{ вид:соверш }, rus_verbs:апробировать{}, // пилот апробировал в ходе испытаний новый режим планера rus_verbs:арестовать{}, // наркодилер был арестован в помещении кафе rus_verbs:базировать{}, // установка будет базирована в лесу rus_verbs:барахтаться{}, // дети барахтались в воде rus_verbs:баррикадироваться{}, // преступники баррикадируются в помещении банка rus_verbs:барствовать{}, // Семен Семенович барствовал в своей деревне rus_verbs:бесчинствовать{}, // Боевики бесчинствовали в захваченном селе rus_verbs:блаженствовать{}, // Воробьи блаженствовали в кроне рябины rus_verbs:блуждать{}, // Туристы блуждали в лесу rus_verbs:брать{}, // Жена берет деньги в тумбочке rus_verbs:бродить{}, // парочки бродили в парке rus_verbs:обойти{}, // Бразилия обошла Россию в рейтинге rus_verbs:задержать{}, // Знаменитый советский фигурист задержан в США rus_verbs:бултыхаться{}, // Ноги бултыхаются в воде rus_verbs:вариться{}, // Курица варится в кастрюле rus_verbs:закончиться{}, // Эта рецессия закончилась в 2003 году rus_verbs:прокручиваться{}, // Ключ прокручивается в замке rus_verbs:прокрутиться{}, // Ключ трижды прокрутился в замке rus_verbs:храниться{}, // Настройки хранятся в текстовом файле rus_verbs:сохраняться{}, // Настройки сохраняются в текстовом файле rus_verbs:витать{}, // Мальчик витает в облаках rus_verbs:владычествовать{}, // Король владычествует в стране rus_verbs:властвовать{}, // Олигархи властвовали в стране rus_verbs:возбудить{}, // возбудить в сердце тоску rus_verbs:возбуждать{}, // возбуждать в сердце тоску rus_verbs:возвыситься{}, // возвыситься в глазах современников rus_verbs:возжечь{}, // возжечь в храме огонь rus_verbs:возжечься{}, // Огонь возжёгся в храме rus_verbs:возжигать{}, // возжигать в храме огонь rus_verbs:возжигаться{}, // Огонь возжигается в храме rus_verbs:вознамериваться{}, // вознамериваться уйти в монастырь rus_verbs:вознамериться{}, // вознамериться уйти в монастырь rus_verbs:возникать{}, // Новые идеи неожиданно возникают в колиной голове rus_verbs:возникнуть{}, // Новые идейки возникли в голове rus_verbs:возродиться{}, // возродиться в новом качестве rus_verbs:возрождать{}, // возрождать в новом качестве rus_verbs:возрождаться{}, // возрождаться в новом амплуа rus_verbs:ворошить{}, // ворошить в камине кочергой золу rus_verbs:воспевать{}, // Поэты воспевают героев в одах rus_verbs:воспеваться{}, // Герои воспеваются в одах поэтами rus_verbs:воспеть{}, // Поэты воспели в этой оде героев rus_verbs:воспретить{}, // воспретить в помещении азартные игры rus_verbs:восславить{}, // Поэты восславили в одах rus_verbs:восславлять{}, // Поэты восславляют в одах rus_verbs:восславляться{}, // Героя восславляются в одах rus_verbs:воссоздать{}, // воссоздает в памяти образ человека rus_verbs:воссоздавать{}, // воссоздать в памяти образ человека rus_verbs:воссоздаться{}, // воссоздаться в памяти rus_verbs:вскипятить{}, // вскипятить в чайнике воду rus_verbs:вскипятиться{}, // вскипятиться в чайнике rus_verbs:встретить{}, // встретить в классе старого приятеля rus_verbs:встретиться{}, // встретиться в классе rus_verbs:встречать{}, // встречать в лесу голодного медведя rus_verbs:встречаться{}, // встречаться в кафе rus_verbs:выбривать{}, // выбривать что-то в подмышках rus_verbs:выбрить{}, // выбрить что-то в паху rus_verbs:вывалять{}, // вывалять кого-то в грязи rus_verbs:вываляться{}, // вываляться в грязи rus_verbs:вываривать{}, // вываривать в молоке rus_verbs:вывариваться{}, // вывариваться в молоке rus_verbs:выварить{}, // выварить в молоке rus_verbs:вывариться{}, // вывариться в молоке rus_verbs:выгрызать{}, // выгрызать в сыре отверствие rus_verbs:выгрызть{}, // выгрызть в сыре отверстие rus_verbs:выгуливать{}, // выгуливать в парке собаку rus_verbs:выгулять{}, // выгулять в парке собаку rus_verbs:выдолбить{}, // выдолбить в стволе углубление rus_verbs:выжить{}, // выжить в пустыне rus_verbs:Выискать{}, // Выискать в программе ошибку rus_verbs:выискаться{}, // Ошибка выискалась в программе rus_verbs:выискивать{}, // выискивать в программе ошибку rus_verbs:выискиваться{}, // выискиваться в программе rus_verbs:выкраивать{}, // выкраивать в расписании время rus_verbs:выкраиваться{}, // выкраиваться в расписании инфинитив:выкупаться{aux stress="в^ыкупаться"}, // выкупаться в озере глагол:выкупаться{вид:соверш}, rus_verbs:выловить{}, // выловить в пруду rus_verbs:вымачивать{}, // вымачивать в молоке rus_verbs:вымачиваться{}, // вымачиваться в молоке rus_verbs:вынюхивать{}, // вынюхивать в траве следы rus_verbs:выпачкать{}, // выпачкать в смоле свою одежду rus_verbs:выпачкаться{}, // выпачкаться в грязи rus_verbs:вырастить{}, // вырастить в теплице ведро огурчиков rus_verbs:выращивать{}, // выращивать в теплице помидоры rus_verbs:выращиваться{}, // выращиваться в теплице rus_verbs:вырыть{}, // вырыть в земле глубокую яму rus_verbs:высадить{}, // высадить в пустынной местности rus_verbs:высадиться{}, // высадиться в пустынной местности rus_verbs:высаживать{}, // высаживать в пустыне rus_verbs:высверливать{}, // высверливать в доске отверствие rus_verbs:высверливаться{}, // высверливаться в стене rus_verbs:высверлить{}, // высверлить в стене отверствие rus_verbs:высверлиться{}, // высверлиться в стене rus_verbs:выскоблить{}, // выскоблить в столешнице канавку rus_verbs:высматривать{}, // высматривать в темноте rus_verbs:заметить{}, // заметить в помещении rus_verbs:оказаться{}, // оказаться в первых рядах rus_verbs:душить{}, // душить в объятиях rus_verbs:оставаться{}, // оставаться в классе rus_verbs:появиться{}, // впервые появиться в фильме rus_verbs:лежать{}, // лежать в футляре rus_verbs:раздаться{}, // раздаться в плечах rus_verbs:ждать{}, // ждать в здании вокзала rus_verbs:жить{}, // жить в трущобах rus_verbs:постелить{}, // постелить в прихожей rus_verbs:оказываться{}, // оказываться в неприятной ситуации rus_verbs:держать{}, // держать в голове rus_verbs:обнаружить{}, // обнаружить в себе способность rus_verbs:начинать{}, // начинать в лаборатории rus_verbs:рассказывать{}, // рассказывать в лицах rus_verbs:ожидать{}, // ожидать в помещении rus_verbs:продолжить{}, // продолжить в помещении rus_verbs:состоять{}, // состоять в группе rus_verbs:родиться{}, // родиться в рубашке rus_verbs:искать{}, // искать в кармане rus_verbs:иметься{}, // иметься в наличии rus_verbs:говориться{}, // говориться в среде панков rus_verbs:клясться{}, // клясться в верности rus_verbs:узнавать{}, // узнавать в нем своего сына rus_verbs:признаться{}, // признаться в ошибке rus_verbs:сомневаться{}, // сомневаться в искренности rus_verbs:толочь{}, // толочь в ступе rus_verbs:понадобиться{}, // понадобиться в суде rus_verbs:служить{}, // служить в пехоте rus_verbs:потолочь{}, // потолочь в ступе rus_verbs:появляться{}, // появляться в театре rus_verbs:сжать{}, // сжать в объятиях rus_verbs:действовать{}, // действовать в постановке rus_verbs:селить{}, // селить в гостинице rus_verbs:поймать{}, // поймать в лесу rus_verbs:увидать{}, // увидать в толпе rus_verbs:подождать{}, // подождать в кабинете rus_verbs:прочесть{}, // прочесть в глазах rus_verbs:тонуть{}, // тонуть в реке rus_verbs:ощущать{}, // ощущать в животе rus_verbs:ошибиться{}, // ошибиться в расчетах rus_verbs:отметить{}, // отметить в списке rus_verbs:показывать{}, // показывать в динамике rus_verbs:скрыться{}, // скрыться в траве rus_verbs:убедиться{}, // убедиться в корректности rus_verbs:прозвучать{}, // прозвучать в наушниках rus_verbs:разговаривать{}, // разговаривать в фойе rus_verbs:издать{}, // издать в России rus_verbs:прочитать{}, // прочитать в газете rus_verbs:попробовать{}, // попробовать в деле rus_verbs:замечать{}, // замечать в программе ошибку rus_verbs:нести{}, // нести в руках rus_verbs:пропасть{}, // пропасть в плену rus_verbs:носить{}, // носить в кармане rus_verbs:гореть{}, // гореть в аду rus_verbs:поправить{}, // поправить в программе rus_verbs:застыть{}, // застыть в неудобной позе rus_verbs:получать{}, // получать в кассе rus_verbs:потребоваться{}, // потребоваться в работе rus_verbs:спрятать{}, // спрятать в шкафу rus_verbs:учиться{}, // учиться в институте rus_verbs:развернуться{}, // развернуться в коридоре rus_verbs:подозревать{}, // подозревать в мошенничестве rus_verbs:играть{}, // играть в команде rus_verbs:сыграть{}, // сыграть в команде rus_verbs:строить{}, // строить в деревне rus_verbs:устроить{}, // устроить в доме вечеринку rus_verbs:находить{}, // находить в лесу rus_verbs:нуждаться{}, // нуждаться в деньгах rus_verbs:испытать{}, // испытать в рабочей обстановке rus_verbs:мелькнуть{}, // мелькнуть в прицеле rus_verbs:очутиться{}, // очутиться в закрытом помещении инфинитив:использовать{вид:соверш}, // использовать в работе инфинитив:использовать{вид:несоверш}, глагол:использовать{вид:несоверш}, глагол:использовать{вид:соверш}, rus_verbs:лететь{}, // лететь в самолете rus_verbs:смеяться{}, // смеяться в цирке rus_verbs:ездить{}, // ездить в лимузине rus_verbs:заснуть{}, // заснуть в неудобной позе rus_verbs:застать{}, // застать в неформальной обстановке rus_verbs:очнуться{}, // очнуться в незнакомой обстановке rus_verbs:твориться{}, // Что творится в закрытой зоне rus_verbs:разглядеть{}, // разглядеть в темноте rus_verbs:изучать{}, // изучать в естественных условиях rus_verbs:удержаться{}, // удержаться в седле rus_verbs:побывать{}, // побывать в зоопарке rus_verbs:уловить{}, // уловить в словах нотку отчаяния rus_verbs:приобрести{}, // приобрести в лавке rus_verbs:исчезать{}, // исчезать в тумане rus_verbs:уверять{}, // уверять в своей невиновности rus_verbs:продолжаться{}, // продолжаться в воздухе rus_verbs:открывать{}, // открывать в городе новый стадион rus_verbs:поддержать{}, // поддержать в парке порядок rus_verbs:солить{}, // солить в бочке rus_verbs:прожить{}, // прожить в деревне rus_verbs:создавать{}, // создавать в театре rus_verbs:обсуждать{}, // обсуждать в коллективе rus_verbs:заказать{}, // заказать в магазине rus_verbs:отыскать{}, // отыскать в гараже rus_verbs:уснуть{}, // уснуть в кресле rus_verbs:задержаться{}, // задержаться в театре rus_verbs:подобрать{}, // подобрать в коллекции rus_verbs:пробовать{}, // пробовать в работе rus_verbs:курить{}, // курить в закрытом помещении rus_verbs:устраивать{}, // устраивать в лесу засаду rus_verbs:установить{}, // установить в багажнике rus_verbs:запереть{}, // запереть в сарае rus_verbs:содержать{}, // содержать в достатке rus_verbs:синеть{}, // синеть в кислородной атмосфере rus_verbs:слышаться{}, // слышаться в голосе rus_verbs:закрыться{}, // закрыться в здании rus_verbs:скрываться{}, // скрываться в квартире rus_verbs:родить{}, // родить в больнице rus_verbs:описать{}, // описать в заметках rus_verbs:перехватить{}, // перехватить в коридоре rus_verbs:менять{}, // менять в магазине rus_verbs:скрывать{}, // скрывать в чужой квартире rus_verbs:стиснуть{}, // стиснуть в стальных объятиях rus_verbs:останавливаться{}, // останавливаться в гостинице rus_verbs:мелькать{}, // мелькать в телевизоре rus_verbs:присутствовать{}, // присутствовать в аудитории rus_verbs:украсть{}, // украсть в магазине rus_verbs:победить{}, // победить в войне rus_verbs:расположиться{}, // расположиться в гостинице rus_verbs:упомянуть{}, // упомянуть в своей книге rus_verbs:плыть{}, // плыть в старой бочке rus_verbs:нащупать{}, // нащупать в глубине rus_verbs:проявляться{}, // проявляться в работе rus_verbs:затихнуть{}, // затихнуть в норе rus_verbs:построить{}, // построить в гараже rus_verbs:поддерживать{}, // поддерживать в исправном состоянии rus_verbs:заработать{}, // заработать в стартапе rus_verbs:сломать{}, // сломать в суставе rus_verbs:снимать{}, // снимать в гардеробе rus_verbs:сохранить{}, // сохранить в коллекции rus_verbs:располагаться{}, // располагаться в отдельном кабинете rus_verbs:сражаться{}, // сражаться в честном бою rus_verbs:спускаться{}, // спускаться в батискафе rus_verbs:уничтожить{}, // уничтожить в схроне rus_verbs:изучить{}, // изучить в естественных условиях rus_verbs:рождаться{}, // рождаться в муках rus_verbs:пребывать{}, // пребывать в прострации rus_verbs:прилететь{}, // прилететь в аэробусе rus_verbs:догнать{}, // догнать в переулке rus_verbs:изобразить{}, // изобразить в танце rus_verbs:проехать{}, // проехать в легковушке rus_verbs:убедить{}, // убедить в разумности rus_verbs:приготовить{}, // приготовить в духовке rus_verbs:собирать{}, // собирать в лесу rus_verbs:поплыть{}, // поплыть в катере rus_verbs:доверять{}, // доверять в управлении rus_verbs:разобраться{}, // разобраться в законах rus_verbs:ловить{}, // ловить в озере rus_verbs:проесть{}, // проесть в куске металла отверстие rus_verbs:спрятаться{}, // спрятаться в подвале rus_verbs:провозгласить{}, // провозгласить в речи rus_verbs:изложить{}, // изложить в своём выступлении rus_verbs:замяться{}, // замяться в коридоре rus_verbs:раздаваться{}, // Крик ягуара раздается в джунглях rus_verbs:доказать{}, // Автор доказал в своей работе, что теорема верна rus_verbs:хранить{}, // хранить в шкатулке rus_verbs:шутить{}, // шутить в классе глагол:рассыпаться{ aux stress="рассып^аться" }, // рассыпаться в извинениях инфинитив:рассыпаться{ aux stress="рассып^аться" }, rus_verbs:чертить{}, // чертить в тетрадке rus_verbs:отразиться{}, // отразиться в аттестате rus_verbs:греть{}, // греть в микроволновке rus_verbs:зарычать{}, // Кто-то зарычал в глубине леса rus_verbs:рассуждать{}, // Автор рассуждает в своей статье rus_verbs:освободить{}, // Обвиняемые были освобождены в зале суда rus_verbs:окружать{}, // окружать в лесу rus_verbs:сопровождать{}, // сопровождать в операции rus_verbs:заканчиваться{}, // заканчиваться в дороге rus_verbs:поселиться{}, // поселиться в загородном доме rus_verbs:охватывать{}, // охватывать в хронологии rus_verbs:запеть{}, // запеть в кино инфинитив:провозить{вид:несоверш}, // провозить в багаже глагол:провозить{вид:несоверш}, rus_verbs:мочить{}, // мочить в сортире rus_verbs:перевернуться{}, // перевернуться в полёте rus_verbs:улететь{}, // улететь в теплые края rus_verbs:сдержать{}, // сдержать в руках rus_verbs:преследовать{}, // преследовать в любой другой стране rus_verbs:драться{}, // драться в баре rus_verbs:просидеть{}, // просидеть в классе rus_verbs:убираться{}, // убираться в квартире rus_verbs:содрогнуться{}, // содрогнуться в приступе отвращения rus_verbs:пугать{}, // пугать в прессе rus_verbs:отреагировать{}, // отреагировать в прессе rus_verbs:проверять{}, // проверять в аппарате rus_verbs:убеждать{}, // убеждать в отсутствии альтернатив rus_verbs:летать{}, // летать в комфортабельном частном самолёте rus_verbs:толпиться{}, // толпиться в фойе rus_verbs:плавать{}, // плавать в специальном костюме rus_verbs:пробыть{}, // пробыть в воде слишком долго rus_verbs:прикинуть{}, // прикинуть в уме rus_verbs:застрять{}, // застрять в лифте rus_verbs:метаться{}, // метаться в кровате rus_verbs:сжечь{}, // сжечь в печке rus_verbs:расслабиться{}, // расслабиться в ванной rus_verbs:услыхать{}, // услыхать в автобусе rus_verbs:удержать{}, // удержать в вертикальном положении rus_verbs:образоваться{}, // образоваться в верхних слоях атмосферы rus_verbs:рассмотреть{}, // рассмотреть в капле воды rus_verbs:просмотреть{}, // просмотреть в браузере rus_verbs:учесть{}, // учесть в планах rus_verbs:уезжать{}, // уезжать в чьей-то машине rus_verbs:похоронить{}, // похоронить в мерзлой земле rus_verbs:растянуться{}, // растянуться в расслабленной позе rus_verbs:обнаружиться{}, // обнаружиться в чужой сумке rus_verbs:гулять{}, // гулять в парке rus_verbs:утонуть{}, // утонуть в реке rus_verbs:зажать{}, // зажать в медвежьих объятиях rus_verbs:усомниться{}, // усомниться в объективности rus_verbs:танцевать{}, // танцевать в спортзале rus_verbs:проноситься{}, // проноситься в голове rus_verbs:трудиться{}, // трудиться в кооперативе глагол:засыпать{ aux stress="засып^ать" переходность:непереходный }, // засыпать в спальном мешке инфинитив:засыпать{ aux stress="засып^ать" переходность:непереходный }, rus_verbs:сушить{}, // сушить в сушильном шкафу rus_verbs:зашевелиться{}, // зашевелиться в траве rus_verbs:обдумывать{}, // обдумывать в спокойной обстановке rus_verbs:промелькнуть{}, // промелькнуть в окне rus_verbs:поучаствовать{}, // поучаствовать в обсуждении rus_verbs:закрыть{}, // закрыть в комнате rus_verbs:запирать{}, // запирать в комнате rus_verbs:закрывать{}, // закрывать в доме rus_verbs:заблокировать{}, // заблокировать в доме rus_verbs:зацвести{}, // В садах зацвела сирень rus_verbs:кричать{}, // Какое-то животное кричало в ночном лесу. rus_verbs:поглотить{}, // фотон, поглощенный в рецепторе rus_verbs:стоять{}, // войска, стоявшие в Риме rus_verbs:закалить{}, // ветераны, закаленные в боях rus_verbs:выступать{}, // пришлось выступать в тюрьме. rus_verbs:выступить{}, // пришлось выступить в тюрьме. rus_verbs:закопошиться{}, // Мыши закопошились в траве rus_verbs:воспламениться{}, // смесь, воспламенившаяся в цилиндре rus_verbs:воспламеняться{}, // смесь, воспламеняющаяся в цилиндре rus_verbs:закрываться{}, // закрываться в комнате rus_verbs:провалиться{}, // провалиться в прокате деепричастие:авторизируясь{ вид:несоверш }, глагол:авторизироваться{ вид:несоверш }, инфинитив:авторизироваться{ вид:несоверш }, // авторизироваться в системе rus_verbs:существовать{}, // существовать в вакууме деепричастие:находясь{}, прилагательное:находившийся{}, прилагательное:находящийся{}, глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, // находиться в вакууме rus_verbs:регистрировать{}, // регистрировать в инспекции глагол:перерегистрировать{ вид:несоверш }, глагол:перерегистрировать{ вид:соверш }, инфинитив:перерегистрировать{ вид:несоверш }, инфинитив:перерегистрировать{ вид:соверш }, // перерегистрировать в инспекции rus_verbs:поковыряться{}, // поковыряться в носу rus_verbs:оттаять{}, // оттаять в кипятке rus_verbs:распинаться{}, // распинаться в проклятиях rus_verbs:отменить{}, // Министерство связи предлагает отменить внутренний роуминг в России rus_verbs:столкнуться{}, // Американский эсминец и японский танкер столкнулись в Персидском заливе rus_verbs:ценить{}, // Он очень ценил в статьях краткость изложения. прилагательное:несчастный{}, // Он очень несчастен в семейной жизни. rus_verbs:объясниться{}, // Он объяснился в любви. прилагательное:нетвердый{}, // Он нетвёрд в истории. rus_verbs:заниматься{}, // Он занимается в читальном зале. rus_verbs:вращаться{}, // Он вращается в учёных кругах. прилагательное:спокойный{}, // Он был спокоен и уверен в завтрашнем дне. rus_verbs:бегать{}, // Он бегал по городу в поисках квартиры. rus_verbs:заключать{}, // Письмо заключало в себе очень важные сведения. rus_verbs:срабатывать{}, // Алгоритм срабатывает в половине случаев. rus_verbs:специализироваться{}, // мы специализируемся в создании ядерного оружия rus_verbs:сравниться{}, // Никто не может сравниться с ним в знаниях. rus_verbs:продолжать{}, // Продолжайте в том же духе. rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц. rus_verbs:болтать{}, // Не болтай в присутствии начальника! rus_verbs:проболтаться{}, // Не проболтайся в присутствии начальника! rus_verbs:повторить{}, // Он должен повторить свои показания в присутствии свидетелей rus_verbs:получить{}, // ректор поздравил студентов, получивших в этом семестре повышенную стипендию rus_verbs:приобретать{}, // Эту еду мы приобретаем в соседнем магазине. rus_verbs:расходиться{}, // Маша и Петя расходятся во взглядах rus_verbs:сходиться{}, // Все дороги сходятся в Москве rus_verbs:убирать{}, // убирать в комнате rus_verbs:удостоверяться{}, // он удостоверяется в личности специалиста rus_verbs:уединяться{}, // уединяться в пустыне rus_verbs:уживаться{}, // уживаться в одном коллективе rus_verbs:укорять{}, // укорять друга в забывчивости rus_verbs:читать{}, // он читал об этом в журнале rus_verbs:состояться{}, // В Израиле состоятся досрочные парламентские выборы rus_verbs:погибнуть{}, // Список погибших в авиакатастрофе под Ярославлем rus_verbs:работать{}, // Я работаю в театре. rus_verbs:признать{}, // Я признал в нём старого друга. rus_verbs:преподавать{}, // Я преподаю в университете. rus_verbs:понимать{}, // Я плохо понимаю в живописи. rus_verbs:водиться{}, // неизвестный науке зверь, который водится в жарких тропических лесах rus_verbs:разразиться{}, // В Москве разразилась эпидемия гриппа rus_verbs:замереть{}, // вся толпа замерла в восхищении rus_verbs:сидеть{}, // Я люблю сидеть в этом удобном кресле. rus_verbs:идти{}, // Я иду в неопределённом направлении. rus_verbs:заболеть{}, // Я заболел в дороге. rus_verbs:ехать{}, // Я еду в автобусе rus_verbs:взять{}, // Я взял книгу в библиотеке на неделю. rus_verbs:провести{}, // Юные годы он провёл в Италии. rus_verbs:вставать{}, // Этот случай живо встаёт в моей памяти. rus_verbs:возвысить{}, // Это событие возвысило его в общественном мнении. rus_verbs:произойти{}, // Это произошло в одном городе в Японии. rus_verbs:привидеться{}, // Это мне привиделось во сне. rus_verbs:держаться{}, // Это дело держится в большом секрете. rus_verbs:привиться{}, // Это выражение не привилось в русском языке. rus_verbs:восстановиться{}, // Эти писатели восстановились в правах. rus_verbs:быть{}, // Эта книга есть в любом книжном магазине. прилагательное:популярный{}, // Эта идея очень популярна в массах. rus_verbs:шуметь{}, // Шумит в голове. rus_verbs:остаться{}, // Шляпа осталась в поезде. rus_verbs:выражаться{}, // Характер писателя лучше всего выражается в его произведениях. rus_verbs:воспитать{}, // Учительница воспитала в детях любовь к природе. rus_verbs:пересохнуть{}, // У меня в горле пересохло. rus_verbs:щекотать{}, // У меня в горле щекочет. rus_verbs:колоть{}, // У меня в боку колет. прилагательное:свежий{}, // Событие ещё свежо в памяти. rus_verbs:собрать{}, // Соберите всех учеников во дворе. rus_verbs:белеть{}, // Снег белеет в горах. rus_verbs:сделать{}, // Сколько орфографических ошибок ты сделал в диктанте? rus_verbs:таять{}, // Сахар тает в кипятке. rus_verbs:жать{}, // Сапог жмёт в подъёме. rus_verbs:возиться{}, // Ребята возятся в углу. rus_verbs:распоряжаться{}, // Прошу не распоряжаться в чужом доме. rus_verbs:кружиться{}, // Они кружились в вальсе. rus_verbs:выставлять{}, // Они выставляют его в смешном виде. rus_verbs:бывать{}, // Она часто бывает в обществе. rus_verbs:петь{}, // Она поёт в опере. rus_verbs:сойтись{}, // Все свидетели сошлись в своих показаниях. rus_verbs:валяться{}, // Вещи валялись в беспорядке. rus_verbs:пройти{}, // Весь день прошёл в беготне. rus_verbs:продавать{}, // В этом магазине продают обувь. rus_verbs:заключаться{}, // В этом заключается вся сущность. rus_verbs:звенеть{}, // В ушах звенит. rus_verbs:проступить{}, // В тумане проступили очертания корабля. rus_verbs:бить{}, // В саду бьёт фонтан. rus_verbs:проскользнуть{}, // В речи проскользнул упрёк. rus_verbs:оставить{}, // Не оставь товарища в опасности. rus_verbs:прогулять{}, // Мы прогуляли час в парке. rus_verbs:перебить{}, // Мы перебили врагов в бою. rus_verbs:остановиться{}, // Мы остановились в первой попавшейся гостинице. rus_verbs:видеть{}, // Он многое видел в жизни. // глагол:проходить{ вид:несоверш }, // Беседа проходила в дружественной атмосфере. rus_verbs:подать{}, // Автор подал своих героев в реалистических тонах. rus_verbs:кинуть{}, // Он кинул меня в беде. rus_verbs:приходить{}, // Приходи в сентябре rus_verbs:воскрешать{}, // воскрешать в памяти rus_verbs:соединять{}, // соединять в себе rus_verbs:разбираться{}, // умение разбираться в вещах rus_verbs:делать{}, // В её комнате делали обыск. rus_verbs:воцариться{}, // В зале воцарилась глубокая тишина. rus_verbs:начаться{}, // В деревне начались полевые работы. rus_verbs:блеснуть{}, // В голове блеснула хорошая мысль. rus_verbs:вертеться{}, // В голове вертится вчерашний разговор. rus_verbs:веять{}, // В воздухе веет прохладой. rus_verbs:висеть{}, // В воздухе висит зной. rus_verbs:носиться{}, // В воздухе носятся комары. rus_verbs:грести{}, // Грести в спокойной воде будет немного легче, но скучнее rus_verbs:воскресить{}, // воскресить в памяти rus_verbs:поплавать{}, // поплавать в 100-метровом бассейне rus_verbs:пострадать{}, // В массовой драке пострадал 23-летний мужчина прилагательное:уверенный{ причастие }, // Она уверена в своих силах. прилагательное:постоянный{}, // Она постоянна во вкусах. прилагательное:сильный{}, // Он не силён в математике. прилагательное:повинный{}, // Он не повинен в этом. прилагательное:возможный{}, // Ураганы, сильные грозы и даже смерчи возможны в конце периода сильной жары rus_verbs:вывести{}, // способный летать над землей крокодил был выведен в секретной лаборатории прилагательное:нужный{}, // сковородка тоже нужна в хозяйстве. rus_verbs:сесть{}, // Она села в тени rus_verbs:заливаться{}, // в нашем парке заливаются соловьи rus_verbs:разнести{}, // В лесу огонь пожара мгновенно разнесло rus_verbs:чувствоваться{}, // В тёплом, но сыром воздухе остро чувствовалось дыхание осени // rus_verbs:расти{}, // дерево, растущее в лесу rus_verbs:происходить{}, // что происходит в поликлиннике rus_verbs:спать{}, // кто спит в моей кровати rus_verbs:мыть{}, // мыть машину в саду ГЛ_ИНФ(царить), // В воздухе царило безмолвие ГЛ_ИНФ(мести), // мести в прихожей пол ГЛ_ИНФ(прятать), // прятать в яме ГЛ_ИНФ(увидеть), прилагательное:увидевший{}, деепричастие:увидев{}, // увидел периодическую таблицу элементов во сне. // ГЛ_ИНФ(собраться), // собраться в порту ГЛ_ИНФ(случиться), // что-то случилось в больнице ГЛ_ИНФ(зажечься), // в небе зажглись звёзды ГЛ_ИНФ(купить), // купи молока в магазине прилагательное:пропагандировавшийся{} // группа студентов университета дружбы народов, активно пропагандировавшейся в СССР } // Чтобы разрешить связывание в паттернах типа: пообедать в macdonalds fact гл_предл { if context { Гл_В_Предл предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_В_Предл предлог:в{} *:*{ падеж:предл } } then return true } // С локативом: // собраться в порту fact гл_предл { if context { Гл_В_Предл предлог:в{} существительное:*{ падеж:мест } } then return true } #endregion Предложный #region Винительный // Для глаголов движения с выраженным направлением действия может присоединяться // предложный паттерн с винительным падежом. wordentry_set Гл_В_Вин = { rus_verbs:вдавиться{}, // Дуло больно вдавилось в позвонок. глагол:ввергнуть{}, // Двух прелестнейших дам он ввергнул в горе. глагол:ввергать{}, инфинитив:ввергнуть{}, инфинитив:ввергать{}, rus_verbs:двинуться{}, // Двинулись в путь и мы. rus_verbs:сплавать{}, // Сплавать в Россию! rus_verbs:уложиться{}, // Уложиться в воскресенье. rus_verbs:спешить{}, // Спешите в Лондон rus_verbs:кинуть{}, // Киньте в море. rus_verbs:проситься{}, // Просилась в Никарагуа. rus_verbs:притопать{}, // Притопал в Будапешт. rus_verbs:скататься{}, // Скатался в Красноярск. rus_verbs:соскользнуть{}, // Соскользнул в пике. rus_verbs:соскальзывать{}, rus_verbs:играть{}, // Играл в дутье. глагол:айда{}, // Айда в каморы. rus_verbs:отзывать{}, // Отзывали в Москву... rus_verbs:сообщаться{}, // Сообщается в Лондон. rus_verbs:вдуматься{}, // Вдумайтесь в них. rus_verbs:проехать{}, // Проехать в Лунево... rus_verbs:спрыгивать{}, // Спрыгиваем в него. rus_verbs:верить{}, // Верю в вас! rus_verbs:прибыть{}, // Прибыл в Подмосковье. rus_verbs:переходить{}, // Переходите в школу. rus_verbs:доложить{}, // Доложили в Москву. rus_verbs:подаваться{}, // Подаваться в Россию? rus_verbs:спрыгнуть{}, // Спрыгнул в него. rus_verbs:вывезти{}, // Вывезли в Китай. rus_verbs:пропихивать{}, // Я очень аккуратно пропихивал дуло в ноздрю. rus_verbs:пропихнуть{}, rus_verbs:транспортироваться{}, rus_verbs:закрадываться{}, // в голову начали закрадываться кое-какие сомнения и подозрения rus_verbs:дуть{}, rus_verbs:БОГАТЕТЬ{}, // rus_verbs:РАЗБОГАТЕТЬ{}, // rus_verbs:ВОЗРАСТАТЬ{}, // rus_verbs:ВОЗРАСТИ{}, // rus_verbs:ПОДНЯТЬ{}, // Он поднял половинку самолета в воздух и на всей скорости повел ее к горам. (ПОДНЯТЬ) rus_verbs:ОТКАТИТЬСЯ{}, // Услышав за спиной дыхание, он прыгнул вперед и откатился в сторону, рассчитывая ускользнуть от врага, нападавшего сзади (ОТКАТИТЬСЯ) rus_verbs:ВПЛЕТАТЬСЯ{}, // В общий смрад вплеталось зловонье пены, летевшей из пастей, и крови из легких (ВПЛЕТАТЬСЯ) rus_verbs:ЗАМАНИТЬ{}, // Они подумали, что Павел пытается заманить их в зону обстрела. (ЗАМАНИТЬ,ЗАМАНИВАТЬ) rus_verbs:ЗАМАНИВАТЬ{}, rus_verbs:ПРОТРУБИТЬ{}, // Эти врата откроются, когда он протрубит в рог, и пропустят его в другую вселенную. (ПРОТРУБИТЬ) rus_verbs:ВРУБИТЬСЯ{}, // Клинок сломался, не врубившись в металл. (ВРУБИТЬСЯ/ВРУБАТЬСЯ) rus_verbs:ВРУБАТЬСЯ{}, rus_verbs:ОТПРАВИТЬ{}, // Мы ищем благородного вельможу, который нанял бы нас или отправил в рыцарский поиск. (ОТПРАВИТЬ) rus_verbs:ОБЛАЧИТЬ{}, // Этот был облачен в сверкавшие красные доспехи с опущенным забралом и держал огромное копье, дожидаясь своей очереди. (ОБЛАЧИТЬ/ОБЛАЧАТЬ/ОБЛАЧИТЬСЯ/ОБЛАЧАТЬСЯ/НАРЯДИТЬСЯ/НАРЯЖАТЬСЯ) rus_verbs:ОБЛАЧАТЬ{}, rus_verbs:ОБЛАЧИТЬСЯ{}, rus_verbs:ОБЛАЧАТЬСЯ{}, rus_verbs:НАРЯДИТЬСЯ{}, rus_verbs:НАРЯЖАТЬСЯ{}, rus_verbs:ЗАХВАТИТЬ{}, // Кроме набранного рабского материала обычного типа, он захватил в плен группу очень странных созданий, а также женщину исключительной красоты (ЗАХВАТИТЬ/ЗАХВАТЫВАТЬ/ЗАХВАТ) rus_verbs:ЗАХВАТЫВАТЬ{}, rus_verbs:ПРОВЕСТИ{}, // Он провел их в маленькое святилище позади штурвала. (ПРОВЕСТИ) rus_verbs:ПОЙМАТЬ{}, // Их можно поймать в ловушку (ПОЙМАТЬ) rus_verbs:СТРОИТЬСЯ{}, // На вершине они остановились, строясь в круг. (СТРОИТЬСЯ,ПОСТРОИТЬСЯ,ВЫСТРОИТЬСЯ) rus_verbs:ПОСТРОИТЬСЯ{}, rus_verbs:ВЫСТРОИТЬСЯ{}, rus_verbs:ВЫПУСТИТЬ{}, // Несколько стрел, выпущенных в преследуемых, вонзились в траву (ВЫПУСТИТЬ/ВЫПУСКАТЬ) rus_verbs:ВЫПУСКАТЬ{}, rus_verbs:ВЦЕПЛЯТЬСЯ{}, // Они вцепляются тебе в горло. (ВЦЕПЛЯТЬСЯ/ВЦЕПИТЬСЯ) rus_verbs:ВЦЕПИТЬСЯ{}, rus_verbs:ПАЛЬНУТЬ{}, // Вольф вставил в тетиву новую стрелу и пальнул в белое брюхо (ПАЛЬНУТЬ) rus_verbs:ОТСТУПИТЬ{}, // Вольф отступил в щель. (ОТСТУПИТЬ/ОТСТУПАТЬ) rus_verbs:ОТСТУПАТЬ{}, rus_verbs:КРИКНУТЬ{}, // Вольф крикнул в ответ и медленно отступил от птицы. (КРИКНУТЬ) rus_verbs:ДЫХНУТЬ{}, // В лицо ему дыхнули винным перегаром. (ДЫХНУТЬ) rus_verbs:ПОТРУБИТЬ{}, // Я видел рог во время своих скитаний по дворцу и даже потрубил в него (ПОТРУБИТЬ) rus_verbs:ОТКРЫВАТЬСЯ{}, // Некоторые врата открывались в другие вселенные (ОТКРЫВАТЬСЯ) rus_verbs:ТРУБИТЬ{}, // А я трубил в рог (ТРУБИТЬ) rus_verbs:ПЫРНУТЬ{}, // Вольф пырнул его в бок. (ПЫРНУТЬ) rus_verbs:ПРОСКРЕЖЕТАТЬ{}, // Тот что-то проскрежетал в ответ, а затем наорал на него. (ПРОСКРЕЖЕТАТЬ В вин, НАОРАТЬ НА вин) rus_verbs:ИМПОРТИРОВАТЬ{}, // импортировать товары двойного применения только в Российскую Федерацию (ИМПОРТИРОВАТЬ) rus_verbs:ОТЪЕХАТЬ{}, // Легкий грохот катков заглушил рог, когда дверь отъехала в сторону. (ОТЪЕХАТЬ) rus_verbs:ПОПЛЕСТИСЬ{}, // Подобрав нижнее белье, носки и ботинки, он поплелся по песку обратно в джунгли. (ПОПЛЕЛСЯ) rus_verbs:СЖАТЬСЯ{}, // Желудок у него сжался в кулак. (СЖАТЬСЯ, СЖИМАТЬСЯ) rus_verbs:СЖИМАТЬСЯ{}, rus_verbs:проверять{}, // Школьников будут принудительно проверять на курение rus_verbs:ПОТЯНУТЬ{}, // Я потянул его в кино (ПОТЯНУТЬ) rus_verbs:ПЕРЕВЕСТИ{}, // Премьер-министр Казахстана поручил до конца года перевести все социально-значимые услуги в электронный вид (ПЕРЕВЕСТИ) rus_verbs:КРАСИТЬ{}, // Почему китайские партийные боссы красят волосы в черный цвет? (КРАСИТЬ/ПОКРАСИТЬ/ПЕРЕКРАСИТЬ/ОКРАСИТЬ/ЗАКРАСИТЬ) rus_verbs:ПОКРАСИТЬ{}, // rus_verbs:ПЕРЕКРАСИТЬ{}, // rus_verbs:ОКРАСИТЬ{}, // rus_verbs:ЗАКРАСИТЬ{}, // rus_verbs:СООБЩИТЬ{}, // Мужчина ранил человека в щеку и сам сообщил об этом в полицию (СООБЩИТЬ) rus_verbs:СТЯГИВАТЬ{}, // Но толщина пузыря постоянно меняется из-за гравитации, которая стягивает жидкость в нижнюю часть (СТЯГИВАТЬ/СТЯНУТЬ/ЗАТЯНУТЬ/ВТЯНУТЬ) rus_verbs:СТЯНУТЬ{}, // rus_verbs:ЗАТЯНУТЬ{}, // rus_verbs:ВТЯНУТЬ{}, // rus_verbs:СОХРАНИТЬ{}, // сохранить данные в файл (СОХРАНИТЬ) деепричастие:придя{}, // Немного придя в себя rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал rus_verbs:УЛЫБАТЬСЯ{}, // она улыбалась во весь рот (УЛЫБАТЬСЯ) rus_verbs:МЕТНУТЬСЯ{}, // она метнулась обратно во тьму (МЕТНУТЬСЯ) rus_verbs:ПОСЛЕДОВАТЬ{}, // большинство жителей города последовало за ним во дворец (ПОСЛЕДОВАТЬ) rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // экстремисты перемещаются из лесов в Сеть (ПЕРЕМЕЩАТЬСЯ) rus_verbs:ВЫТАЩИТЬ{}, // Алексей позволил вытащить себя через дверь во тьму (ВЫТАЩИТЬ) rus_verbs:СЫПАТЬСЯ{}, // внизу под ними камни градом сыпались во двор (СЫПАТЬСЯ) rus_verbs:выезжать{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку rus_verbs:КРИЧАТЬ{}, // ей хотелось кричать во весь голос (КРИЧАТЬ В вин) rus_verbs:ВЫПРЯМИТЬСЯ{}, // волк выпрямился во весь огромный рост (ВЫПРЯМИТЬСЯ В вин) rus_verbs:спрятать{}, // Джон спрятал очки во внутренний карман (спрятать в вин) rus_verbs:ЭКСТРАДИРОВАТЬ{}, // Украина экстрадирует в Таджикистан задержанного бывшего премьер-министра (ЭКСТРАДИРОВАТЬ В вин) rus_verbs:ВВОЗИТЬ{}, // лабораторный мониторинг ввозимой в Россию мясной продукции из США (ВВОЗИТЬ В вин) rus_verbs:УПАКОВАТЬ{}, // упакованных в несколько слоев полиэтилена (УПАКОВАТЬ В вин) rus_verbs:ОТТЯГИВАТЬ{}, // использовать естественную силу гравитации, оттягивая объекты в сторону и изменяя их орбиту (ОТТЯГИВАТЬ В вин) rus_verbs:ПОЗВОНИТЬ{}, // они позвонили в отдел экологии городской администрации (ПОЗВОНИТЬ В) rus_verbs:ПРИВЛЕЧЬ{}, // Открытость данных о лесе поможет привлечь инвестиции в отрасль (ПРИВЛЕЧЬ В) rus_verbs:ЗАПРОСИТЬСЯ{}, // набегавшись и наплясавшись, Стасик утомился и запросился в кроватку (ЗАПРОСИТЬСЯ В) rus_verbs:ОТСТАВИТЬ{}, // бутыль с ацетоном Витька отставил в сторонку (ОТСТАВИТЬ В) rus_verbs:ИСПОЛЬЗОВАТЬ{}, // ты использовал свою магию во зло. (ИСПОЛЬЗОВАТЬ В вин) rus_verbs:ВЫСЕВАТЬ{}, // В апреле редис возможно уже высевать в грунт (ВЫСЕВАТЬ В) rus_verbs:ЗАГНАТЬ{}, // Американский психолог загнал любовь в три угла (ЗАГНАТЬ В) rus_verbs:ЭВОЛЮЦИОНИРОВАТЬ{}, // Почему не все обезьяны эволюционировали в человека? (ЭВОЛЮЦИОНИРОВАТЬ В вин) rus_verbs:СФОТОГРАФИРОВАТЬСЯ{}, // Он сфотографировался во весь рост. (СФОТОГРАФИРОВАТЬСЯ В) rus_verbs:СТАВИТЬ{}, // Он ставит мне в упрёк свою ошибку. (СТАВИТЬ В) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) rus_verbs:ПЕРЕСЕЛЯТЬСЯ{}, // Греки переселяются в Германию (ПЕРЕСЕЛЯТЬСЯ В) rus_verbs:ФОРМИРОВАТЬСЯ{}, // Сахарная свекла относится к двулетним растениям, мясистый корнеплод формируется в первый год. (ФОРМИРОВАТЬСЯ В) rus_verbs:ПРОВОРЧАТЬ{}, // дедуля что-то проворчал в ответ (ПРОВОРЧАТЬ В) rus_verbs:БУРКНУТЬ{}, // нелюдимый парень что-то буркнул в ответ (БУРКНУТЬ В) rus_verbs:ВЕСТИ{}, // дверь вела во тьму. (ВЕСТИ В) rus_verbs:ВЫСКОЧИТЬ{}, // беглецы выскочили во двор. (ВЫСКОЧИТЬ В) rus_verbs:ДОСЫЛАТЬ{}, // Одним движением стрелок досылает патрон в ствол (ДОСЫЛАТЬ В) rus_verbs:СЪЕХАТЬСЯ{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В) rus_verbs:ВЫТЯНУТЬ{}, // Дым вытянуло в трубу. (ВЫТЯНУТЬ В) rus_verbs:торчать{}, // острые обломки бревен торчали во все стороны. rus_verbs:ОГЛЯДЫВАТЬ{}, // Она оглядывает себя в зеркало. (ОГЛЯДЫВАТЬ В) rus_verbs:ДЕЙСТВОВАТЬ{}, // Этот пакет законов действует в ущерб частным предпринимателям. rus_verbs:РАЗЛЕТЕТЬСЯ{}, // люди разлетелись во все стороны. (РАЗЛЕТЕТЬСЯ В) rus_verbs:брызнуть{}, // во все стороны брызнула кровь. (брызнуть в) rus_verbs:ТЯНУТЬСЯ{}, // провода тянулись во все углы. (ТЯНУТЬСЯ В) rus_verbs:валить{}, // валить все в одну кучу (валить в) rus_verbs:выдвинуть{}, // его выдвинули в палату представителей (выдвинуть в) rus_verbs:карабкаться{}, // карабкаться в гору (карабкаться в) rus_verbs:клониться{}, // он клонился в сторону (клониться в) rus_verbs:командировать{}, // мы командировали нашего представителя в Рим (командировать в) rus_verbs:запасть{}, // Эти слова запали мне в душу. rus_verbs:давать{}, // В этой лавке дают в долг? rus_verbs:ездить{}, // Каждый день грузовик ездит в город. rus_verbs:претвориться{}, // Замысел претворился в жизнь. rus_verbs:разойтись{}, // Они разошлись в разные стороны. rus_verbs:выйти{}, // Охотник вышел в поле с ружьём. rus_verbs:отозвать{}, // Отзовите его в сторону и скажите ему об этом. rus_verbs:расходиться{}, // Маша и Петя расходятся в разные стороны rus_verbs:переодеваться{}, // переодеваться в женское платье rus_verbs:перерастать{}, // перерастать в массовые беспорядки rus_verbs:завязываться{}, // завязываться в узел rus_verbs:похватать{}, // похватать в руки rus_verbs:увлечь{}, // увлечь в прогулку по парку rus_verbs:помещать{}, // помещать в изолятор rus_verbs:зыркнуть{}, // зыркнуть в окошко rus_verbs:закатать{}, // закатать в асфальт rus_verbs:усаживаться{}, // усаживаться в кресло rus_verbs:загонять{}, // загонять в сарай rus_verbs:подбрасывать{}, // подбрасывать в воздух rus_verbs:телеграфировать{}, // телеграфировать в центр rus_verbs:вязать{}, // вязать в стопы rus_verbs:подлить{}, // подлить в огонь rus_verbs:заполучить{}, // заполучить в распоряжение rus_verbs:подогнать{}, // подогнать в док rus_verbs:ломиться{}, // ломиться в открытую дверь rus_verbs:переправить{}, // переправить в деревню rus_verbs:затягиваться{}, // затягиваться в трубу rus_verbs:разлетаться{}, // разлетаться в стороны rus_verbs:кланяться{}, // кланяться в ножки rus_verbs:устремляться{}, // устремляться в открытое море rus_verbs:переместиться{}, // переместиться в другую аудиторию rus_verbs:ложить{}, // ложить в ящик rus_verbs:отвозить{}, // отвозить в аэропорт rus_verbs:напрашиваться{}, // напрашиваться в гости rus_verbs:напроситься{}, // напроситься в гости rus_verbs:нагрянуть{}, // нагрянуть в гости rus_verbs:заворачивать{}, // заворачивать в фольгу rus_verbs:заковать{}, // заковать в кандалы rus_verbs:свезти{}, // свезти в сарай rus_verbs:притащиться{}, // притащиться в дом rus_verbs:завербовать{}, // завербовать в разведку rus_verbs:рубиться{}, // рубиться в компьютерные игры rus_verbs:тыкаться{}, // тыкаться в материнскую грудь инфинитив:ссыпать{ вид:несоверш }, инфинитив:ссыпать{ вид:соверш }, // ссыпать в контейнер глагол:ссыпать{ вид:несоверш }, глагол:ссыпать{ вид:соверш }, деепричастие:ссыпав{}, деепричастие:ссыпая{}, rus_verbs:засасывать{}, // засасывать в себя rus_verbs:скакнуть{}, // скакнуть в будущее rus_verbs:подвозить{}, // подвозить в театр rus_verbs:переиграть{}, // переиграть в покер rus_verbs:мобилизовать{}, // мобилизовать в действующую армию rus_verbs:залетать{}, // залетать в закрытое воздушное пространство rus_verbs:подышать{}, // подышать в трубочку rus_verbs:смотаться{}, // смотаться в институт rus_verbs:рассовать{}, // рассовать в кармашки rus_verbs:захаживать{}, // захаживать в дом инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять в ломбард деепричастие:сгоняя{}, rus_verbs:посылаться{}, // посылаться в порт rus_verbs:отлить{}, // отлить в кастрюлю rus_verbs:преобразоваться{}, // преобразоваться в линейное уравнение rus_verbs:поплакать{}, // поплакать в платочек rus_verbs:обуться{}, // обуться в сапоги rus_verbs:закапать{}, // закапать в глаза инфинитив:свозить{ вид:несоверш }, инфинитив:свозить{ вид:соверш }, // свозить в центр утилизации глагол:свозить{ вид:несоверш }, глагол:свозить{ вид:соверш }, деепричастие:свозив{}, деепричастие:свозя{}, rus_verbs:преобразовать{}, // преобразовать в линейное уравнение rus_verbs:кутаться{}, // кутаться в плед rus_verbs:смещаться{}, // смещаться в сторону rus_verbs:зазывать{}, // зазывать в свой магазин инфинитив:трансформироваться{ вид:несоверш }, инфинитив:трансформироваться{ вид:соверш }, // трансформироваться в комбинезон глагол:трансформироваться{ вид:несоверш }, глагол:трансформироваться{ вид:соверш }, деепричастие:трансформируясь{}, деепричастие:трансформировавшись{}, rus_verbs:погружать{}, // погружать в кипящее масло rus_verbs:обыграть{}, // обыграть в теннис rus_verbs:закутать{}, // закутать в одеяло rus_verbs:изливаться{}, // изливаться в воду rus_verbs:закатывать{}, // закатывать в асфальт rus_verbs:мотнуться{}, // мотнуться в банк rus_verbs:избираться{}, // избираться в сенат rus_verbs:наниматься{}, // наниматься в услужение rus_verbs:настучать{}, // настучать в органы rus_verbs:запихивать{}, // запихивать в печку rus_verbs:закапывать{}, // закапывать в нос rus_verbs:засобираться{}, // засобираться в поход rus_verbs:копировать{}, // копировать в другую папку rus_verbs:замуровать{}, // замуровать в стену rus_verbs:упечь{}, // упечь в тюрьму rus_verbs:зрить{}, // зрить в корень rus_verbs:стягиваться{}, // стягиваться в одну точку rus_verbs:усаживать{}, // усаживать в тренажер rus_verbs:протолкнуть{}, // протолкнуть в отверстие rus_verbs:расшибиться{}, // расшибиться в лепешку rus_verbs:приглашаться{}, // приглашаться в кабинет rus_verbs:садить{}, // садить в телегу rus_verbs:уткнуть{}, // уткнуть в подушку rus_verbs:протечь{}, // протечь в подвал rus_verbs:перегнать{}, // перегнать в другую страну rus_verbs:переползти{}, // переползти в тень rus_verbs:зарываться{}, // зарываться в грунт rus_verbs:переодеть{}, // переодеть в сухую одежду rus_verbs:припуститься{}, // припуститься в пляс rus_verbs:лопотать{}, // лопотать в микрофон rus_verbs:прогнусавить{}, // прогнусавить в микрофон rus_verbs:мочиться{}, // мочиться в штаны rus_verbs:загружать{}, // загружать в патронник rus_verbs:радировать{}, // радировать в центр rus_verbs:промотать{}, // промотать в конец rus_verbs:помчать{}, // помчать в школу rus_verbs:съезжать{}, // съезжать в кювет rus_verbs:завозить{}, // завозить в магазин rus_verbs:заявляться{}, // заявляться в школу rus_verbs:наглядеться{}, // наглядеться в зеркало rus_verbs:сворачиваться{}, // сворачиваться в клубочек rus_verbs:устремлять{}, // устремлять взор в будущее rus_verbs:забредать{}, // забредать в глухие уголки rus_verbs:перемотать{}, // перемотать в самое начало диалога rus_verbs:сморкаться{}, // сморкаться в носовой платочек rus_verbs:перетекать{}, // перетекать в другой сосуд rus_verbs:закачать{}, // закачать в шарик rus_verbs:запрятать{}, // запрятать в сейф rus_verbs:пинать{}, // пинать в живот rus_verbs:затрубить{}, // затрубить в горн rus_verbs:подглядывать{}, // подглядывать в замочную скважину инфинитив:подсыпать{ вид:соверш }, инфинитив:подсыпать{ вид:несоверш }, // подсыпать в питье глагол:подсыпать{ вид:соверш }, глагол:подсыпать{ вид:несоверш }, деепричастие:подсыпав{}, деепричастие:подсыпая{}, rus_verbs:засовывать{}, // засовывать в пенал rus_verbs:отрядить{}, // отрядить в командировку rus_verbs:справлять{}, // справлять в кусты rus_verbs:поторапливаться{}, // поторапливаться в самолет rus_verbs:скопировать{}, // скопировать в кэш rus_verbs:подливать{}, // подливать в огонь rus_verbs:запрячь{}, // запрячь в повозку rus_verbs:окраситься{}, // окраситься в пурпур rus_verbs:уколоть{}, // уколоть в шею rus_verbs:слететься{}, // слететься в гнездо rus_verbs:резаться{}, // резаться в карты rus_verbs:затесаться{}, // затесаться в ряды оппозиционеров инфинитив:задвигать{ вид:несоверш }, глагол:задвигать{ вид:несоверш }, // задвигать в ячейку (несоверш) деепричастие:задвигая{}, rus_verbs:доставляться{}, // доставляться в ресторан rus_verbs:поплевать{}, // поплевать в чашку rus_verbs:попереться{}, // попереться в магазин rus_verbs:хаживать{}, // хаживать в церковь rus_verbs:преображаться{}, // преображаться в королеву rus_verbs:организоваться{}, // организоваться в группу rus_verbs:ужалить{}, // ужалить в руку rus_verbs:протискиваться{}, // протискиваться в аудиторию rus_verbs:препроводить{}, // препроводить в закуток rus_verbs:разъезжаться{}, // разъезжаться в разные стороны rus_verbs:пропыхтеть{}, // пропыхтеть в трубку rus_verbs:уволочь{}, // уволочь в нору rus_verbs:отодвигаться{}, // отодвигаться в сторону rus_verbs:разливать{}, // разливать в стаканы rus_verbs:сбегаться{}, // сбегаться в актовый зал rus_verbs:наведаться{}, // наведаться в кладовку rus_verbs:перекочевать{}, // перекочевать в горы rus_verbs:прощебетать{}, // прощебетать в трубку rus_verbs:перекладывать{}, // перекладывать в другой карман rus_verbs:углубляться{}, // углубляться в теорию rus_verbs:переименовать{}, // переименовать в город rus_verbs:переметнуться{}, // переметнуться в лагерь противника rus_verbs:разносить{}, // разносить в щепки rus_verbs:осыпаться{}, // осыпаться в холода rus_verbs:попроситься{}, // попроситься в туалет rus_verbs:уязвить{}, // уязвить в сердце rus_verbs:перетащить{}, // перетащить в дом rus_verbs:закутаться{}, // закутаться в плед // rus_verbs:упаковать{}, // упаковать в бумагу инфинитив:тикать{ aux stress="тик^ать" }, глагол:тикать{ aux stress="тик^ать" }, // тикать в крепость rus_verbs:хихикать{}, // хихикать в кулачок rus_verbs:объединить{}, // объединить в сеть инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать в Калифорнию деепричастие:слетав{}, rus_verbs:заползти{}, // заползти в норку rus_verbs:перерасти{}, // перерасти в крупную аферу rus_verbs:списать{}, // списать в утиль rus_verbs:просачиваться{}, // просачиваться в бункер rus_verbs:пускаться{}, // пускаться в погоню rus_verbs:согревать{}, // согревать в мороз rus_verbs:наливаться{}, // наливаться в емкость rus_verbs:унестись{}, // унестись в небо rus_verbs:зашвырнуть{}, // зашвырнуть в шкаф rus_verbs:сигануть{}, // сигануть в воду rus_verbs:окунуть{}, // окунуть в ледяную воду rus_verbs:просочиться{}, // просочиться в сапог rus_verbs:соваться{}, // соваться в толпу rus_verbs:протолкаться{}, // протолкаться в гардероб rus_verbs:заложить{}, // заложить в ломбард rus_verbs:перекатить{}, // перекатить в сарай rus_verbs:поставлять{}, // поставлять в Китай rus_verbs:залезать{}, // залезать в долги rus_verbs:отлучаться{}, // отлучаться в туалет rus_verbs:сбиваться{}, // сбиваться в кучу rus_verbs:зарыть{}, // зарыть в землю rus_verbs:засадить{}, // засадить в тело rus_verbs:прошмыгнуть{}, // прошмыгнуть в дверь rus_verbs:переставить{}, // переставить в шкаф rus_verbs:отчалить{}, // отчалить в плавание rus_verbs:набираться{}, // набираться в команду rus_verbs:лягнуть{}, // лягнуть в живот rus_verbs:притворить{}, // притворить в жизнь rus_verbs:проковылять{}, // проковылять в гардероб rus_verbs:прикатить{}, // прикатить в гараж rus_verbs:залететь{}, // залететь в окно rus_verbs:переделать{}, // переделать в мопед rus_verbs:протащить{}, // протащить в совет rus_verbs:обмакнуть{}, // обмакнуть в воду rus_verbs:отклоняться{}, // отклоняться в сторону rus_verbs:запихать{}, // запихать в пакет rus_verbs:избирать{}, // избирать в совет rus_verbs:загрузить{}, // загрузить в буфер rus_verbs:уплывать{}, // уплывать в Париж rus_verbs:забивать{}, // забивать в мерзлоту rus_verbs:потыкать{}, // потыкать в безжизненную тушу rus_verbs:съезжаться{}, // съезжаться в санаторий rus_verbs:залепить{}, // залепить в рыло rus_verbs:набиться{}, // набиться в карманы rus_verbs:уползти{}, // уползти в нору rus_verbs:упрятать{}, // упрятать в камеру rus_verbs:переместить{}, // переместить в камеру анабиоза rus_verbs:закрасться{}, // закрасться в душу rus_verbs:сместиться{}, // сместиться в инфракрасную область rus_verbs:запускать{}, // запускать в серию rus_verbs:потрусить{}, // потрусить в чащобу rus_verbs:забрасывать{}, // забрасывать в чистую воду rus_verbs:переселить{}, // переселить в отдаленную деревню rus_verbs:переезжать{}, // переезжать в новую квартиру rus_verbs:приподнимать{}, // приподнимать в воздух rus_verbs:добавиться{}, // добавиться в конец очереди rus_verbs:убыть{}, // убыть в часть rus_verbs:передвигать{}, // передвигать в соседнюю клетку rus_verbs:добавляться{}, // добавляться в очередь rus_verbs:дописать{}, // дописать в перечень rus_verbs:записываться{}, // записываться в кружок rus_verbs:продаться{}, // продаться в кредитное рабство rus_verbs:переписывать{}, // переписывать в тетрадку rus_verbs:заплыть{}, // заплыть в территориальные воды инфинитив:пописать{ aux stress="поп^исать" }, инфинитив:пописать{ aux stress="попис^ать" }, // пописать в горшок глагол:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="попис^ать" }, rus_verbs:отбирать{}, // отбирать в гвардию rus_verbs:нашептывать{}, // нашептывать в микрофон rus_verbs:ковылять{}, // ковылять в стойло rus_verbs:прилетать{}, // прилетать в Париж rus_verbs:пролиться{}, // пролиться в канализацию rus_verbs:запищать{}, // запищать в микрофон rus_verbs:подвезти{}, // подвезти в больницу rus_verbs:припереться{}, // припереться в театр rus_verbs:утечь{}, // утечь в сеть rus_verbs:прорываться{}, // прорываться в буфет rus_verbs:увозить{}, // увозить в ремонт rus_verbs:съедать{}, // съедать в обед rus_verbs:просунуться{}, // просунуться в дверь rus_verbs:перенестись{}, // перенестись в прошлое rus_verbs:завезти{}, // завезти в магазин rus_verbs:проложить{}, // проложить в деревню rus_verbs:объединяться{}, // объединяться в профсоюз rus_verbs:развиться{}, // развиться в бабочку rus_verbs:засеменить{}, // засеменить в кабинку rus_verbs:скатываться{}, // скатываться в яму rus_verbs:завозиться{}, // завозиться в магазин rus_verbs:нанимать{}, // нанимать в рейс rus_verbs:поспеть{}, // поспеть в класс rus_verbs:кидаться{}, // кинаться в крайности rus_verbs:поспевать{}, // поспевать в оперу rus_verbs:обернуть{}, // обернуть в фольгу rus_verbs:обратиться{}, // обратиться в прокуратуру rus_verbs:истолковать{}, // истолковать в свою пользу rus_verbs:таращиться{}, // таращиться в дисплей rus_verbs:прыснуть{}, // прыснуть в кулачок rus_verbs:загнуть{}, // загнуть в другую сторону rus_verbs:раздать{}, // раздать в разные руки rus_verbs:назначить{}, // назначить в приемную комиссию rus_verbs:кидать{}, // кидать в кусты rus_verbs:увлекать{}, // увлекать в лес rus_verbs:переселиться{}, // переселиться в чужое тело rus_verbs:присылать{}, // присылать в город rus_verbs:уплыть{}, // уплыть в Европу rus_verbs:запричитать{}, // запричитать в полный голос rus_verbs:утащить{}, // утащить в логово rus_verbs:завернуться{}, // завернуться в плед rus_verbs:заносить{}, // заносить в блокнот rus_verbs:пятиться{}, // пятиться в дом rus_verbs:наведываться{}, // наведываться в больницу rus_verbs:нырять{}, // нырять в прорубь rus_verbs:зачастить{}, // зачастить в бар rus_verbs:назначаться{}, // назначается в комиссию rus_verbs:мотаться{}, // мотаться в областной центр rus_verbs:разыграть{}, // разыграть в карты rus_verbs:пропищать{}, // пропищать в микрофон rus_verbs:пихнуть{}, // пихнуть в бок rus_verbs:эмигрировать{}, // эмигрировать в Канаду rus_verbs:подключить{}, // подключить в сеть rus_verbs:упереть{}, // упереть в фундамент rus_verbs:уплатить{}, // уплатить в кассу rus_verbs:потащиться{}, // потащиться в медпункт rus_verbs:пригнать{}, // пригнать в стойло rus_verbs:оттеснить{}, // оттеснить в фойе rus_verbs:стучаться{}, // стучаться в ворота rus_verbs:перечислить{}, // перечислить в фонд rus_verbs:сомкнуть{}, // сомкнуть в круг rus_verbs:закачаться{}, // закачаться в резервуар rus_verbs:кольнуть{}, // кольнуть в бок rus_verbs:накрениться{}, // накрениться в сторону берега rus_verbs:подвинуться{}, // подвинуться в другую сторону rus_verbs:разнести{}, // разнести в клочья rus_verbs:отливать{}, // отливать в форму rus_verbs:подкинуть{}, // подкинуть в карман rus_verbs:уводить{}, // уводить в кабинет rus_verbs:ускакать{}, // ускакать в школу rus_verbs:ударять{}, // ударять в барабаны rus_verbs:даться{}, // даться в руки rus_verbs:поцеловаться{}, // поцеловаться в губы rus_verbs:посветить{}, // посветить в подвал rus_verbs:тыкать{}, // тыкать в арбуз rus_verbs:соединяться{}, // соединяться в кольцо rus_verbs:растянуть{}, // растянуть в тонкую ниточку rus_verbs:побросать{}, // побросать в пыль rus_verbs:стукнуться{}, // стукнуться в закрытую дверь rus_verbs:проигрывать{}, // проигрывать в теннис rus_verbs:дунуть{}, // дунуть в трубочку rus_verbs:улетать{}, // улетать в Париж rus_verbs:переводиться{}, // переводиться в филиал rus_verbs:окунуться{}, // окунуться в водоворот событий rus_verbs:попрятаться{}, // попрятаться в норы rus_verbs:перевезти{}, // перевезти в соседнюю палату rus_verbs:топать{}, // топать в школу rus_verbs:относить{}, // относить в помещение rus_verbs:укладывать{}, // укладывать в стопку rus_verbs:укатить{}, // укатил в турне rus_verbs:убирать{}, // убирать в сумку rus_verbs:помалкивать{}, // помалкивать в тряпочку rus_verbs:ронять{}, // ронять в грязь rus_verbs:глазеть{}, // глазеть в бинокль rus_verbs:преобразиться{}, // преобразиться в другого человека rus_verbs:запрыгнуть{}, // запрыгнуть в поезд rus_verbs:сгодиться{}, // сгодиться в суп rus_verbs:проползти{}, // проползти в нору rus_verbs:забираться{}, // забираться в коляску rus_verbs:сбежаться{}, // сбежались в класс rus_verbs:закатиться{}, // закатиться в угол rus_verbs:плевать{}, // плевать в душу rus_verbs:поиграть{}, // поиграть в демократию rus_verbs:кануть{}, // кануть в небытие rus_verbs:опаздывать{}, // опаздывать в школу rus_verbs:отползти{}, // отползти в сторону rus_verbs:стекаться{}, // стекаться в отстойник rus_verbs:запихнуть{}, // запихнуть в пакет rus_verbs:вышвырнуть{}, // вышвырнуть в коридор rus_verbs:связываться{}, // связываться в плотный узел rus_verbs:затолкать{}, // затолкать в ухо rus_verbs:скрутить{}, // скрутить в трубочку rus_verbs:сворачивать{}, // сворачивать в трубочку rus_verbs:сплестись{}, // сплестись в узел rus_verbs:заскочить{}, // заскочить в кабинет rus_verbs:проваливаться{}, // проваливаться в сон rus_verbs:уверовать{}, // уверовать в свою безнаказанность rus_verbs:переписать{}, // переписать в тетрадку rus_verbs:переноситься{}, // переноситься в мир фантазий rus_verbs:заводить{}, // заводить в помещение rus_verbs:сунуться{}, // сунуться в аудиторию rus_verbs:устраиваться{}, // устраиваться в автомастерскую rus_verbs:пропускать{}, // пропускать в зал инфинитив:сбегать{ вид:несоверш }, инфинитив:сбегать{ вид:соверш }, // сбегать в кино глагол:сбегать{ вид:несоверш }, глагол:сбегать{ вид:соверш }, деепричастие:сбегая{}, деепричастие:сбегав{}, rus_verbs:прибегать{}, // прибегать в школу rus_verbs:съездить{}, // съездить в лес rus_verbs:захлопать{}, // захлопать в ладошки rus_verbs:опрокинуться{}, // опрокинуться в грязь инфинитив:насыпать{ вид:несоверш }, инфинитив:насыпать{ вид:соверш }, // насыпать в стакан глагол:насыпать{ вид:несоверш }, глагол:насыпать{ вид:соверш }, деепричастие:насыпая{}, деепричастие:насыпав{}, rus_verbs:употреблять{}, // употреблять в пищу rus_verbs:приводиться{}, // приводиться в действие rus_verbs:пристроить{}, // пристроить в надежные руки rus_verbs:юркнуть{}, // юркнуть в нору rus_verbs:объединиться{}, // объединиться в банду rus_verbs:сажать{}, // сажать в одиночку rus_verbs:соединить{}, // соединить в кольцо rus_verbs:забрести{}, // забрести в кафешку rus_verbs:свернуться{}, // свернуться в клубочек rus_verbs:пересесть{}, // пересесть в другой автобус rus_verbs:постучаться{}, // постучаться в дверцу rus_verbs:соединять{}, // соединять в кольцо rus_verbs:приволочь{}, // приволочь в коморку rus_verbs:смахивать{}, // смахивать в ящик стола rus_verbs:забежать{}, // забежать в помещение rus_verbs:целиться{}, // целиться в беглеца rus_verbs:прокрасться{}, // прокрасться в хранилище rus_verbs:заковылять{}, // заковылять в травтамологию rus_verbs:прискакать{}, // прискакать в стойло rus_verbs:колотить{}, // колотить в дверь rus_verbs:смотреться{}, // смотреться в зеркало rus_verbs:подложить{}, // подложить в салон rus_verbs:пущать{}, // пущать в королевские покои rus_verbs:согнуть{}, // согнуть в дугу rus_verbs:забарабанить{}, // забарабанить в дверь rus_verbs:отклонить{}, // отклонить в сторону посадочной полосы rus_verbs:убраться{}, // убраться в специальную нишу rus_verbs:насмотреться{}, // насмотреться в зеркало rus_verbs:чмокнуть{}, // чмокнуть в щечку rus_verbs:усмехаться{}, // усмехаться в бороду rus_verbs:передвинуть{}, // передвинуть в конец очереди rus_verbs:допускаться{}, // допускаться в опочивальню rus_verbs:задвинуть{}, // задвинуть в дальний угол rus_verbs:отправлять{}, // отправлять в центр rus_verbs:сбрасывать{}, // сбрасывать в жерло rus_verbs:расстреливать{}, // расстреливать в момент обнаружения rus_verbs:заволочь{}, // заволочь в закуток rus_verbs:пролить{}, // пролить в воду rus_verbs:зарыться{}, // зарыться в сено rus_verbs:переливаться{}, // переливаться в емкость rus_verbs:затащить{}, // затащить в клуб rus_verbs:перебежать{}, // перебежать в лагерь врагов rus_verbs:одеть{}, // одеть в новое платье инфинитив:задвигаться{ вид:несоверш }, глагол:задвигаться{ вид:несоверш }, // задвигаться в нишу деепричастие:задвигаясь{}, rus_verbs:клюнуть{}, // клюнуть в темечко rus_verbs:наливать{}, // наливать в кружку rus_verbs:пролезть{}, // пролезть в ушко rus_verbs:откладывать{}, // откладывать в ящик rus_verbs:протянуться{}, // протянуться в соседний дом rus_verbs:шлепнуться{}, // шлепнуться лицом в грязь rus_verbs:устанавливать{}, // устанавливать в машину rus_verbs:употребляться{}, // употребляться в пищу rus_verbs:переключиться{}, // переключиться в реверсный режим rus_verbs:пискнуть{}, // пискнуть в микрофон rus_verbs:заявиться{}, // заявиться в класс rus_verbs:налиться{}, // налиться в стакан rus_verbs:заливать{}, // заливать в бак rus_verbs:ставиться{}, // ставиться в очередь инфинитив:писаться{ aux stress="п^исаться" }, глагол:писаться{ aux stress="п^исаться" }, // писаться в штаны деепричастие:писаясь{}, rus_verbs:целоваться{}, // целоваться в губы rus_verbs:наносить{}, // наносить в область сердца rus_verbs:посмеяться{}, // посмеяться в кулачок rus_verbs:употребить{}, // употребить в пищу rus_verbs:прорваться{}, // прорваться в столовую rus_verbs:укладываться{}, // укладываться в ровные стопки rus_verbs:пробиться{}, // пробиться в финал rus_verbs:забить{}, // забить в землю rus_verbs:переложить{}, // переложить в другой карман rus_verbs:опускать{}, // опускать в свежевырытую могилу rus_verbs:поторопиться{}, // поторопиться в школу rus_verbs:сдвинуться{}, // сдвинуться в сторону rus_verbs:капать{}, // капать в смесь rus_verbs:погружаться{}, // погружаться во тьму rus_verbs:направлять{}, // направлять в кабинку rus_verbs:погрузить{}, // погрузить во тьму rus_verbs:примчаться{}, // примчаться в школу rus_verbs:упираться{}, // упираться в дверь rus_verbs:удаляться{}, // удаляться в комнату совещаний rus_verbs:ткнуться{}, // ткнуться в окошко rus_verbs:убегать{}, // убегать в чащу rus_verbs:соединиться{}, // соединиться в необычную пространственную фигуру rus_verbs:наговорить{}, // наговорить в микрофон rus_verbs:переносить{}, // переносить в дом rus_verbs:прилечь{}, // прилечь в кроватку rus_verbs:поворачивать{}, // поворачивать в обратную сторону rus_verbs:проскочить{}, // проскочить в щель rus_verbs:совать{}, // совать в духовку rus_verbs:переодеться{}, // переодеться в чистую одежду rus_verbs:порвать{}, // порвать в лоскуты rus_verbs:завязать{}, // завязать в бараний рог rus_verbs:съехать{}, // съехать в кювет rus_verbs:литься{}, // литься в канистру rus_verbs:уклониться{}, // уклониться в левую сторону rus_verbs:смахнуть{}, // смахнуть в мусорное ведро rus_verbs:спускать{}, // спускать в шахту rus_verbs:плеснуть{}, // плеснуть в воду rus_verbs:подуть{}, // подуть в угольки rus_verbs:набирать{}, // набирать в команду rus_verbs:хлопать{}, // хлопать в ладошки rus_verbs:ранить{}, // ранить в самое сердце rus_verbs:посматривать{}, // посматривать в иллюминатор rus_verbs:превращать{}, // превращать воду в вино rus_verbs:толкать{}, // толкать в пучину rus_verbs:отбыть{}, // отбыть в расположение части rus_verbs:сгрести{}, // сгрести в карман rus_verbs:удрать{}, // удрать в тайгу rus_verbs:пристроиться{}, // пристроиться в хорошую фирму rus_verbs:сбиться{}, // сбиться в плотную группу rus_verbs:заключать{}, // заключать в объятия rus_verbs:отпускать{}, // отпускать в поход rus_verbs:устремить{}, // устремить взгляд в будущее rus_verbs:обронить{}, // обронить в траву rus_verbs:сливаться{}, // сливаться в речку rus_verbs:стекать{}, // стекать в канаву rus_verbs:свалить{}, // свалить в кучу rus_verbs:подтянуть{}, // подтянуть в кабину rus_verbs:скатиться{}, // скатиться в канаву rus_verbs:проскользнуть{}, // проскользнуть в приоткрытую дверь rus_verbs:заторопиться{}, // заторопиться в буфет rus_verbs:протиснуться{}, // протиснуться в центр толпы rus_verbs:прятать{}, // прятать в укромненькое местечко rus_verbs:пропеть{}, // пропеть в микрофон rus_verbs:углубиться{}, // углубиться в джунгли rus_verbs:сползти{}, // сползти в яму rus_verbs:записывать{}, // записывать в память rus_verbs:расстрелять{}, // расстрелять в упор (наречный оборот В УПОР) rus_verbs:колотиться{}, // колотиться в дверь rus_verbs:просунуть{}, // просунуть в отверстие rus_verbs:провожать{}, // провожать в армию rus_verbs:катить{}, // катить в гараж rus_verbs:поражать{}, // поражать в самое сердце rus_verbs:отлететь{}, // отлететь в дальний угол rus_verbs:закинуть{}, // закинуть в речку rus_verbs:катиться{}, // катиться в пропасть rus_verbs:забросить{}, // забросить в дальний угол rus_verbs:отвезти{}, // отвезти в лагерь rus_verbs:втопить{}, // втопить педаль в пол rus_verbs:втапливать{}, // втапливать педать в пол rus_verbs:утопить{}, // утопить кнопку в панель rus_verbs:напасть{}, // В Пекине участники антияпонских протестов напали на машину посла США rus_verbs:нанять{}, // Босс нанял в службу поддержки еще несколько девушек rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму rus_verbs:баллотировать{}, // претендент был баллотирован в жюри (баллотирован?) rus_verbs:вбухать{}, // Власти вбухали в этой проект много денег rus_verbs:вбухивать{}, // Власти вбухивают в этот проект очень много денег rus_verbs:поскакать{}, // поскакать в атаку rus_verbs:прицелиться{}, // прицелиться в бегущего зайца rus_verbs:прыгать{}, // прыгать в кровать rus_verbs:приглашать{}, // приглашать в дом rus_verbs:понестись{}, // понестись в ворота rus_verbs:заехать{}, // заехать в гаражный бокс rus_verbs:опускаться{}, // опускаться в бездну rus_verbs:переехать{}, // переехать в коттедж rus_verbs:поместить{}, // поместить в карантин rus_verbs:ползти{}, // ползти в нору rus_verbs:добавлять{}, // добавлять в корзину rus_verbs:уткнуться{}, // уткнуться в подушку rus_verbs:продавать{}, // продавать в рабство rus_verbs:спрятаться{}, // Белка спрячется в дупло. rus_verbs:врисовывать{}, // врисовывать новый персонаж в анимацию rus_verbs:воткнуть{}, // воткни вилку в розетку rus_verbs:нести{}, // нести в больницу rus_verbs:воткнуться{}, // вилка воткнулась в сочную котлетку rus_verbs:впаивать{}, // впаивать деталь в плату rus_verbs:впаиваться{}, // деталь впаивается в плату rus_verbs:впархивать{}, // впархивать в помещение rus_verbs:впаять{}, // впаять деталь в плату rus_verbs:впендюривать{}, // впендюривать штукенцию в агрегат rus_verbs:впендюрить{}, // впендюрить штукенцию в агрегат rus_verbs:вперивать{}, // вперивать взгляд в экран rus_verbs:впериваться{}, // впериваться в экран rus_verbs:вперить{}, // вперить взгляд в экран rus_verbs:впериться{}, // впериться в экран rus_verbs:вперять{}, // вперять взгляд в экран rus_verbs:вперяться{}, // вперяться в экран rus_verbs:впечатать{}, // впечатать текст в первую главу rus_verbs:впечататься{}, // впечататься в стену rus_verbs:впечатывать{}, // впечатывать текст в первую главу rus_verbs:впечатываться{}, // впечатываться в стену rus_verbs:впиваться{}, // Хищник впивается в жертву мощными зубами rus_verbs:впитаться{}, // Жидкость впиталась в ткань rus_verbs:впитываться{}, // Жидкость впитывается в ткань rus_verbs:впихивать{}, // Мама впихивает в сумку кусок колбасы rus_verbs:впихиваться{}, // Кусок колбасы впихивается в сумку rus_verbs:впихнуть{}, // Мама впихнула кастрюлю в холодильник rus_verbs:впихнуться{}, // Кастрюля впихнулась в холодильник rus_verbs:вплавиться{}, // Провод вплавился в плату rus_verbs:вплеснуть{}, // вплеснуть краситель в бак rus_verbs:вплести{}, // вплести ленту в волосы rus_verbs:вплестись{}, // вплестись в волосы rus_verbs:вплетать{}, // вплетать ленты в волосы rus_verbs:вплывать{}, // корабль вплывает в порт rus_verbs:вплыть{}, // яхта вплыла в бухту rus_verbs:вползать{}, // дракон вползает в пещеру rus_verbs:вползти{}, // дракон вполз в свою пещеру rus_verbs:впорхнуть{}, // бабочка впорхнула в окно rus_verbs:впрессовать{}, // впрессовать деталь в плиту rus_verbs:впрессоваться{}, // впрессоваться в плиту rus_verbs:впрессовывать{}, // впрессовывать деталь в плиту rus_verbs:впрессовываться{}, // впрессовываться в плиту rus_verbs:впрыгивать{}, // Пассажир впрыгивает в вагон rus_verbs:впрыгнуть{}, // Пассажир впрыгнул в вагон rus_verbs:впрыскивать{}, // Форсунка впрыскивает топливо в цилиндр rus_verbs:впрыскиваться{}, // Топливо впрыскивается форсункой в цилиндр rus_verbs:впрыснуть{}, // Форсунка впрыснула топливную смесь в камеру сгорания rus_verbs:впрягать{}, // впрягать лошадь в телегу rus_verbs:впрягаться{}, // впрягаться в работу rus_verbs:впрячь{}, // впрячь лошадь в телегу rus_verbs:впрячься{}, // впрячься в работу rus_verbs:впускать{}, // впускать посетителей в музей rus_verbs:впускаться{}, // впускаться в помещение rus_verbs:впустить{}, // впустить посетителей в музей rus_verbs:впутать{}, // впутать кого-то во что-то rus_verbs:впутаться{}, // впутаться во что-то rus_verbs:впутывать{}, // впутывать кого-то во что-то rus_verbs:впутываться{}, // впутываться во что-то rus_verbs:врабатываться{}, // врабатываться в режим rus_verbs:вработаться{}, // вработаться в режим rus_verbs:врастать{}, // врастать в кожу rus_verbs:врасти{}, // врасти в кожу инфинитив:врезать{ вид:несоверш }, // врезать замок в дверь инфинитив:врезать{ вид:соверш }, глагол:врезать{ вид:несоверш }, глагол:врезать{ вид:соверш }, деепричастие:врезая{}, деепричастие:врезав{}, прилагательное:врезанный{}, инфинитив:врезаться{ вид:несоверш }, // врезаться в стену инфинитив:врезаться{ вид:соверш }, глагол:врезаться{ вид:несоверш }, деепричастие:врезаясь{}, деепричастие:врезавшись{}, rus_verbs:врубить{}, // врубить в нагрузку rus_verbs:врываться{}, // врываться в здание rus_verbs:закачивать{}, // Насос закачивает топливо в бак rus_verbs:ввезти{}, // Предприятие ввезло товар в страну rus_verbs:вверстать{}, // Дизайнер вверстал блок в страницу rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу rus_verbs:вверстываться{}, // Блок тяжело вверстывается в эту страницу rus_verbs:ввивать{}, // Женщина ввивает полоску в косу rus_verbs:вволакиваться{}, // Пойманная мышь вволакивается котиком в дом rus_verbs:вволочь{}, // Кот вволок в дом пойманную крысу rus_verbs:вдергивать{}, // приспособление вдергивает нитку в игольное ушко rus_verbs:вдернуть{}, // приспособление вдернуло нитку в игольное ушко rus_verbs:вдувать{}, // Челоек вдувает воздух в легкие второго человека rus_verbs:вдуваться{}, // Воздух вдувается в легкие человека rus_verbs:вламываться{}, // Полиция вламывается в квартиру rus_verbs:вовлекаться{}, // трудные подростки вовлекаются в занятие спортом rus_verbs:вовлечь{}, // вовлечь трудных подростков в занятие спортом rus_verbs:вовлечься{}, // вовлечься в занятие спортом rus_verbs:спуститься{}, // спуститься в подвал rus_verbs:спускаться{}, // спускаться в подвал rus_verbs:отправляться{}, // отправляться в дальнее плавание инфинитив:эмитировать{ вид:соверш }, // Поверхность эмитирует электроны в пространство инфинитив:эмитировать{ вид:несоверш }, глагол:эмитировать{ вид:соверш }, глагол:эмитировать{ вид:несоверш }, деепричастие:эмитируя{}, деепричастие:эмитировав{}, прилагательное:эмитировавший{ вид:несоверш }, // прилагательное:эмитировавший{ вид:соверш }, прилагательное:эмитирующий{}, прилагательное:эмитируемый{}, прилагательное:эмитированный{}, инфинитив:этапировать{вид:несоверш}, // Преступника этапировали в колонию инфинитив:этапировать{вид:соверш}, глагол:этапировать{вид:несоверш}, глагол:этапировать{вид:соверш}, деепричастие:этапируя{}, прилагательное:этапируемый{}, прилагательное:этапированный{}, rus_verbs:этапироваться{}, // Преступники этапируются в колонию rus_verbs:баллотироваться{}, // они баллотировались в жюри rus_verbs:бежать{}, // Олигарх с семьей любовницы бежал в другую страну rus_verbs:бросать{}, // Они бросали в фонтан медные монетки rus_verbs:бросаться{}, // Дети бросались в воду с моста rus_verbs:бросить{}, // Он бросил в фонтан медную монетку rus_verbs:броситься{}, // самоубийца бросился с моста в воду rus_verbs:превратить{}, // Найден белок, который превратит человека в супергероя rus_verbs:буксировать{}, // Буксир буксирует танкер в порт rus_verbs:буксироваться{}, // Сухогруз буксируется в порт rus_verbs:вбегать{}, // Курьер вбегает в дверь rus_verbs:вбежать{}, // Курьер вбежал в дверь rus_verbs:вбетонировать{}, // Опора была вбетонирована в пол rus_verbs:вбивать{}, // Мастер вбивает штырь в плиту rus_verbs:вбиваться{}, // Штырь вбивается в плиту rus_verbs:вбирать{}, // Вата вбирает в себя влагу rus_verbs:вбить{}, // Ученик вбил в доску маленький гвоздь rus_verbs:вбрасывать{}, // Арбитр вбрасывает мяч в игру rus_verbs:вбрасываться{}, // Мяч вбрасывается в игру rus_verbs:вбросить{}, // Судья вбросил мяч в игру rus_verbs:вбуравиться{}, // Сверло вбуравилось в бетон rus_verbs:вбуравливаться{}, // Сверло вбуравливается в бетон rus_verbs:вбухиваться{}, // Много денег вбухиваются в этот проект rus_verbs:вваливаться{}, // Человек вваливается в кабинет врача rus_verbs:ввалить{}, // Грузчики ввалили мешок в квартиру rus_verbs:ввалиться{}, // Человек ввалился в кабинет терапевта rus_verbs:вваривать{}, // Робот вваривает арматурину в плиту rus_verbs:ввариваться{}, // Арматура вваривается в плиту rus_verbs:вварить{}, // Робот вварил арматурину в плиту rus_verbs:влезть{}, // Предприятие ввезло товар в страну rus_verbs:ввернуть{}, // Вверни новую лампочку в люстру rus_verbs:ввернуться{}, // Лампочка легко ввернулась в патрон rus_verbs:ввертывать{}, // Электрик ввертывает лампочку в патрон rus_verbs:ввертываться{}, // Лампочка легко ввертывается в патрон rus_verbs:вверять{}, // Пациент вверяет свою жизнь в руки врача rus_verbs:вверяться{}, // Пациент вверяется в руки врача rus_verbs:ввести{}, // Агенство ввело своего представителя в совет директоров rus_verbs:ввиваться{}, // полоска ввивается в косу rus_verbs:ввинтить{}, // Отвертка ввинтила шуруп в дерево rus_verbs:ввинтиться{}, // Шуруп ввинтился в дерево rus_verbs:ввинчивать{}, // Рука ввинчивает саморез в стену rus_verbs:ввинчиваться{}, // Саморез ввинчивается в стену rus_verbs:вводить{}, // Агенство вводит своего представителя в совет директоров rus_verbs:вводиться{}, // Представитель агенства вводится в совет директоров // rus_verbs:ввозить{}, // Фирма ввозит в страну станки и сырье rus_verbs:ввозиться{}, // Станки и сырье ввозятся в страну rus_verbs:вволакивать{}, // Пойманная мышь вволакивается котиком в дом rus_verbs:вворачивать{}, // Электрик вворачивает новую лампочку в патрон rus_verbs:вворачиваться{}, // Новая лампочка легко вворачивается в патрон rus_verbs:ввязаться{}, // Разведрота ввязалась в бой rus_verbs:ввязываться{}, // Передовые части ввязываются в бой rus_verbs:вглядеться{}, // Охранник вгляделся в темный коридор rus_verbs:вглядываться{}, // Охранник внимательно вглядывается в монитор rus_verbs:вгонять{}, // Эта музыка вгоняет меня в депрессию rus_verbs:вгрызаться{}, // Зонд вгрызается в поверхность астероида rus_verbs:вгрызться{}, // Зонд вгрызся в поверхность астероида rus_verbs:вдаваться{}, // Вы не должны вдаваться в юридические детали rus_verbs:вдвигать{}, // Робот вдвигает контейнер в ячейку rus_verbs:вдвигаться{}, // Контейнер вдвигается в ячейку rus_verbs:вдвинуть{}, // манипулятор вдвинул деталь в печь rus_verbs:вдвинуться{}, // деталь вдвинулась в печь rus_verbs:вдевать{}, // портниха быстро вдевает нитку в иголку rus_verbs:вдеваться{}, // нитка быстро вдевается в игольное ушко rus_verbs:вдеть{}, // портниха быстро вдела нитку в игольное ушко rus_verbs:вдеться{}, // нитка быстро вделась в игольное ушко rus_verbs:вделать{}, // мастер вделал розетку в стену rus_verbs:вделывать{}, // мастер вделывает выключатель в стену rus_verbs:вделываться{}, // кронштейн вделывается в стену rus_verbs:вдергиваться{}, // нитка легко вдергивается в игольное ушко rus_verbs:вдернуться{}, // нитка легко вдернулась в игольное ушко rus_verbs:вдолбить{}, // Американцы обещали вдолбить страну в каменный век rus_verbs:вдумываться{}, // Мальчик обычно не вдумывался в сюжет фильмов rus_verbs:вдыхать{}, // мы вдыхаем в себя весь этот смог rus_verbs:вдыхаться{}, // Весь этот смог вдыхается в легкие rus_verbs:вернуть{}, // Книгу надо вернуть в библиотеку rus_verbs:вернуться{}, // Дети вернулись в библиотеку rus_verbs:вжаться{}, // Водитель вжался в кресло rus_verbs:вживаться{}, // Актер вживается в новую роль rus_verbs:вживить{}, // Врачи вживили стимулятор в тело пациента rus_verbs:вживиться{}, // Стимулятор вживился в тело пациента rus_verbs:вживлять{}, // Врачи вживляют стимулятор в тело пациента rus_verbs:вживляться{}, // Стимулятор вживляется в тело rus_verbs:вжиматься{}, // Видитель инстинктивно вжимается в кресло rus_verbs:вжиться{}, // Актер вжился в свою новую роль rus_verbs:взвиваться{}, // Воздушный шарик взвивается в небо rus_verbs:взвинтить{}, // Кризис взвинтил цены в небо rus_verbs:взвинтиться{}, // Цены взвинтились в небо rus_verbs:взвинчивать{}, // Кризис взвинчивает цены в небо rus_verbs:взвинчиваться{}, // Цены взвинчиваются в небо rus_verbs:взвиться{}, // Шарики взвились в небо rus_verbs:взлетать{}, // Экспериментальный аппарат взлетает в воздух rus_verbs:взлететь{}, // Экспериментальный аппарат взлетел в небо rus_verbs:взмывать{}, // шарики взмывают в небо rus_verbs:взмыть{}, // Шарики взмыли в небо rus_verbs:вильнуть{}, // Машина вильнула в левую сторону rus_verbs:вкалывать{}, // Медсестра вкалывает иглу в вену rus_verbs:вкалываться{}, // Игла вкалываться прямо в вену rus_verbs:вкапывать{}, // рабочий вкапывает сваю в землю rus_verbs:вкапываться{}, // Свая вкапывается в землю rus_verbs:вкатить{}, // рабочие вкатили бочку в гараж rus_verbs:вкатиться{}, // машина вкатилась в гараж rus_verbs:вкатывать{}, // рабочик вкатывают бочку в гараж rus_verbs:вкатываться{}, // машина вкатывается в гараж rus_verbs:вкачать{}, // Механики вкачали в бак много топлива rus_verbs:вкачивать{}, // Насос вкачивает топливо в бак rus_verbs:вкачиваться{}, // Топливо вкачивается в бак rus_verbs:вкидать{}, // Манипулятор вкидал груз в контейнер rus_verbs:вкидывать{}, // Манипулятор вкидывает груз в контейнер rus_verbs:вкидываться{}, // Груз вкидывается в контейнер rus_verbs:вкладывать{}, // Инвестор вкладывает деньги в акции rus_verbs:вкладываться{}, // Инвестор вкладывается в акции rus_verbs:вклеивать{}, // Мальчик вклеивает картинку в тетрадь rus_verbs:вклеиваться{}, // Картинка вклеивается в тетрадь rus_verbs:вклеить{}, // Мальчик вклеил картинку в тетрадь rus_verbs:вклеиться{}, // Картинка вклеилась в тетрадь rus_verbs:вклепать{}, // Молоток вклепал заклепку в лист rus_verbs:вклепывать{}, // Молоток вклепывает заклепку в лист rus_verbs:вклиниваться{}, // Машина вклинивается в поток rus_verbs:вклиниться{}, // машина вклинилась в поток rus_verbs:включать{}, // Команда включает компьютер в сеть rus_verbs:включаться{}, // Машина включается в глобальную сеть rus_verbs:включить{}, // Команда включила компьютер в сеть rus_verbs:включиться{}, // Компьютер включился в сеть rus_verbs:вколачивать{}, // Столяр вколачивает гвоздь в доску rus_verbs:вколачиваться{}, // Гвоздь вколачивается в доску rus_verbs:вколотить{}, // Столяр вколотил гвоздь в доску rus_verbs:вколоть{}, // Медсестра вколола в мышцу лекарство rus_verbs:вкопать{}, // Рабочие вкопали сваю в землю rus_verbs:вкрадываться{}, // Ошибка вкрадывается в расчеты rus_verbs:вкраивать{}, // Портниха вкраивает вставку в юбку rus_verbs:вкраиваться{}, // Вставка вкраивается в юбку rus_verbs:вкрасться{}, // Ошибка вкралась в расчеты rus_verbs:вкрутить{}, // Электрик вкрутил лампочку в патрон rus_verbs:вкрутиться{}, // лампочка легко вкрутилась в патрон rus_verbs:вкручивать{}, // Электрик вкручивает лампочку в патрон rus_verbs:вкручиваться{}, // Лампочка легко вкручивается в патрон rus_verbs:влазить{}, // Разъем влазит в отверствие rus_verbs:вламывать{}, // Полиция вламывается в квартиру rus_verbs:влетать{}, // Самолет влетает в грозовой фронт rus_verbs:влететь{}, // Самолет влетел в грозовой фронт rus_verbs:вливать{}, // Механик вливает масло в картер rus_verbs:вливаться{}, // Масло вливается в картер rus_verbs:влипать{}, // Эти неудачники постоянно влипают в разные происшествия rus_verbs:влипнуть{}, // Эти неудачники опять влипли в неприятности rus_verbs:влить{}, // Механик влил свежее масло в картер rus_verbs:влиться{}, // Свежее масло влилось в бак rus_verbs:вложить{}, // Инвесторы вложили в эти акции большие средства rus_verbs:вложиться{}, // Инвесторы вложились в эти акции rus_verbs:влюбиться{}, // Коля влюбился в Олю rus_verbs:влюблять{}, // Оля постоянно влюбляла в себя мальчиков rus_verbs:влюбляться{}, // Оля влюбляется в спортсменов rus_verbs:вляпаться{}, // Коля вляпался в неприятность rus_verbs:вляпываться{}, // Коля постоянно вляпывается в неприятности rus_verbs:вменить{}, // вменить в вину rus_verbs:вменять{}, // вменять в обязанность rus_verbs:вмерзать{}, // Колеса вмерзают в лед rus_verbs:вмерзнуть{}, // Колеса вмерзли в лед rus_verbs:вмести{}, // вмести в дом rus_verbs:вместить{}, // вместить в ёмкость rus_verbs:вместиться{}, // Прибор не вместился в зонд rus_verbs:вмешаться{}, // Начальник вмешался в конфликт rus_verbs:вмешивать{}, // Не вмешивай меня в это дело rus_verbs:вмешиваться{}, // Начальник вмешивается в переговоры rus_verbs:вмещаться{}, // Приборы не вмещаются в корпус rus_verbs:вминать{}, // вминать в корпус rus_verbs:вминаться{}, // кронштейн вминается в корпус rus_verbs:вмонтировать{}, // Конструкторы вмонтировали в корпус зонда новые приборы rus_verbs:вмонтироваться{}, // Новые приборы легко вмонтировались в корпус зонда rus_verbs:вмораживать{}, // Установка вмораживает сваи в грунт rus_verbs:вмораживаться{}, // Сваи вмораживаются в грунт rus_verbs:вморозить{}, // Установка вморозила сваи в грунт rus_verbs:вмуровать{}, // Сейф был вмурован в стену rus_verbs:вмуровывать{}, // вмуровывать сейф в стену rus_verbs:вмуровываться{}, // сейф вмуровывается в бетонную стену rus_verbs:внедрить{}, // внедрить инновацию в производство rus_verbs:внедриться{}, // Шпион внедрился в руководство rus_verbs:внедрять{}, // внедрять инновации в производство rus_verbs:внедряться{}, // Шпионы внедряются в руководство rus_verbs:внести{}, // внести коробку в дом rus_verbs:внестись{}, // внестись в список приглашенных гостей rus_verbs:вникать{}, // Разработчик вникает в детали задачи rus_verbs:вникнуть{}, // Дизайнер вник в детали задачи rus_verbs:вносить{}, // вносить новое действующее лицо в список главных героев rus_verbs:вноситься{}, // вноситься в список главных персонажей rus_verbs:внюхаться{}, // Пёс внюхался в ароматы леса rus_verbs:внюхиваться{}, // Пёс внюхивается в ароматы леса rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями rus_verbs:вовлекать{}, // вовлекать трудных подростков в занятие спортом rus_verbs:вогнать{}, // вогнал человека в тоску rus_verbs:водворить{}, // водворить преступника в тюрьму rus_verbs:возвернуть{}, // возвернуть в родную стихию rus_verbs:возвернуться{}, // возвернуться в родную стихию rus_verbs:возвести{}, // возвести число в четную степень rus_verbs:возводить{}, // возводить число в четную степень rus_verbs:возводиться{}, // число возводится в четную степень rus_verbs:возвратить{}, // возвратить коров в стойло rus_verbs:возвратиться{}, // возвратиться в родной дом rus_verbs:возвращать{}, // возвращать коров в стойло rus_verbs:возвращаться{}, // возвращаться в родной дом rus_verbs:войти{}, // войти в галерею славы rus_verbs:вонзать{}, // Коля вонзает вилку в котлету rus_verbs:вонзаться{}, // Вилка вонзается в котлету rus_verbs:вонзить{}, // Коля вонзил вилку в котлету rus_verbs:вонзиться{}, // Вилка вонзилась в сочную котлету rus_verbs:воплотить{}, // Коля воплотил свои мечты в реальность rus_verbs:воплотиться{}, // Мечты воплотились в реальность rus_verbs:воплощать{}, // Коля воплощает мечты в реальность rus_verbs:воплощаться{}, // Мечты иногда воплощаются в реальность rus_verbs:ворваться{}, // Перемены неожиданно ворвались в размеренную жизнь rus_verbs:воспарить{}, // Душа воспарила в небо rus_verbs:воспарять{}, // Душа воспаряет в небо rus_verbs:врыть{}, // врыть опору в землю rus_verbs:врыться{}, // врыться в землю rus_verbs:всадить{}, // всадить пулю в сердце rus_verbs:всаживать{}, // всаживать нож в бок rus_verbs:всасывать{}, // всасывать воду в себя rus_verbs:всасываться{}, // всасываться в ёмкость rus_verbs:вселить{}, // вселить надежду в кого-либо rus_verbs:вселиться{}, // вселиться в пустующее здание rus_verbs:вселять{}, // вселять надежду в кого-то rus_verbs:вселяться{}, // вселяться в пустующее здание rus_verbs:вскидывать{}, // вскидывать руку в небо rus_verbs:вскинуть{}, // вскинуть руку в небо rus_verbs:вслушаться{}, // вслушаться в звуки rus_verbs:вслушиваться{}, // вслушиваться в шорох rus_verbs:всматриваться{}, // всматриваться в темноту rus_verbs:всмотреться{}, // всмотреться в темень rus_verbs:всовывать{}, // всовывать палец в отверстие rus_verbs:всовываться{}, // всовываться в форточку rus_verbs:всосать{}, // всосать жидкость в себя rus_verbs:всосаться{}, // всосаться в кожу rus_verbs:вставить{}, // вставить ключ в замок rus_verbs:вставлять{}, // вставлять ключ в замок rus_verbs:встраивать{}, // встраивать черный ход в систему защиты rus_verbs:встраиваться{}, // встраиваться в систему безопасности rus_verbs:встревать{}, // встревать в разговор rus_verbs:встроить{}, // встроить секретный модуль в систему безопасности rus_verbs:встроиться{}, // встроиться в систему безопасности rus_verbs:встрять{}, // встрять в разговор rus_verbs:вступать{}, // вступать в действующую армию rus_verbs:вступить{}, // вступить в действующую армию rus_verbs:всунуть{}, // всунуть палец в отверстие rus_verbs:всунуться{}, // всунуться в форточку инфинитив:всыпать{вид:соверш}, // всыпать порошок в контейнер инфинитив:всыпать{вид:несоверш}, глагол:всыпать{вид:соверш}, глагол:всыпать{вид:несоверш}, деепричастие:всыпав{}, деепричастие:всыпая{}, прилагательное:всыпавший{ вид:соверш }, // прилагательное:всыпавший{ вид:несоверш }, прилагательное:всыпанный{}, // прилагательное:всыпающий{}, инфинитив:всыпаться{ вид:несоверш}, // всыпаться в контейнер // инфинитив:всыпаться{ вид:соверш}, // глагол:всыпаться{ вид:соверш}, глагол:всыпаться{ вид:несоверш}, // деепричастие:всыпавшись{}, деепричастие:всыпаясь{}, // прилагательное:всыпавшийся{ вид:соверш }, // прилагательное:всыпавшийся{ вид:несоверш }, // прилагательное:всыпающийся{}, rus_verbs:вталкивать{}, // вталкивать деталь в ячейку rus_verbs:вталкиваться{}, // вталкиваться в ячейку rus_verbs:втаптывать{}, // втаптывать в грязь rus_verbs:втаптываться{}, // втаптываться в грязь rus_verbs:втаскивать{}, // втаскивать мешок в комнату rus_verbs:втаскиваться{}, // втаскиваться в комнату rus_verbs:втащить{}, // втащить мешок в комнату rus_verbs:втащиться{}, // втащиться в комнату rus_verbs:втекать{}, // втекать в бутылку rus_verbs:втемяшивать{}, // втемяшивать в голову rus_verbs:втемяшиваться{}, // втемяшиваться в голову rus_verbs:втемяшить{}, // втемяшить в голову rus_verbs:втемяшиться{}, // втемяшиться в голову rus_verbs:втереть{}, // втереть крем в кожу rus_verbs:втереться{}, // втереться в кожу rus_verbs:втесаться{}, // втесаться в группу rus_verbs:втесывать{}, // втесывать в группу rus_verbs:втесываться{}, // втесываться в группу rus_verbs:втечь{}, // втечь в бак rus_verbs:втирать{}, // втирать крем в кожу rus_verbs:втираться{}, // втираться в кожу rus_verbs:втискивать{}, // втискивать сумку в вагон rus_verbs:втискиваться{}, // втискиваться в переполненный вагон rus_verbs:втиснуть{}, // втиснуть сумку в вагон rus_verbs:втиснуться{}, // втиснуться в переполненный вагон метро rus_verbs:втолкать{}, // втолкать коляску в лифт rus_verbs:втолкаться{}, // втолкаться в вагон метро rus_verbs:втолкнуть{}, // втолкнуть коляску в лифт rus_verbs:втолкнуться{}, // втолкнуться в вагон метро rus_verbs:втолочь{}, // втолочь в смесь rus_verbs:втоптать{}, // втоптать цветы в землю rus_verbs:вторгаться{}, // вторгаться в чужую зону rus_verbs:вторгнуться{}, // вторгнуться в частную жизнь rus_verbs:втравить{}, // втравить кого-то в неприятности rus_verbs:втравливать{}, // втравливать кого-то в неприятности rus_verbs:втрамбовать{}, // втрамбовать камни в землю rus_verbs:втрамбовывать{}, // втрамбовывать камни в землю rus_verbs:втрамбовываться{}, // втрамбовываться в землю rus_verbs:втрескаться{}, // втрескаться в кого-то rus_verbs:втрескиваться{}, // втрескиваться в кого-либо rus_verbs:втыкать{}, // втыкать вилку в котлетку rus_verbs:втыкаться{}, // втыкаться в розетку rus_verbs:втюриваться{}, // втюриваться в кого-либо rus_verbs:втюриться{}, // втюриться в кого-либо rus_verbs:втягивать{}, // втягивать что-то в себя rus_verbs:втягиваться{}, // втягиваться в себя rus_verbs:втянуться{}, // втянуться в себя rus_verbs:вцементировать{}, // вцементировать сваю в фундамент rus_verbs:вчеканить{}, // вчеканить надпись в лист rus_verbs:вчитаться{}, // вчитаться внимательнее в текст rus_verbs:вчитываться{}, // вчитываться внимательнее в текст rus_verbs:вчувствоваться{}, // вчувствоваться в роль rus_verbs:вшагивать{}, // вшагивать в новую жизнь rus_verbs:вшагнуть{}, // вшагнуть в новую жизнь rus_verbs:вшивать{}, // вшивать заплату в рубашку rus_verbs:вшиваться{}, // вшиваться в ткань rus_verbs:вшить{}, // вшить заплату в ткань rus_verbs:въедаться{}, // въедаться в мякоть rus_verbs:въезжать{}, // въезжать в гараж rus_verbs:въехать{}, // въехать в гараж rus_verbs:выиграть{}, // Коля выиграл в шахматы rus_verbs:выигрывать{}, // Коля часто выигрывает у меня в шахматы rus_verbs:выкладывать{}, // выкладывать в общий доступ rus_verbs:выкладываться{}, // выкладываться в общий доступ rus_verbs:выкрасить{}, // выкрасить машину в розовый цвет rus_verbs:выкраситься{}, // выкраситься в дерзкий розовый цвет rus_verbs:выкрашивать{}, // выкрашивать волосы в красный цвет rus_verbs:выкрашиваться{}, // выкрашиваться в красный цвет rus_verbs:вылезать{}, // вылезать в открытое пространство rus_verbs:вылезти{}, // вылезти в открытое пространство rus_verbs:выливать{}, // выливать в бутылку rus_verbs:выливаться{}, // выливаться в ёмкость rus_verbs:вылить{}, // вылить отходы в канализацию rus_verbs:вылиться{}, // Топливо вылилось в воду rus_verbs:выложить{}, // выложить в общий доступ rus_verbs:выпадать{}, // выпадать в осадок rus_verbs:выпрыгивать{}, // выпрыгивать в окно rus_verbs:выпрыгнуть{}, // выпрыгнуть в окно rus_verbs:выродиться{}, // выродиться в жалкое подобие rus_verbs:вырождаться{}, // вырождаться в жалкое подобие славных предков rus_verbs:высеваться{}, // высеваться в землю rus_verbs:высеять{}, // высеять в землю rus_verbs:выслать{}, // выслать в страну постоянного пребывания rus_verbs:высморкаться{}, // высморкаться в платок rus_verbs:высморкнуться{}, // высморкнуться в платок rus_verbs:выстреливать{}, // выстреливать в цель rus_verbs:выстреливаться{}, // выстреливаться в цель rus_verbs:выстрелить{}, // выстрелить в цель rus_verbs:вытекать{}, // вытекать в озеро rus_verbs:вытечь{}, // вытечь в воду rus_verbs:смотреть{}, // смотреть в будущее rus_verbs:подняться{}, // подняться в лабораторию rus_verbs:послать{}, // послать в магазин rus_verbs:слать{}, // слать в неизвестность rus_verbs:добавить{}, // добавить в суп rus_verbs:пройти{}, // пройти в лабораторию rus_verbs:положить{}, // положить в ящик rus_verbs:прислать{}, // прислать в полицию rus_verbs:упасть{}, // упасть в пропасть инфинитив:писать{ aux stress="пис^ать" }, // писать в газету инфинитив:писать{ aux stress="п^исать" }, // писать в штанишки глагол:писать{ aux stress="п^исать" }, глагол:писать{ aux stress="пис^ать" }, деепричастие:писая{}, прилагательное:писавший{ aux stress="п^исавший" }, // писавший в штанишки прилагательное:писавший{ aux stress="пис^авший" }, // писавший в газету rus_verbs:собираться{}, // собираться в поход rus_verbs:звать{}, // звать в ресторан rus_verbs:направиться{}, // направиться в ресторан rus_verbs:отправиться{}, // отправиться в ресторан rus_verbs:поставить{}, // поставить в угол rus_verbs:целить{}, // целить в мишень rus_verbs:попасть{}, // попасть в переплет rus_verbs:ударить{}, // ударить в больное место rus_verbs:закричать{}, // закричать в микрофон rus_verbs:опустить{}, // опустить в воду rus_verbs:принести{}, // принести в дом бездомного щенка rus_verbs:отдать{}, // отдать в хорошие руки rus_verbs:ходить{}, // ходить в школу rus_verbs:уставиться{}, // уставиться в экран rus_verbs:приходить{}, // приходить в бешенство rus_verbs:махнуть{}, // махнуть в Италию rus_verbs:сунуть{}, // сунуть в замочную скважину rus_verbs:явиться{}, // явиться в расположение части rus_verbs:уехать{}, // уехать в город rus_verbs:целовать{}, // целовать в лобик rus_verbs:повести{}, // повести в бой rus_verbs:опуститься{}, // опуститься в кресло rus_verbs:передать{}, // передать в архив rus_verbs:побежать{}, // побежать в школу rus_verbs:стечь{}, // стечь в воду rus_verbs:уходить{}, // уходить добровольцем в армию rus_verbs:привести{}, // привести в дом rus_verbs:шагнуть{}, // шагнуть в неизвестность rus_verbs:собраться{}, // собраться в поход rus_verbs:заглянуть{}, // заглянуть в основу rus_verbs:поспешить{}, // поспешить в церковь rus_verbs:поцеловать{}, // поцеловать в лоб rus_verbs:перейти{}, // перейти в высшую лигу rus_verbs:поверить{}, // поверить в искренность rus_verbs:глянуть{}, // глянуть в оглавление rus_verbs:зайти{}, // зайти в кафетерий rus_verbs:подобрать{}, // подобрать в лесу rus_verbs:проходить{}, // проходить в помещение rus_verbs:глядеть{}, // глядеть в глаза rus_verbs:пригласить{}, // пригласить в театр rus_verbs:позвать{}, // позвать в класс rus_verbs:усесться{}, // усесться в кресло rus_verbs:поступить{}, // поступить в институт rus_verbs:лечь{}, // лечь в постель rus_verbs:поклониться{}, // поклониться в пояс rus_verbs:потянуться{}, // потянуться в лес rus_verbs:колоть{}, // колоть в ягодицу rus_verbs:присесть{}, // присесть в кресло rus_verbs:оглядеться{}, // оглядеться в зеркало rus_verbs:поглядеть{}, // поглядеть в зеркало rus_verbs:превратиться{}, // превратиться в лягушку rus_verbs:принимать{}, // принимать во внимание rus_verbs:звонить{}, // звонить в колокола rus_verbs:привезти{}, // привезти в гостиницу rus_verbs:рухнуть{}, // рухнуть в пропасть rus_verbs:пускать{}, // пускать в дело rus_verbs:отвести{}, // отвести в больницу rus_verbs:сойти{}, // сойти в ад rus_verbs:набрать{}, // набрать в команду rus_verbs:собрать{}, // собрать в кулак rus_verbs:двигаться{}, // двигаться в каюту rus_verbs:падать{}, // падать в область нуля rus_verbs:полезть{}, // полезть в драку rus_verbs:направить{}, // направить в стационар rus_verbs:приводить{}, // приводить в чувство rus_verbs:толкнуть{}, // толкнуть в бок rus_verbs:кинуться{}, // кинуться в драку rus_verbs:ткнуть{}, // ткнуть в глаз rus_verbs:заключить{}, // заключить в объятия rus_verbs:подниматься{}, // подниматься в небо rus_verbs:расти{}, // расти в глубину rus_verbs:налить{}, // налить в кружку rus_verbs:швырнуть{}, // швырнуть в бездну rus_verbs:прыгнуть{}, // прыгнуть в дверь rus_verbs:промолчать{}, // промолчать в тряпочку rus_verbs:садиться{}, // садиться в кресло rus_verbs:лить{}, // лить в кувшин rus_verbs:дослать{}, // дослать деталь в держатель rus_verbs:переслать{}, // переслать в обработчик rus_verbs:удалиться{}, // удалиться в совещательную комнату rus_verbs:разглядывать{}, // разглядывать в бинокль rus_verbs:повесить{}, // повесить в шкаф инфинитив:походить{ вид:соверш }, // походить в институт глагол:походить{ вид:соверш }, деепричастие:походив{}, // прилагательное:походивший{вид:соверш}, rus_verbs:помчаться{}, // помчаться в класс rus_verbs:свалиться{}, // свалиться в яму rus_verbs:сбежать{}, // сбежать в Англию rus_verbs:стрелять{}, // стрелять в цель rus_verbs:обращать{}, // обращать в свою веру rus_verbs:завести{}, // завести в дом rus_verbs:приобрести{}, // приобрести в рассрочку rus_verbs:сбросить{}, // сбросить в яму rus_verbs:устроиться{}, // устроиться в крупную корпорацию rus_verbs:погрузиться{}, // погрузиться в пучину rus_verbs:течь{}, // течь в канаву rus_verbs:произвести{}, // произвести в звание майора rus_verbs:метать{}, // метать в цель rus_verbs:пустить{}, // пустить в дело rus_verbs:полететь{}, // полететь в Европу rus_verbs:пропустить{}, // пропустить в здание rus_verbs:рвануть{}, // рвануть в отпуск rus_verbs:заходить{}, // заходить в каморку rus_verbs:нырнуть{}, // нырнуть в прорубь rus_verbs:рвануться{}, // рвануться в атаку rus_verbs:приподняться{}, // приподняться в воздух rus_verbs:превращаться{}, // превращаться в крупную величину rus_verbs:прокричать{}, // прокричать в ухо rus_verbs:записать{}, // записать в блокнот rus_verbs:забраться{}, // забраться в шкаф rus_verbs:приезжать{}, // приезжать в деревню rus_verbs:продать{}, // продать в рабство rus_verbs:проникнуть{}, // проникнуть в центр rus_verbs:устремиться{}, // устремиться в открытое море rus_verbs:посадить{}, // посадить в кресло rus_verbs:упереться{}, // упереться в пол rus_verbs:ринуться{}, // ринуться в буфет rus_verbs:отдавать{}, // отдавать в кадетское училище rus_verbs:отложить{}, // отложить в долгий ящик rus_verbs:убежать{}, // убежать в приют rus_verbs:оценить{}, // оценить в миллион долларов rus_verbs:поднимать{}, // поднимать в стратосферу rus_verbs:отослать{}, // отослать в квалификационную комиссию rus_verbs:отодвинуть{}, // отодвинуть в дальний угол rus_verbs:торопиться{}, // торопиться в школу rus_verbs:попадаться{}, // попадаться в руки rus_verbs:поразить{}, // поразить в самое сердце rus_verbs:доставить{}, // доставить в квартиру rus_verbs:заслать{}, // заслать в тыл rus_verbs:сослать{}, // сослать в изгнание rus_verbs:запустить{}, // запустить в космос rus_verbs:удариться{}, // удариться в запой rus_verbs:ударяться{}, // ударяться в крайность rus_verbs:шептать{}, // шептать в лицо rus_verbs:уронить{}, // уронить в унитаз rus_verbs:прорычать{}, // прорычать в микрофон rus_verbs:засунуть{}, // засунуть в глотку rus_verbs:плыть{}, // плыть в открытое море rus_verbs:перенести{}, // перенести в духовку rus_verbs:светить{}, // светить в лицо rus_verbs:мчаться{}, // мчаться в ремонт rus_verbs:стукнуть{}, // стукнуть в лоб rus_verbs:обрушиться{}, // обрушиться в котлован rus_verbs:поглядывать{}, // поглядывать в экран rus_verbs:уложить{}, // уложить в кроватку инфинитив:попадать{ вид:несоверш }, // попадать в черный список глагол:попадать{ вид:несоверш }, прилагательное:попадающий{ вид:несоверш }, прилагательное:попадавший{ вид:несоверш }, деепричастие:попадая{}, rus_verbs:провалиться{}, // провалиться в яму rus_verbs:жаловаться{}, // жаловаться в комиссию rus_verbs:опоздать{}, // опоздать в школу rus_verbs:посылать{}, // посылать в парикмахерскую rus_verbs:погнать{}, // погнать в хлев rus_verbs:поступать{}, // поступать в институт rus_verbs:усадить{}, // усадить в кресло rus_verbs:проиграть{}, // проиграть в рулетку rus_verbs:прилететь{}, // прилететь в страну rus_verbs:повалиться{}, // повалиться в траву rus_verbs:огрызнуться{}, // Собака огрызнулась в ответ rus_verbs:лезть{}, // лезть в чужие дела rus_verbs:потащить{}, // потащить в суд rus_verbs:направляться{}, // направляться в порт rus_verbs:поползти{}, // поползти в другую сторону rus_verbs:пуститься{}, // пуститься в пляс rus_verbs:забиться{}, // забиться в нору rus_verbs:залезть{}, // залезть в конуру rus_verbs:сдать{}, // сдать в утиль rus_verbs:тронуться{}, // тронуться в путь rus_verbs:сыграть{}, // сыграть в шахматы rus_verbs:перевернуть{}, // перевернуть в более удобную позу rus_verbs:сжимать{}, // сжимать пальцы в кулак rus_verbs:подтолкнуть{}, // подтолкнуть в бок rus_verbs:отнести{}, // отнести животное в лечебницу rus_verbs:одеться{}, // одеться в зимнюю одежду rus_verbs:плюнуть{}, // плюнуть в колодец rus_verbs:передавать{}, // передавать в прокуратуру rus_verbs:отскочить{}, // отскочить в лоб rus_verbs:призвать{}, // призвать в армию rus_verbs:увезти{}, // увезти в деревню rus_verbs:улечься{}, // улечься в кроватку rus_verbs:отшатнуться{}, // отшатнуться в сторону rus_verbs:ложиться{}, // ложиться в постель rus_verbs:пролететь{}, // пролететь в конец rus_verbs:класть{}, // класть в сейф rus_verbs:доставлять{}, // доставлять в кабинет rus_verbs:приобретать{}, // приобретать в кредит rus_verbs:сводить{}, // сводить в театр rus_verbs:унести{}, // унести в могилу rus_verbs:покатиться{}, // покатиться в яму rus_verbs:сходить{}, // сходить в магазинчик rus_verbs:спустить{}, // спустить в канализацию rus_verbs:проникать{}, // проникать в сердцевину rus_verbs:метнуть{}, // метнуть в болвана гневный взгляд rus_verbs:пожаловаться{}, // пожаловаться в администрацию rus_verbs:стучать{}, // стучать в металлическую дверь rus_verbs:тащить{}, // тащить в ремонт rus_verbs:заглядывать{}, // заглядывать в ответы rus_verbs:плюхнуться{}, // плюхнуться в стол ароматного сена rus_verbs:увести{}, // увести в следующий кабинет rus_verbs:успевать{}, // успевать в школу rus_verbs:пробраться{}, // пробраться в собачью конуру rus_verbs:подавать{}, // подавать в суд rus_verbs:прибежать{}, // прибежать в конюшню rus_verbs:рассмотреть{}, // рассмотреть в микроскоп rus_verbs:пнуть{}, // пнуть в живот rus_verbs:завернуть{}, // завернуть в декоративную пленку rus_verbs:уезжать{}, // уезжать в деревню rus_verbs:привлекать{}, // привлекать в свои ряды rus_verbs:перебраться{}, // перебраться в прибрежный город rus_verbs:долить{}, // долить в коктейль rus_verbs:палить{}, // палить в нападающих rus_verbs:отобрать{}, // отобрать в коллекцию rus_verbs:улететь{}, // улететь в неизвестность rus_verbs:выглянуть{}, // выглянуть в окно rus_verbs:выглядывать{}, // выглядывать в окно rus_verbs:пробираться{}, // грабитель, пробирающийся в дом инфинитив:написать{ aux stress="напис^ать"}, // читатель, написавший в блог глагол:написать{ aux stress="напис^ать"}, прилагательное:написавший{ aux stress="напис^авший"}, rus_verbs:свернуть{}, // свернуть в колечко инфинитив:сползать{ вид:несоверш }, // сползать в овраг глагол:сползать{ вид:несоверш }, прилагательное:сползающий{ вид:несоверш }, прилагательное:сползавший{ вид:несоверш }, rus_verbs:барабанить{}, // барабанить в дверь rus_verbs:дописывать{}, // дописывать в конец rus_verbs:меняться{}, // меняться в лучшую сторону rus_verbs:измениться{}, // измениться в лучшую сторону rus_verbs:изменяться{}, // изменяться в лучшую сторону rus_verbs:вписаться{}, // вписаться в поворот rus_verbs:вписываться{}, // вписываться в повороты rus_verbs:переработать{}, // переработать в удобрение rus_verbs:перерабатывать{}, // перерабатывать в удобрение rus_verbs:уползать{}, // уползать в тень rus_verbs:заползать{}, // заползать в нору rus_verbs:перепрятать{}, // перепрятать в укромное место rus_verbs:заталкивать{}, // заталкивать в вагон rus_verbs:преобразовывать{}, // преобразовывать в список инфинитив:конвертировать{ вид:несоверш }, // конвертировать в список глагол:конвертировать{ вид:несоверш }, инфинитив:конвертировать{ вид:соверш }, глагол:конвертировать{ вид:соверш }, деепричастие:конвертировав{}, деепричастие:конвертируя{}, rus_verbs:изорвать{}, // Он изорвал газету в клочки. rus_verbs:выходить{}, // Окна выходят в сад. rus_verbs:говорить{}, // Он говорил в защиту своего отца. rus_verbs:вырастать{}, // Он вырастает в большого художника. rus_verbs:вывести{}, // Он вывел детей в сад. // инфинитив:всыпать{ вид:соверш }, инфинитив:всыпать{ вид:несоверш }, // глагол:всыпать{ вид:соверш }, глагол:всыпать{ вид:несоверш }, // Он всыпал в воду две ложки соли. // прилагательное:раненый{}, // Он был ранен в левую руку. // прилагательное:одетый{}, // Он был одет в толстое осеннее пальто. rus_verbs:бухнуться{}, // Он бухнулся в воду. rus_verbs:склонять{}, // склонять защиту в свою пользу rus_verbs:впиться{}, // Пиявка впилась в тело. rus_verbs:сходиться{}, // Интеллигенты начала века часто сходились в разные союзы rus_verbs:сохранять{}, // сохранить данные в файл rus_verbs:собирать{}, // собирать игрушки в ящик rus_verbs:упаковывать{}, // упаковывать вещи в чемодан rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время rus_verbs:стрельнуть{}, // стрельни в толпу! rus_verbs:пулять{}, // пуляй в толпу rus_verbs:пульнуть{}, // пульни в толпу rus_verbs:становиться{}, // Становитесь в очередь. rus_verbs:вписать{}, // Юля вписала свое имя в список. rus_verbs:вписывать{}, // Мы вписывали свои имена в список прилагательное:видный{}, // Планета Марс видна в обычный бинокль rus_verbs:пойти{}, // Девочка рано пошла в школу rus_verbs:отойти{}, // Эти обычаи отошли в историю. rus_verbs:бить{}, // Холодный ветер бил ему в лицо. rus_verbs:входить{}, // Это входит в его обязанности. rus_verbs:принять{}, // меня приняли в пионеры rus_verbs:уйти{}, // Правительство РФ ушло в отставку rus_verbs:допустить{}, // Япония была допущена в Организацию Объединённых Наций в 1956 году. rus_verbs:посвятить{}, // Я посвятил друга в свою тайну. инфинитив:экспортировать{ вид:несоверш }, глагол:экспортировать{ вид:несоверш }, // экспортировать нефть в страны Востока rus_verbs:взглянуть{}, // Я не смел взглянуть ему в глаза. rus_verbs:идти{}, // Я иду гулять в парк. rus_verbs:вскочить{}, // Я вскочил в трамвай и помчался в институт. rus_verbs:получить{}, // Эту мебель мы получили в наследство от родителей. rus_verbs:везти{}, // Учитель везёт детей в лагерь. rus_verbs:качать{}, // Судно качает во все стороны. rus_verbs:заезжать{}, // Сегодня вечером я заезжал в магазин за книгами. rus_verbs:связать{}, // Свяжите свои вещи в узелок. rus_verbs:пронести{}, // Пронесите стол в дверь. rus_verbs:вынести{}, // Надо вынести примечания в конец. rus_verbs:устроить{}, // Она устроила сына в школу. rus_verbs:угодить{}, // Она угодила головой в дверь. rus_verbs:отвернуться{}, // Она резко отвернулась в сторону. rus_verbs:рассматривать{}, // Она рассматривала сцену в бинокль. rus_verbs:обратить{}, // Война обратила город в развалины. rus_verbs:сойтись{}, // Мы сошлись в школьные годы. rus_verbs:приехать{}, // Мы приехали в положенный час. rus_verbs:встать{}, // Дети встали в круг. rus_verbs:впасть{}, // Из-за болезни он впал в нужду. rus_verbs:придти{}, // придти в упадок rus_verbs:заявить{}, // Надо заявить в милицию о краже. rus_verbs:заявлять{}, // заявлять в полицию rus_verbs:ехать{}, // Мы будем ехать в Орёл rus_verbs:окрашиваться{}, // окрашиваться в красный цвет rus_verbs:решить{}, // Дело решено в пользу истца. rus_verbs:сесть{}, // Она села в кресло rus_verbs:посмотреть{}, // Она посмотрела на себя в зеркало. rus_verbs:влезать{}, // он влезает в мою квартирку rus_verbs:попасться{}, // в мою ловушку попалась мышь rus_verbs:лететь{}, // Мы летим в Орёл ГЛ_ИНФ(брать), // он берет в свою правую руку очень тяжелый шершавый камень ГЛ_ИНФ(взять), // Коля взял в руку камень ГЛ_ИНФ(поехать), // поехать в круиз ГЛ_ИНФ(подать), // подать в отставку инфинитив:засыпать{ вид:соверш }, глагол:засыпать{ вид:соверш }, // засыпать песок в ящик инфинитив:засыпать{ вид:несоверш переходность:переходный }, глагол:засыпать{ вид:несоверш переходность:переходный }, // засыпать песок в ящик ГЛ_ИНФ(впадать), прилагательное:впадающий{}, прилагательное:впадавший{}, деепричастие:впадая{}, // впадать в море ГЛ_ИНФ(постучать) // постучать в дверь } // Чтобы разрешить связывание в паттернах типа: уйти в BEA Systems fact гл_предл { if context { Гл_В_Вин предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_В_Вин предлог:в{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { глагол:подвывать{} предлог:в{} существительное:такт{ падеж:вин } } then return true } #endregion Винительный // Все остальные варианты по умолчанию запрещаем. fact гл_предл { if context { * предлог:в{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:в{} *:*{ падеж:мест } } then return false,-3 } fact гл_предл { if context { * предлог:в{} *:*{ падеж:вин } } then return false,-4 } fact гл_предл { if context { * предлог:в{} * } then return false,-5 } #endregion Предлог_В #region Предлог_НА // ------------------- С ПРЕДЛОГОМ 'НА' --------------------------- #region ПРЕДЛОЖНЫЙ // НА+предложный падеж: // ЛЕЖАТЬ НА СТОЛЕ #region VerbList wordentry_set Гл_НА_Предл= { rus_verbs:заслушать{}, // Вопрос заслушали на сессии облсовета rus_verbs:ПРОСТУПАТЬ{}, // На лбу, носу и щеке проступало черное пятно кровоподтека. (ПРОСТУПАТЬ/ПРОСТУПИТЬ) rus_verbs:ПРОСТУПИТЬ{}, // rus_verbs:ВИДНЕТЬСЯ{}, // На другой стороне Океана виднелась полоска суши, окружавшая нижний ярус планеты. (ВИДНЕТЬСЯ) rus_verbs:ЗАВИСАТЬ{}, // Машина умела зависать в воздухе на любой высоте (ЗАВИСАТЬ) rus_verbs:ЗАМЕРЕТЬ{}, // Скользнув по траве, он замер на боку (ЗАМЕРЕТЬ, локатив) rus_verbs:ЗАМИРАТЬ{}, // rus_verbs:ЗАКРЕПИТЬ{}, // Он вручил ей лишний кинжал, который она воткнула в рубаху и закрепила на подоле. (ЗАКРЕПИТЬ) rus_verbs:УПОЛЗТИ{}, // Зверь завизжал и попытался уползти на двух невредимых передних ногах. (УПОЛЗТИ/УПОЛЗАТЬ) rus_verbs:УПОЛЗАТЬ{}, // rus_verbs:БОЛТАТЬСЯ{}, // Тело его будет болтаться на пространственных ветрах, пока не сгниет веревка. (БОЛТАТЬСЯ) rus_verbs:РАЗВЕРНУТЬ{}, // Филиппины разрешат США развернуть военные базы на своей территории (РАЗВЕРНУТЬ) rus_verbs:ПОЛУЧИТЬ{}, // Я пытался узнать секреты и получить советы на официальном русскоязычном форуме (ПОЛУЧИТЬ) rus_verbs:ЗАСИЯТЬ{}, // Он активировал управление, и на экране снова засияло изображение полумесяца. (ЗАСИЯТЬ) rus_verbs:ВЗОРВАТЬСЯ{}, // Смертник взорвался на предвыборном митинге в Пакистане (ВЗОРВАТЬСЯ) rus_verbs:искриться{}, rus_verbs:ОДЕРЖИВАТЬ{}, // На выборах в иранский парламент победу одерживают противники действующего президента (ОДЕРЖИВАТЬ) rus_verbs:ПРЕСЕЧЬ{}, // На Украине пресекли дерзкий побег заключенных на вертолете (ПРЕСЕЧЬ) rus_verbs:УЛЕТЕТЬ{}, // Голый норвежец улетел на лыжах с трамплина на 60 метров (УЛЕТЕТЬ) rus_verbs:ПРОХОДИТЬ{}, // укрывающийся в лесу американский подросток проходил инициацию на охоте, выпив кружку крови первого убитого им оленя (ПРОХОДИТЬ) rus_verbs:СУЩЕСТВОВАТЬ{}, // На Марсе существовали условия для жизни (СУЩЕСТВОВАТЬ) rus_verbs:УКАЗАТЬ{}, // Победу в Лиге чемпионов укажут на часах (УКАЗАТЬ) rus_verbs:отвести{}, // отвести душу на людях rus_verbs:сходиться{}, // Оба профессора сходились на том, что в черепной коробке динозавра rus_verbs:сойтись{}, rus_verbs:ОБНАРУЖИТЬ{}, // Доказательство наличия подповерхностного океана на Европе обнаружено на её поверхности (ОБНАРУЖИТЬ) rus_verbs:НАБЛЮДАТЬСЯ{}, // Редкий зодиакальный свет вскоре будет наблюдаться на ночном небе (НАБЛЮДАТЬСЯ) rus_verbs:ДОСТИГНУТЬ{}, // На всех аварийных реакторах достигнуто состояние так называемой холодной остановки (ДОСТИГНУТЬ/ДОСТИЧЬ) глагол:ДОСТИЧЬ{}, инфинитив:ДОСТИЧЬ{}, rus_verbs:завершить{}, // Российские биатлонисты завершили чемпионат мира на мажорной ноте rus_verbs:РАСКЛАДЫВАТЬ{}, rus_verbs:ФОКУСИРОВАТЬСЯ{}, // Инвесторы предпочитают фокусироваться на среднесрочных ожиданиях (ФОКУСИРОВАТЬСЯ) rus_verbs:ВОСПРИНИМАТЬ{}, // как несерьезно воспринимали его на выборах мэра (ВОСПРИНИМАТЬ) rus_verbs:БУШЕВАТЬ{}, // на территории Тверской области бушевала гроза , в результате которой произошло отключение электроснабжения в ряде муниципальных образований региона (БУШЕВАТЬ) rus_verbs:УЧАСТИТЬСЯ{}, // В последние месяцы в зоне ответственности бундесвера на севере Афганистана участились случаи обстрелов полевых лагерей немецких миротворцев (УЧАСТИТЬСЯ) rus_verbs:ВЫИГРАТЬ{}, // Почему женская сборная России не может выиграть медаль на чемпионате мира (ВЫИГРАТЬ) rus_verbs:ПРОПАСТЬ{}, // Пропавшим на прогулке актером заинтересовались следователи (ПРОПАСТЬ) rus_verbs:УБИТЬ{}, // Силовики убили двух боевиков на административной границе Ингушетии и Чечни (УБИТЬ) rus_verbs:подпрыгнуть{}, // кобель нелепо подпрыгнул на трех ногах , а его хозяин отправил струю пива мимо рта rus_verbs:подпрыгивать{}, rus_verbs:высветиться{}, // на компьютере высветится твоя подпись rus_verbs:фигурировать{}, // его портрет фигурирует на страницах печати и телеэкранах rus_verbs:действовать{}, // выявленный контрабандный канал действовал на постоянной основе rus_verbs:СОХРАНИТЬСЯ{}, // На рынке международных сделок IPO сохранится высокая активность (СОХРАНИТЬСЯ НА) rus_verbs:ПРОЙТИ{}, // Необычный конкурс прошёл на севере Швеции (ПРОЙТИ НА предл) rus_verbs:НАЧАТЬСЯ{}, // На северо-востоке США началась сильная снежная буря. (НАЧАТЬСЯ НА предл) rus_verbs:ВОЗНИКНУТЬ{}, // Конфликт возник на почве совместной коммерческой деятельности по выращиванию овощей и зелени (ВОЗНИКНУТЬ НА) rus_verbs:СВЕТИТЬСЯ{}, // она по-прежнему светится на лицах людей (СВЕТИТЬСЯ НА предл) rus_verbs:ОРГАНИЗОВАТЬ{}, // Власти Москвы намерены организовать масленичные гуляния на 100 площадках (ОРГАНИЗОВАТЬ НА предл) rus_verbs:ИМЕТЬ{}, // Имея власть на низовом уровне, оказывать самое непосредственное и определяющее влияние на верховную власть (ИМЕТЬ НА предл) rus_verbs:ОПРОБОВАТЬ{}, // Опробовать и отточить этот инструмент на местных и региональных выборах (ОПРОБОВАТЬ, ОТТОЧИТЬ НА предл) rus_verbs:ОТТОЧИТЬ{}, rus_verbs:ДОЛОЖИТЬ{}, // Участникам совещания предложено подготовить по этому вопросу свои предложения и доложить на повторной встрече (ДОЛОЖИТЬ НА предл) rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Солевые и пылевые бури , образующиеся на поверхности обнаженной площади моря , уничтожают урожаи и растительность (ОБРАЗОВЫВАТЬСЯ НА) rus_verbs:СОБРАТЬ{}, // использует собранные на местном рынке депозиты (СОБРАТЬ НА предл) инфинитив:НАХОДИТЬСЯ{ вид:несоверш}, // находившихся на борту самолета (НАХОДИТЬСЯ НА предл) глагол:НАХОДИТЬСЯ{ вид:несоверш }, прилагательное:находившийся{ вид:несоверш }, прилагательное:находящийся{ вид:несоверш }, деепричастие:находясь{}, rus_verbs:ГОТОВИТЬ{}, // пищу готовят сами на примусах (ГОТОВИТЬ НА предл) rus_verbs:РАЗДАТЬСЯ{}, // Они сообщили о сильном хлопке , который раздался на территории нефтебазы (РАЗДАТЬСЯ НА) rus_verbs:ПОДСКАЛЬЗЫВАТЬСЯ{}, // подскальзываться на той же апельсиновой корке (ПОДСКАЛЬЗЫВАТЬСЯ НА) rus_verbs:СКРЫТЬСЯ{}, // Германия: латвиец ограбил магазин и попытался скрыться на такси (СКРЫТЬСЯ НА предл) rus_verbs:ВЫРАСТИТЬ{}, // Пациенту вырастили новый нос на руке (ВЫРАСТИТЬ НА) rus_verbs:ПРОДЕМОНСТРИРОВАТЬ{}, // Они хотят подчеркнуть эмоциональную тонкость оппозиционера и на этом фоне продемонстрировать бездушность российской власти (ПРОДЕМОНСТРИРОВАТЬ НА предл) rus_verbs:ОСУЩЕСТВЛЯТЬСЯ{}, // первичный анализ смеси запахов может осуществляться уже на уровне рецепторных нейронов благодаря механизму латерального торможения (ОСУЩЕСТВЛЯТЬСЯ НА) rus_verbs:ВЫДЕЛЯТЬСЯ{}, // Ягоды брусники, резко выделяющиеся своим красным цветом на фоне зелёной листвы, поедаются животными и птицами (ВЫДЕЛЯТЬСЯ НА) rus_verbs:РАСКРЫТЬ{}, // На Украине раскрыто крупное мошенничество в сфере туризма (РАСКРЫТЬ НА) rus_verbs:ОБЖАРИВАТЬСЯ{}, // Омлет обжаривается на сливочном масле с одной стороны, пока он почти полностью не загустеет (ОБЖАРИВАТЬСЯ НА) rus_verbs:ПРИГОТОВЛЯТЬ{}, // Яичница — блюдо европейской кухни, приготовляемое на сковороде из разбитых яиц (ПРИГОТОВЛЯТЬ НА) rus_verbs:РАССАДИТЬ{}, // Женька рассадил игрушки на скамеечке (РАССАДИТЬ НА) rus_verbs:ОБОЖДАТЬ{}, // обожди Анжелу на остановке троллейбуса (ОБОЖДАТЬ НА) rus_verbs:УЧИТЬСЯ{}, // Марина учится на факультете журналистики (УЧИТЬСЯ НА предл) rus_verbs:раскладываться{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА) rus_verbs:ПОСЛУШАТЬ{}, // Послушайте друзей и врагов на расстоянии! (ПОСЛУШАТЬ НА) rus_verbs:ВЕСТИСЬ{}, // На стороне противника всю ночь велась перегруппировка сил. (ВЕСТИСЬ НА) rus_verbs:ПОИНТЕРЕСОВАТЬСЯ{}, // корреспондент поинтересовался у людей на улице (ПОИНТЕРЕСОВАТЬСЯ НА) rus_verbs:ОТКРЫВАТЬСЯ{}, // Российские биржи открываются на негативном фоне (ОТКРЫВАТЬСЯ НА) rus_verbs:СХОДИТЬ{}, // Вы сходите на следующей остановке? (СХОДИТЬ НА) rus_verbs:ПОГИБНУТЬ{}, // Её отец погиб на войне. (ПОГИБНУТЬ НА) rus_verbs:ВЫЙТИ{}, // Книга выйдет на будущей неделе. (ВЫЙТИ НА предл) rus_verbs:НЕСТИСЬ{}, // Корабль несётся на всех парусах. (НЕСТИСЬ НА предл) rus_verbs:вкалывать{}, // Папа вкалывает на работе, чтобы прокормить семью (вкалывать на) rus_verbs:доказать{}, // разработчики доказали на практике применимость данного подхода к обсчету сцен (доказать на, применимость к) rus_verbs:хулиганить{}, // дозволять кому-то хулиганить на кладбище (хулиганить на) глагол:вычитать{вид:соверш}, инфинитив:вычитать{вид:соверш}, // вычитать на сайте (вычитать на сайте) деепричастие:вычитав{}, rus_verbs:аккомпанировать{}, // он аккомпанировал певцу на губной гармошке (аккомпанировать на) rus_verbs:набрать{}, // статья с заголовком, набранным на компьютере rus_verbs:сделать{}, // книга с иллюстрацией, сделанной на компьютере rus_verbs:развалиться{}, // Антонио развалился на диване rus_verbs:улечься{}, // Антонио улегся на полу rus_verbs:зарубить{}, // Заруби себе на носу. rus_verbs:ценить{}, // Его ценят на заводе. rus_verbs:вернуться{}, // Отец вернулся на закате. rus_verbs:шить{}, // Вы умеете шить на машинке? rus_verbs:бить{}, // Скот бьют на бойне. rus_verbs:выехать{}, // Мы выехали на рассвете. rus_verbs:валяться{}, // На полу валяется бумага. rus_verbs:разложить{}, // она разложила полотенце на песке rus_verbs:заниматься{}, // я занимаюсь на тренажере rus_verbs:позаниматься{}, rus_verbs:порхать{}, // порхать на лугу rus_verbs:пресекать{}, // пресекать на корню rus_verbs:изъясняться{}, // изъясняться на непонятном языке rus_verbs:развесить{}, // развесить на столбах rus_verbs:обрасти{}, // обрасти на южной части rus_verbs:откладываться{}, // откладываться на стенках артерий rus_verbs:уносить{}, // уносить на носилках rus_verbs:проплыть{}, // проплыть на плоту rus_verbs:подъезжать{}, // подъезжать на повозках rus_verbs:пульсировать{}, // пульсировать на лбу rus_verbs:рассесться{}, // птицы расселись на ветках rus_verbs:застопориться{}, // застопориться на первом пункте rus_verbs:изловить{}, // изловить на окраинах rus_verbs:покататься{}, // покататься на машинках rus_verbs:залопотать{}, // залопотать на неизвестном языке rus_verbs:растягивать{}, // растягивать на станке rus_verbs:поделывать{}, // поделывать на пляже rus_verbs:подстеречь{}, // подстеречь на площадке rus_verbs:проектировать{}, // проектировать на компьютере rus_verbs:притулиться{}, // притулиться на кушетке rus_verbs:дозволять{}, // дозволять кому-то хулиганить на кладбище rus_verbs:пострелять{}, // пострелять на испытательном полигоне rus_verbs:засиживаться{}, // засиживаться на работе rus_verbs:нежиться{}, // нежиться на солнышке rus_verbs:притомиться{}, // притомиться на рабочем месте rus_verbs:поселяться{}, // поселяться на чердаке rus_verbs:потягиваться{}, // потягиваться на земле rus_verbs:отлеживаться{}, // отлеживаться на койке rus_verbs:протаранить{}, // протаранить на танке rus_verbs:гарцевать{}, // гарцевать на коне rus_verbs:облупиться{}, // облупиться на носу rus_verbs:оговорить{}, // оговорить на собеседовании rus_verbs:зарегистрироваться{}, // зарегистрироваться на сайте rus_verbs:отпечатать{}, // отпечатать на картоне rus_verbs:сэкономить{}, // сэкономить на мелочах rus_verbs:покатать{}, // покатать на пони rus_verbs:колесить{}, // колесить на старой машине rus_verbs:понастроить{}, // понастроить на участках rus_verbs:поджарить{}, // поджарить на костре rus_verbs:узнаваться{}, // узнаваться на фотографии rus_verbs:отощать{}, // отощать на казенных харчах rus_verbs:редеть{}, // редеть на макушке rus_verbs:оглашать{}, // оглашать на общем собрании rus_verbs:лопотать{}, // лопотать на иврите rus_verbs:пригреть{}, // пригреть на груди rus_verbs:консультироваться{}, // консультироваться на форуме rus_verbs:приноситься{}, // приноситься на одежде rus_verbs:сушиться{}, // сушиться на балконе rus_verbs:наследить{}, // наследить на полу rus_verbs:нагреться{}, // нагреться на солнце rus_verbs:рыбачить{}, // рыбачить на озере rus_verbs:прокатить{}, // прокатить на выборах rus_verbs:запинаться{}, // запинаться на ровном месте rus_verbs:отрубиться{}, // отрубиться на мягкой подушке rus_verbs:заморозить{}, // заморозить на улице rus_verbs:промерзнуть{}, // промерзнуть на открытом воздухе rus_verbs:просохнуть{}, // просохнуть на батарее rus_verbs:развозить{}, // развозить на велосипеде rus_verbs:прикорнуть{}, // прикорнуть на диванчике rus_verbs:отпечататься{}, // отпечататься на коже rus_verbs:выявлять{}, // выявлять на таможне rus_verbs:расставлять{}, // расставлять на башнях rus_verbs:прокрутить{}, // прокрутить на пальце rus_verbs:умываться{}, // умываться на улице rus_verbs:пересказывать{}, // пересказывать на страницах романа rus_verbs:удалять{}, // удалять на пуховике rus_verbs:хозяйничать{}, // хозяйничать на складе rus_verbs:оперировать{}, // оперировать на поле боя rus_verbs:поносить{}, // поносить на голове rus_verbs:замурлыкать{}, // замурлыкать на коленях rus_verbs:передвигать{}, // передвигать на тележке rus_verbs:прочертить{}, // прочертить на земле rus_verbs:колдовать{}, // колдовать на кухне rus_verbs:отвозить{}, // отвозить на казенном транспорте rus_verbs:трахать{}, // трахать на природе rus_verbs:мастерить{}, // мастерить на кухне rus_verbs:ремонтировать{}, // ремонтировать на коленке rus_verbs:развезти{}, // развезти на велосипеде rus_verbs:робеть{}, // робеть на сцене инфинитив:реализовать{ вид:несоверш }, инфинитив:реализовать{ вид:соверш }, // реализовать на сайте глагол:реализовать{ вид:несоверш }, глагол:реализовать{ вид:соверш }, деепричастие:реализовав{}, деепричастие:реализуя{}, rus_verbs:покаяться{}, // покаяться на смертном одре rus_verbs:специализироваться{}, // специализироваться на тестировании rus_verbs:попрыгать{}, // попрыгать на батуте rus_verbs:переписывать{}, // переписывать на столе rus_verbs:расписывать{}, // расписывать на доске rus_verbs:зажимать{}, // зажимать на запястье rus_verbs:практиковаться{}, // практиковаться на мышах rus_verbs:уединиться{}, // уединиться на чердаке rus_verbs:подохнуть{}, // подохнуть на чужбине rus_verbs:приподниматься{}, // приподниматься на руках rus_verbs:уродиться{}, // уродиться на полях rus_verbs:продолжиться{}, // продолжиться на улице rus_verbs:посапывать{}, // посапывать на диване rus_verbs:ободрать{}, // ободрать на спине rus_verbs:скрючиться{}, // скрючиться на песке rus_verbs:тормознуть{}, // тормознуть на перекрестке rus_verbs:лютовать{}, // лютовать на хуторе rus_verbs:зарегистрировать{}, // зарегистрировать на сайте rus_verbs:переждать{}, // переждать на вершине холма rus_verbs:доминировать{}, // доминировать на территории rus_verbs:публиковать{}, // публиковать на сайте rus_verbs:морщить{}, // морщить на лбу rus_verbs:сконцентрироваться{}, // сконцентрироваться на главном rus_verbs:подрабатывать{}, // подрабатывать на рынке rus_verbs:репетировать{}, // репетировать на заднем дворе rus_verbs:подвернуть{}, // подвернуть на брусчатке rus_verbs:зашелестеть{}, // зашелестеть на ветру rus_verbs:расчесывать{}, // расчесывать на спине rus_verbs:одевать{}, // одевать на рынке rus_verbs:испечь{}, // испечь на углях rus_verbs:сбрить{}, // сбрить на затылке rus_verbs:согреться{}, // согреться на печке rus_verbs:замаячить{}, // замаячить на горизонте rus_verbs:пересчитывать{}, // пересчитывать на пальцах rus_verbs:галдеть{}, // галдеть на крыльце rus_verbs:переплыть{}, // переплыть на плоту rus_verbs:передохнуть{}, // передохнуть на скамейке rus_verbs:прижиться{}, // прижиться на ферме rus_verbs:переправляться{}, // переправляться на плотах rus_verbs:накупить{}, // накупить на блошином рынке rus_verbs:проторчать{}, // проторчать на виду rus_verbs:мокнуть{}, // мокнуть на улице rus_verbs:застукать{}, // застукать на камбузе rus_verbs:завязывать{}, // завязывать на ботинках rus_verbs:повисать{}, // повисать на ветке rus_verbs:подвизаться{}, // подвизаться на государственной службе rus_verbs:кормиться{}, // кормиться на болоте rus_verbs:покурить{}, // покурить на улице rus_verbs:зимовать{}, // зимовать на болотах rus_verbs:застегивать{}, // застегивать на гимнастерке rus_verbs:поигрывать{}, // поигрывать на гитаре rus_verbs:погореть{}, // погореть на махинациях с землей rus_verbs:кувыркаться{}, // кувыркаться на батуте rus_verbs:похрапывать{}, // похрапывать на диване rus_verbs:пригревать{}, // пригревать на груди rus_verbs:завязнуть{}, // завязнуть на болоте rus_verbs:шастать{}, // шастать на втором этаже rus_verbs:заночевать{}, // заночевать на сеновале rus_verbs:отсиживаться{}, // отсиживаться на чердаке rus_verbs:мчать{}, // мчать на байке rus_verbs:сгнить{}, // сгнить на урановых рудниках rus_verbs:тренировать{}, // тренировать на манекенах rus_verbs:повеселиться{}, // повеселиться на празднике rus_verbs:измучиться{}, // измучиться на болоте rus_verbs:увянуть{}, // увянуть на подоконнике rus_verbs:раскрутить{}, // раскрутить на оси rus_verbs:выцвести{}, // выцвести на солнечном свету rus_verbs:изготовлять{}, // изготовлять на коленке rus_verbs:гнездиться{}, // гнездиться на вершине дерева rus_verbs:разогнаться{}, // разогнаться на мотоцикле rus_verbs:излагаться{}, // излагаться на страницах доклада rus_verbs:сконцентрировать{}, // сконцентрировать на левом фланге rus_verbs:расчесать{}, // расчесать на макушке rus_verbs:плавиться{}, // плавиться на солнце rus_verbs:редактировать{}, // редактировать на ноутбуке rus_verbs:подскакивать{}, // подскакивать на месте rus_verbs:покупаться{}, // покупаться на рынке rus_verbs:промышлять{}, // промышлять на мелководье rus_verbs:приобретаться{}, // приобретаться на распродажах rus_verbs:наигрывать{}, // наигрывать на банджо rus_verbs:маневрировать{}, // маневрировать на флангах rus_verbs:запечатлеться{}, // запечатлеться на записях камер rus_verbs:укрывать{}, // укрывать на чердаке rus_verbs:подорваться{}, // подорваться на фугасе rus_verbs:закрепиться{}, // закрепиться на занятых позициях rus_verbs:громыхать{}, // громыхать на кухне инфинитив:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:соверш }, // подвигаться на полу деепричастие:подвигавшись{}, rus_verbs:добываться{}, // добываться на территории Анголы rus_verbs:приплясывать{}, // приплясывать на сцене rus_verbs:доживать{}, // доживать на больничной койке rus_verbs:отпраздновать{}, // отпраздновать на работе rus_verbs:сгубить{}, // сгубить на корню rus_verbs:схоронить{}, // схоронить на кладбище rus_verbs:тускнеть{}, // тускнеть на солнце rus_verbs:скопить{}, // скопить на счету rus_verbs:помыть{}, // помыть на своем этаже rus_verbs:пороть{}, // пороть на конюшне rus_verbs:наличествовать{}, // наличествовать на складе rus_verbs:нащупывать{}, // нащупывать на полке rus_verbs:змеиться{}, // змеиться на дне rus_verbs:пожелтеть{}, // пожелтеть на солнце rus_verbs:заостриться{}, // заостриться на конце rus_verbs:свезти{}, // свезти на поле rus_verbs:прочувствовать{}, // прочувствовать на своей шкуре rus_verbs:подкрутить{}, // подкрутить на приборной панели rus_verbs:рубиться{}, // рубиться на мечах rus_verbs:сиживать{}, // сиживать на крыльце rus_verbs:тараторить{}, // тараторить на иностранном языке rus_verbs:теплеть{}, // теплеть на сердце rus_verbs:покачаться{}, // покачаться на ветке rus_verbs:сосредоточиваться{}, // сосредоточиваться на главной задаче rus_verbs:развязывать{}, // развязывать на ботинках rus_verbs:подвозить{}, // подвозить на мотороллере rus_verbs:вышивать{}, // вышивать на рубашке rus_verbs:скупать{}, // скупать на открытом рынке rus_verbs:оформлять{}, // оформлять на встрече rus_verbs:распускаться{}, // распускаться на клумбах rus_verbs:прогореть{}, // прогореть на спекуляциях rus_verbs:приползти{}, // приползти на коленях rus_verbs:загореть{}, // загореть на пляже rus_verbs:остудить{}, // остудить на балконе rus_verbs:нарвать{}, // нарвать на поляне rus_verbs:издохнуть{}, // издохнуть на болоте rus_verbs:разгружать{}, // разгружать на дороге rus_verbs:произрастать{}, // произрастать на болотах rus_verbs:разуться{}, // разуться на коврике rus_verbs:сооружать{}, // сооружать на площади rus_verbs:зачитывать{}, // зачитывать на митинге rus_verbs:уместиться{}, // уместиться на ладони rus_verbs:закупить{}, // закупить на рынке rus_verbs:горланить{}, // горланить на улице rus_verbs:экономить{}, // экономить на спичках rus_verbs:исправлять{}, // исправлять на доске rus_verbs:расслабляться{}, // расслабляться на лежаке rus_verbs:скапливаться{}, // скапливаться на крыше rus_verbs:сплетничать{}, // сплетничать на скамеечке rus_verbs:отъезжать{}, // отъезжать на лимузине rus_verbs:отчитывать{}, // отчитывать на собрании rus_verbs:сфокусировать{}, // сфокусировать на удаленной точке rus_verbs:потчевать{}, // потчевать на лаврах rus_verbs:окопаться{}, // окопаться на окраине rus_verbs:загорать{}, // загорать на пляже rus_verbs:обгореть{}, // обгореть на солнце rus_verbs:распознавать{}, // распознавать на фотографии rus_verbs:заплетаться{}, // заплетаться на макушке rus_verbs:перегреться{}, // перегреться на жаре rus_verbs:подметать{}, // подметать на крыльце rus_verbs:нарисоваться{}, // нарисоваться на горизонте rus_verbs:проскакивать{}, // проскакивать на экране rus_verbs:попивать{}, // попивать на балконе чай rus_verbs:отплывать{}, // отплывать на лодке rus_verbs:чирикать{}, // чирикать на ветках rus_verbs:скупить{}, // скупить на оптовых базах rus_verbs:наколоть{}, // наколоть на коже картинку rus_verbs:созревать{}, // созревать на ветке rus_verbs:проколоться{}, // проколоться на мелочи rus_verbs:крутнуться{}, // крутнуться на заднем колесе rus_verbs:переночевать{}, // переночевать на постоялом дворе rus_verbs:концентрироваться{}, // концентрироваться на фильтре rus_verbs:одичать{}, // одичать на хуторе rus_verbs:спасаться{}, // спасаются на лодке rus_verbs:доказываться{}, // доказываться на страницах книги rus_verbs:познаваться{}, // познаваться на ринге rus_verbs:замыкаться{}, // замыкаться на металлическом предмете rus_verbs:заприметить{}, // заприметить на пригорке rus_verbs:продержать{}, // продержать на морозе rus_verbs:форсировать{}, // форсировать на плотах rus_verbs:сохнуть{}, // сохнуть на солнце rus_verbs:выявить{}, // выявить на поверхности rus_verbs:заседать{}, // заседать на кафедре rus_verbs:расплачиваться{}, // расплачиваться на выходе rus_verbs:светлеть{}, // светлеть на горизонте rus_verbs:залепетать{}, // залепетать на незнакомом языке rus_verbs:подсчитывать{}, // подсчитывать на пальцах rus_verbs:зарыть{}, // зарыть на пустыре rus_verbs:сформироваться{}, // сформироваться на месте rus_verbs:развертываться{}, // развертываться на площадке rus_verbs:набивать{}, // набивать на манекенах rus_verbs:замерзать{}, // замерзать на ветру rus_verbs:схватывать{}, // схватывать на лету rus_verbs:перевестись{}, // перевестись на Руси rus_verbs:смешивать{}, // смешивать на блюдце rus_verbs:прождать{}, // прождать на входе rus_verbs:мерзнуть{}, // мерзнуть на ветру rus_verbs:растирать{}, // растирать на коже rus_verbs:переспать{}, // переспал на сеновале rus_verbs:рассекать{}, // рассекать на скутере rus_verbs:опровергнуть{}, // опровергнуть на высшем уровне rus_verbs:дрыхнуть{}, // дрыхнуть на диване rus_verbs:распять{}, // распять на кресте rus_verbs:запечься{}, // запечься на костре rus_verbs:застилать{}, // застилать на балконе rus_verbs:сыскаться{}, // сыскаться на огороде rus_verbs:разориться{}, // разориться на продаже спичек rus_verbs:переделать{}, // переделать на станке rus_verbs:разъяснять{}, // разъяснять на страницах газеты rus_verbs:поседеть{}, // поседеть на висках rus_verbs:протащить{}, // протащить на спине rus_verbs:осуществиться{}, // осуществиться на деле rus_verbs:селиться{}, // селиться на окраине rus_verbs:оплачивать{}, // оплачивать на первой кассе rus_verbs:переворачивать{}, // переворачивать на сковородке rus_verbs:упражняться{}, // упражняться на батуте rus_verbs:испробовать{}, // испробовать на себе rus_verbs:разгладиться{}, // разгладиться на спине rus_verbs:рисоваться{}, // рисоваться на стекле rus_verbs:продрогнуть{}, // продрогнуть на морозе rus_verbs:пометить{}, // пометить на доске rus_verbs:приютить{}, // приютить на чердаке rus_verbs:избирать{}, // избирать на первых свободных выборах rus_verbs:затеваться{}, // затеваться на матче rus_verbs:уплывать{}, // уплывать на катере rus_verbs:замерцать{}, // замерцать на рекламном щите rus_verbs:фиксироваться{}, // фиксироваться на достигнутом уровне rus_verbs:запираться{}, // запираться на чердаке rus_verbs:загубить{}, // загубить на корню rus_verbs:развеяться{}, // развеяться на природе rus_verbs:съезжаться{}, // съезжаться на лимузинах rus_verbs:потанцевать{}, // потанцевать на могиле rus_verbs:дохнуть{}, // дохнуть на солнце rus_verbs:припарковаться{}, // припарковаться на газоне rus_verbs:отхватить{}, // отхватить на распродаже rus_verbs:остывать{}, // остывать на улице rus_verbs:переваривать{}, // переваривать на высокой ветке rus_verbs:подвесить{}, // подвесить на веревке rus_verbs:хвастать{}, // хвастать на работе rus_verbs:отрабатывать{}, // отрабатывать на уборке урожая rus_verbs:разлечься{}, // разлечься на полу rus_verbs:очертить{}, // очертить на полу rus_verbs:председательствовать{}, // председательствовать на собрании rus_verbs:сконфузиться{}, // сконфузиться на сцене rus_verbs:выявляться{}, // выявляться на ринге rus_verbs:крутануться{}, // крутануться на заднем колесе rus_verbs:караулить{}, // караулить на входе rus_verbs:перечислять{}, // перечислять на пальцах rus_verbs:обрабатывать{}, // обрабатывать на станке rus_verbs:настигать{}, // настигать на берегу rus_verbs:разгуливать{}, // разгуливать на берегу rus_verbs:насиловать{}, // насиловать на пляже rus_verbs:поредеть{}, // поредеть на макушке rus_verbs:учитывать{}, // учитывать на балансе rus_verbs:зарождаться{}, // зарождаться на большой глубине rus_verbs:распространять{}, // распространять на сайтах rus_verbs:пировать{}, // пировать на вершине холма rus_verbs:начертать{}, // начертать на стене rus_verbs:расцветать{}, // расцветать на подоконнике rus_verbs:умнеть{}, // умнеть на глазах rus_verbs:царствовать{}, // царствовать на окраине rus_verbs:закрутиться{}, // закрутиться на работе rus_verbs:отработать{}, // отработать на шахте rus_verbs:полечь{}, // полечь на поле брани rus_verbs:щебетать{}, // щебетать на ветке rus_verbs:подчеркиваться{}, // подчеркиваться на сайте rus_verbs:посеять{}, // посеять на другом поле rus_verbs:замечаться{}, // замечаться на пастбище rus_verbs:просчитать{}, // просчитать на пальцах rus_verbs:голосовать{}, // голосовать на трассе rus_verbs:маяться{}, // маяться на пляже rus_verbs:сколотить{}, // сколотить на службе rus_verbs:обретаться{}, // обретаться на чужбине rus_verbs:обливаться{}, // обливаться на улице rus_verbs:катать{}, // катать на лошадке rus_verbs:припрятать{}, // припрятать на теле rus_verbs:запаниковать{}, // запаниковать на экзамене инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать на частном самолете деепричастие:слетав{}, rus_verbs:срубить{}, // срубить денег на спекуляциях rus_verbs:зажигаться{}, // зажигаться на улице rus_verbs:жарить{}, // жарить на углях rus_verbs:накапливаться{}, // накапливаться на счету rus_verbs:распуститься{}, // распуститься на грядке rus_verbs:рассаживаться{}, // рассаживаться на местах rus_verbs:странствовать{}, // странствовать на лошади rus_verbs:осматриваться{}, // осматриваться на месте rus_verbs:разворачивать{}, // разворачивать на завоеванной территории rus_verbs:согревать{}, // согревать на вершине горы rus_verbs:заскучать{}, // заскучать на вахте rus_verbs:перекусить{}, // перекусить на бегу rus_verbs:приплыть{}, // приплыть на тримаране rus_verbs:зажигать{}, // зажигать на танцах rus_verbs:закопать{}, // закопать на поляне rus_verbs:стирать{}, // стирать на берегу rus_verbs:подстерегать{}, // подстерегать на подходе rus_verbs:погулять{}, // погулять на свадьбе rus_verbs:огласить{}, // огласить на митинге rus_verbs:разбогатеть{}, // разбогатеть на прииске rus_verbs:грохотать{}, // грохотать на чердаке rus_verbs:расположить{}, // расположить на границе rus_verbs:реализоваться{}, // реализоваться на новой работе rus_verbs:застывать{}, // застывать на морозе rus_verbs:запечатлеть{}, // запечатлеть на пленке rus_verbs:тренироваться{}, // тренироваться на манекене rus_verbs:поспорить{}, // поспорить на совещании rus_verbs:затягивать{}, // затягивать на поясе rus_verbs:зиждиться{}, // зиждиться на твердой основе rus_verbs:построиться{}, // построиться на песке rus_verbs:надрываться{}, // надрываться на работе rus_verbs:закипать{}, // закипать на плите rus_verbs:затонуть{}, // затонуть на мелководье rus_verbs:побыть{}, // побыть на фазенде rus_verbs:сгорать{}, // сгорать на солнце инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на улице деепричастие:пописав{ aux stress="поп^исав" }, rus_verbs:подраться{}, // подраться на сцене rus_verbs:заправить{}, // заправить на последней заправке rus_verbs:обозначаться{}, // обозначаться на карте rus_verbs:просиживать{}, // просиживать на берегу rus_verbs:начертить{}, // начертить на листке rus_verbs:тормозить{}, // тормозить на льду rus_verbs:затевать{}, // затевать на космической базе rus_verbs:задерживать{}, // задерживать на таможне rus_verbs:прилетать{}, // прилетать на частном самолете rus_verbs:полулежать{}, // полулежать на травке rus_verbs:ерзать{}, // ерзать на табуретке rus_verbs:покопаться{}, // покопаться на складе rus_verbs:подвезти{}, // подвезти на машине rus_verbs:полежать{}, // полежать на водном матрасе rus_verbs:стыть{}, // стыть на улице rus_verbs:стынуть{}, // стынуть на улице rus_verbs:скреститься{}, // скреститься на груди rus_verbs:припарковать{}, // припарковать на стоянке rus_verbs:здороваться{}, // здороваться на кафедре rus_verbs:нацарапать{}, // нацарапать на парте rus_verbs:откопать{}, // откопать на поляне rus_verbs:смастерить{}, // смастерить на коленках rus_verbs:довезти{}, // довезти на машине rus_verbs:избивать{}, // избивать на крыше rus_verbs:сварить{}, // сварить на костре rus_verbs:истребить{}, // истребить на корню rus_verbs:раскопать{}, // раскопать на болоте rus_verbs:попить{}, // попить на кухне rus_verbs:заправлять{}, // заправлять на базе rus_verbs:кушать{}, // кушать на кухне rus_verbs:замолкать{}, // замолкать на половине фразы rus_verbs:измеряться{}, // измеряться на весах rus_verbs:сбываться{}, // сбываться на самом деле rus_verbs:изображаться{}, // изображается на сцене rus_verbs:фиксировать{}, // фиксировать на данной высоте rus_verbs:ослаблять{}, // ослаблять на шее rus_verbs:зреть{}, // зреть на грядке rus_verbs:зеленеть{}, // зеленеть на грядке rus_verbs:критиковать{}, // критиковать на страницах газеты rus_verbs:облететь{}, // облететь на самолете rus_verbs:заразиться{}, // заразиться на работе rus_verbs:рассеять{}, // рассеять на территории rus_verbs:печься{}, // печься на костре rus_verbs:поспать{}, // поспать на земле rus_verbs:сплетаться{}, // сплетаться на макушке rus_verbs:удерживаться{}, // удерживаться на расстоянии rus_verbs:помешаться{}, // помешаться на чистоте rus_verbs:ликвидировать{}, // ликвидировать на полигоне rus_verbs:проваляться{}, // проваляться на диване rus_verbs:лечиться{}, // лечиться на дому rus_verbs:обработать{}, // обработать на станке rus_verbs:защелкнуть{}, // защелкнуть на руках rus_verbs:разносить{}, // разносить на одежде rus_verbs:чесать{}, // чесать на груди rus_verbs:наладить{}, // наладить на конвейере выпуск rus_verbs:отряхнуться{}, // отряхнуться на улице rus_verbs:разыгрываться{}, // разыгрываться на скачках rus_verbs:обеспечиваться{}, // обеспечиваться на выгодных условиях rus_verbs:греться{}, // греться на вокзале rus_verbs:засидеться{}, // засидеться на одном месте rus_verbs:материализоваться{}, // материализоваться на границе rus_verbs:рассеиваться{}, // рассеиваться на высоте вершин rus_verbs:перевозить{}, // перевозить на платформе rus_verbs:поиграть{}, // поиграть на скрипке rus_verbs:потоптаться{}, // потоптаться на одном месте rus_verbs:переправиться{}, // переправиться на плоту rus_verbs:забрезжить{}, // забрезжить на горизонте rus_verbs:завывать{}, // завывать на опушке rus_verbs:заваривать{}, // заваривать на кухоньке rus_verbs:перемещаться{}, // перемещаться на спасательном плоту инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться на бланке rus_verbs:праздновать{}, // праздновать на улицах rus_verbs:обучить{}, // обучить на корте rus_verbs:орудовать{}, // орудовать на складе rus_verbs:подрасти{}, // подрасти на глядке rus_verbs:шелестеть{}, // шелестеть на ветру rus_verbs:раздеваться{}, // раздеваться на публике rus_verbs:пообедать{}, // пообедать на газоне rus_verbs:жрать{}, // жрать на помойке rus_verbs:исполняться{}, // исполняться на флейте rus_verbs:похолодать{}, // похолодать на улице rus_verbs:гнить{}, // гнить на каторге rus_verbs:прослушать{}, // прослушать на концерте rus_verbs:совещаться{}, // совещаться на заседании rus_verbs:покачивать{}, // покачивать на волнах rus_verbs:отсидеть{}, // отсидеть на гаупвахте rus_verbs:формировать{}, // формировать на секретной базе rus_verbs:захрапеть{}, // захрапеть на кровати rus_verbs:объехать{}, // объехать на попутке rus_verbs:поселить{}, // поселить на верхних этажах rus_verbs:заворочаться{}, // заворочаться на сене rus_verbs:напрятать{}, // напрятать на теле rus_verbs:очухаться{}, // очухаться на земле rus_verbs:полистать{}, // полистать на досуге rus_verbs:завертеть{}, // завертеть на шесте rus_verbs:печатать{}, // печатать на ноуте rus_verbs:отыскаться{}, // отыскаться на складе rus_verbs:зафиксировать{}, // зафиксировать на пленке rus_verbs:расстилаться{}, // расстилаться на столе rus_verbs:заместить{}, // заместить на посту rus_verbs:угасать{}, // угасать на неуправляемом корабле rus_verbs:сразить{}, // сразить на ринге rus_verbs:расплываться{}, // расплываться на жаре rus_verbs:сосчитать{}, // сосчитать на пальцах rus_verbs:сгуститься{}, // сгуститься на небольшой высоте rus_verbs:цитировать{}, // цитировать на плите rus_verbs:ориентироваться{}, // ориентироваться на местности rus_verbs:расширить{}, // расширить на другом конце rus_verbs:обтереть{}, // обтереть на стоянке rus_verbs:подстрелить{}, // подстрелить на охоте rus_verbs:растереть{}, // растереть на твердой поверхности rus_verbs:подавлять{}, // подавлять на первом этапе rus_verbs:смешиваться{}, // смешиваться на поверхности // инфинитив:вычитать{ aux stress="в^ычитать" }, глагол:вычитать{ aux stress="в^ычитать" }, // вычитать на сайте // деепричастие:вычитав{}, rus_verbs:сократиться{}, // сократиться на втором этапе rus_verbs:занервничать{}, // занервничать на экзамене rus_verbs:соприкоснуться{}, // соприкоснуться на трассе rus_verbs:обозначить{}, // обозначить на плане rus_verbs:обучаться{}, // обучаться на производстве rus_verbs:снизиться{}, // снизиться на большой высоте rus_verbs:простудиться{}, // простудиться на ветру rus_verbs:поддерживаться{}, // поддерживается на встрече rus_verbs:уплыть{}, // уплыть на лодочке rus_verbs:резвиться{}, // резвиться на песочке rus_verbs:поерзать{}, // поерзать на скамеечке rus_verbs:похвастаться{}, // похвастаться на встрече rus_verbs:знакомиться{}, // знакомиться на уроке rus_verbs:проплывать{}, // проплывать на катере rus_verbs:засесть{}, // засесть на чердаке rus_verbs:подцепить{}, // подцепить на дискотеке rus_verbs:обыскать{}, // обыскать на входе rus_verbs:оправдаться{}, // оправдаться на суде rus_verbs:раскрываться{}, // раскрываться на сцене rus_verbs:одеваться{}, // одеваться на вещевом рынке rus_verbs:засветиться{}, // засветиться на фотографиях rus_verbs:употребляться{}, // употребляться на птицефабриках rus_verbs:грабить{}, // грабить на пустыре rus_verbs:гонять{}, // гонять на повышенных оборотах rus_verbs:развеваться{}, // развеваться на древке rus_verbs:основываться{}, // основываться на безусловных фактах rus_verbs:допрашивать{}, // допрашивать на базе rus_verbs:проработать{}, // проработать на стройке rus_verbs:сосредоточить{}, // сосредоточить на месте rus_verbs:сочинять{}, // сочинять на ходу rus_verbs:ползать{}, // ползать на камне rus_verbs:раскинуться{}, // раскинуться на пустыре rus_verbs:уставать{}, // уставать на работе rus_verbs:укрепить{}, // укрепить на конце rus_verbs:образовывать{}, // образовывать на открытом воздухе взрывоопасную смесь rus_verbs:одобрять{}, // одобрять на словах rus_verbs:приговорить{}, // приговорить на заседании тройки rus_verbs:чернеть{}, // чернеть на свету rus_verbs:гнуть{}, // гнуть на станке rus_verbs:размещаться{}, // размещаться на бирже rus_verbs:соорудить{}, // соорудить на даче rus_verbs:пастись{}, // пастись на лугу rus_verbs:формироваться{}, // формироваться на дне rus_verbs:таить{}, // таить на дне rus_verbs:приостановиться{}, // приостановиться на середине rus_verbs:топтаться{}, // топтаться на месте rus_verbs:громить{}, // громить на подступах rus_verbs:вычислить{}, // вычислить на бумажке rus_verbs:заказывать{}, // заказывать на сайте rus_verbs:осуществить{}, // осуществить на практике rus_verbs:обосноваться{}, // обосноваться на верхушке rus_verbs:пытать{}, // пытать на электрическом стуле rus_verbs:совершиться{}, // совершиться на заседании rus_verbs:свернуться{}, // свернуться на медленном огне rus_verbs:пролетать{}, // пролетать на дельтаплане rus_verbs:сбыться{}, // сбыться на самом деле rus_verbs:разговориться{}, // разговориться на уроке rus_verbs:разворачиваться{}, // разворачиваться на перекрестке rus_verbs:преподнести{}, // преподнести на блюдечке rus_verbs:напечатать{}, // напечатать на лазернике rus_verbs:прорвать{}, // прорвать на периферии rus_verbs:раскачиваться{}, // раскачиваться на доске rus_verbs:задерживаться{}, // задерживаться на старте rus_verbs:угощать{}, // угощать на вечеринке rus_verbs:шарить{}, // шарить на столе rus_verbs:увеличивать{}, // увеличивать на первом этапе rus_verbs:рехнуться{}, // рехнуться на старости лет rus_verbs:расцвести{}, // расцвести на грядке rus_verbs:закипеть{}, // закипеть на плите rus_verbs:подлететь{}, // подлететь на параплане rus_verbs:рыться{}, // рыться на свалке rus_verbs:добираться{}, // добираться на попутках rus_verbs:продержаться{}, // продержаться на вершине rus_verbs:разыскивать{}, // разыскивать на выставках rus_verbs:освобождать{}, // освобождать на заседании rus_verbs:передвигаться{}, // передвигаться на самокате rus_verbs:проявиться{}, // проявиться на свету rus_verbs:заскользить{}, // заскользить на льду rus_verbs:пересказать{}, // пересказать на сцене студенческого театра rus_verbs:протестовать{}, // протестовать на улице rus_verbs:указываться{}, // указываться на табличках rus_verbs:прискакать{}, // прискакать на лошадке rus_verbs:копошиться{}, // копошиться на свежем воздухе rus_verbs:подсчитать{}, // подсчитать на бумажке rus_verbs:разволноваться{}, // разволноваться на экзамене rus_verbs:завертеться{}, // завертеться на полу rus_verbs:ознакомиться{}, // ознакомиться на ходу rus_verbs:ржать{}, // ржать на уроке rus_verbs:раскинуть{}, // раскинуть на грядках rus_verbs:разгромить{}, // разгромить на ринге rus_verbs:подслушать{}, // подслушать на совещании rus_verbs:описываться{}, // описываться на страницах книги rus_verbs:качаться{}, // качаться на стуле rus_verbs:усилить{}, // усилить на флангах rus_verbs:набросать{}, // набросать на клочке картона rus_verbs:расстреливать{}, // расстреливать на подходе rus_verbs:запрыгать{}, // запрыгать на одной ноге rus_verbs:сыскать{}, // сыскать на чужбине rus_verbs:подтвердиться{}, // подтвердиться на практике rus_verbs:плескаться{}, // плескаться на мелководье rus_verbs:расширяться{}, // расширяться на конце rus_verbs:подержать{}, // подержать на солнце rus_verbs:планироваться{}, // планироваться на общем собрании rus_verbs:сгинуть{}, // сгинуть на чужбине rus_verbs:замкнуться{}, // замкнуться на точке rus_verbs:закачаться{}, // закачаться на ветру rus_verbs:перечитывать{}, // перечитывать на ходу rus_verbs:перелететь{}, // перелететь на дельтаплане rus_verbs:оживать{}, // оживать на солнце rus_verbs:женить{}, // женить на богатой невесте rus_verbs:заглохнуть{}, // заглохнуть на старте rus_verbs:копаться{}, // копаться на полу rus_verbs:развлекаться{}, // развлекаться на дискотеке rus_verbs:печататься{}, // печататься на струйном принтере rus_verbs:обрываться{}, // обрываться на полуслове rus_verbs:ускакать{}, // ускакать на лошадке rus_verbs:подписывать{}, // подписывать на столе rus_verbs:добывать{}, // добывать на выработке rus_verbs:скопиться{}, // скопиться на выходе rus_verbs:повстречать{}, // повстречать на пути rus_verbs:поцеловаться{}, // поцеловаться на площади rus_verbs:растянуть{}, // растянуть на столе rus_verbs:подаваться{}, // подаваться на благотворительном обеде rus_verbs:повстречаться{}, // повстречаться на митинге rus_verbs:примоститься{}, // примоститься на ступеньках rus_verbs:отразить{}, // отразить на страницах доклада rus_verbs:пояснять{}, // пояснять на страницах приложения rus_verbs:накормить{}, // накормить на кухне rus_verbs:поужинать{}, // поужинать на веранде инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть на митинге деепричастие:спев{}, инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш }, rus_verbs:топить{}, // топить на мелководье rus_verbs:освоить{}, // освоить на практике rus_verbs:распластаться{}, // распластаться на травке rus_verbs:отплыть{}, // отплыть на старом каяке rus_verbs:улетать{}, // улетать на любом самолете rus_verbs:отстаивать{}, // отстаивать на корте rus_verbs:осуждать{}, // осуждать на словах rus_verbs:переговорить{}, // переговорить на обеде rus_verbs:укрыть{}, // укрыть на чердаке rus_verbs:томиться{}, // томиться на привязи rus_verbs:сжигать{}, // сжигать на полигоне rus_verbs:позавтракать{}, // позавтракать на лоне природы rus_verbs:функционировать{}, // функционирует на солнечной энергии rus_verbs:разместить{}, // разместить на сайте rus_verbs:пронести{}, // пронести на теле rus_verbs:нашарить{}, // нашарить на столе rus_verbs:корчиться{}, // корчиться на полу rus_verbs:распознать{}, // распознать на снимке rus_verbs:повеситься{}, // повеситься на шнуре rus_verbs:обозначиться{}, // обозначиться на картах rus_verbs:оступиться{}, // оступиться на скользком льду rus_verbs:подносить{}, // подносить на блюдечке rus_verbs:расстелить{}, // расстелить на газоне rus_verbs:обсуждаться{}, // обсуждаться на собрании rus_verbs:расписаться{}, // расписаться на бланке rus_verbs:плестись{}, // плестись на привязи rus_verbs:объявиться{}, // объявиться на сцене rus_verbs:повышаться{}, // повышаться на первом датчике rus_verbs:разрабатывать{}, // разрабатывать на заводе rus_verbs:прерывать{}, // прерывать на середине rus_verbs:каяться{}, // каяться на публике rus_verbs:освоиться{}, // освоиться на лошади rus_verbs:подплыть{}, // подплыть на плоту rus_verbs:оскорбить{}, // оскорбить на митинге rus_verbs:торжествовать{}, // торжествовать на пьедестале rus_verbs:поправлять{}, // поправлять на одежде rus_verbs:отражать{}, // отражать на картине rus_verbs:дремать{}, // дремать на кушетке rus_verbs:применяться{}, // применяться на производстве стали rus_verbs:поражать{}, // поражать на большой дистанции rus_verbs:расстрелять{}, // расстрелять на окраине хутора rus_verbs:рассчитать{}, // рассчитать на калькуляторе rus_verbs:записывать{}, // записывать на ленте rus_verbs:перебирать{}, // перебирать на ладони rus_verbs:разбиться{}, // разбиться на катере rus_verbs:поискать{}, // поискать на ферме rus_verbs:прятать{}, // прятать на заброшенном складе rus_verbs:пропеть{}, // пропеть на эстраде rus_verbs:замелькать{}, // замелькать на экране rus_verbs:грустить{}, // грустить на веранде rus_verbs:крутить{}, // крутить на оси rus_verbs:подготовить{}, // подготовить на конспиративной квартире rus_verbs:различать{}, // различать на картинке rus_verbs:киснуть{}, // киснуть на чужбине rus_verbs:оборваться{}, // оборваться на полуслове rus_verbs:запутаться{}, // запутаться на простейшем тесте rus_verbs:общаться{}, // общаться на уроке rus_verbs:производиться{}, // производиться на фабрике rus_verbs:сочинить{}, // сочинить на досуге rus_verbs:давить{}, // давить на лице rus_verbs:разработать{}, // разработать на секретном предприятии rus_verbs:качать{}, // качать на качелях rus_verbs:тушить{}, // тушить на крыше пожар rus_verbs:охранять{}, // охранять на территории базы rus_verbs:приметить{}, // приметить на взгорке rus_verbs:скрыть{}, // скрыть на теле rus_verbs:удерживать{}, // удерживать на руке rus_verbs:усвоить{}, // усвоить на уроке rus_verbs:растаять{}, // растаять на солнечной стороне rus_verbs:красоваться{}, // красоваться на виду rus_verbs:сохраняться{}, // сохраняться на холоде rus_verbs:лечить{}, // лечить на дому rus_verbs:прокатиться{}, // прокатиться на уницикле rus_verbs:договариваться{}, // договариваться на нейтральной территории rus_verbs:качнуться{}, // качнуться на одной ноге rus_verbs:опубликовать{}, // опубликовать на сайте rus_verbs:отражаться{}, // отражаться на поверхности воды rus_verbs:обедать{}, // обедать на веранде rus_verbs:посидеть{}, // посидеть на лавочке rus_verbs:сообщаться{}, // сообщаться на официальном сайте rus_verbs:свершиться{}, // свершиться на заседании rus_verbs:ночевать{}, // ночевать на даче rus_verbs:темнеть{}, // темнеть на свету rus_verbs:гибнуть{}, // гибнуть на территории полигона rus_verbs:усиливаться{}, // усиливаться на территории округа rus_verbs:проживать{}, // проживать на даче rus_verbs:исследовать{}, // исследовать на большой глубине rus_verbs:обитать{}, // обитать на громадной глубине rus_verbs:сталкиваться{}, // сталкиваться на большой высоте rus_verbs:таиться{}, // таиться на большой глубине rus_verbs:спасать{}, // спасать на пожаре rus_verbs:сказываться{}, // сказываться на общем результате rus_verbs:заблудиться{}, // заблудиться на стройке rus_verbs:пошарить{}, // пошарить на полках rus_verbs:планировать{}, // планировать на бумаге rus_verbs:ранить{}, // ранить на полигоне rus_verbs:хлопать{}, // хлопать на сцене rus_verbs:основать{}, // основать на горе новый монастырь rus_verbs:отбить{}, // отбить на столе rus_verbs:отрицать{}, // отрицать на заседании комиссии rus_verbs:устоять{}, // устоять на ногах rus_verbs:отзываться{}, // отзываться на страницах отчёта rus_verbs:притормозить{}, // притормозить на обочине rus_verbs:читаться{}, // читаться на лице rus_verbs:заиграть{}, // заиграть на саксофоне rus_verbs:зависнуть{}, // зависнуть на игровой площадке rus_verbs:сознаться{}, // сознаться на допросе rus_verbs:выясняться{}, // выясняться на очной ставке rus_verbs:наводить{}, // наводить на столе порядок rus_verbs:покоиться{}, // покоиться на кладбище rus_verbs:значиться{}, // значиться на бейджике rus_verbs:съехать{}, // съехать на санках rus_verbs:познакомить{}, // познакомить на свадьбе rus_verbs:завязать{}, // завязать на спине rus_verbs:грохнуть{}, // грохнуть на площади rus_verbs:разъехаться{}, // разъехаться на узкой дороге rus_verbs:столпиться{}, // столпиться на крыльце rus_verbs:порыться{}, // порыться на полках rus_verbs:ослабить{}, // ослабить на шее rus_verbs:оправдывать{}, // оправдывать на суде rus_verbs:обнаруживаться{}, // обнаруживаться на складе rus_verbs:спастись{}, // спастись на дереве rus_verbs:прерваться{}, // прерваться на полуслове rus_verbs:строиться{}, // строиться на пустыре rus_verbs:познать{}, // познать на практике rus_verbs:путешествовать{}, // путешествовать на поезде rus_verbs:побеждать{}, // побеждать на ринге rus_verbs:рассматриваться{}, // рассматриваться на заседании rus_verbs:продаваться{}, // продаваться на открытом рынке rus_verbs:разместиться{}, // разместиться на базе rus_verbs:завыть{}, // завыть на холме rus_verbs:настигнуть{}, // настигнуть на окраине rus_verbs:укрыться{}, // укрыться на чердаке rus_verbs:расплакаться{}, // расплакаться на заседании комиссии rus_verbs:заканчивать{}, // заканчивать на последнем задании rus_verbs:пролежать{}, // пролежать на столе rus_verbs:громоздиться{}, // громоздиться на полу rus_verbs:замерзнуть{}, // замерзнуть на открытом воздухе rus_verbs:поскользнуться{}, // поскользнуться на льду rus_verbs:таскать{}, // таскать на спине rus_verbs:просматривать{}, // просматривать на сайте rus_verbs:обдумать{}, // обдумать на досуге rus_verbs:гадать{}, // гадать на кофейной гуще rus_verbs:останавливать{}, // останавливать на выходе rus_verbs:обозначать{}, // обозначать на странице rus_verbs:долететь{}, // долететь на спортивном байке rus_verbs:тесниться{}, // тесниться на чердачке rus_verbs:хоронить{}, // хоронить на частном кладбище rus_verbs:установиться{}, // установиться на юге rus_verbs:прикидывать{}, // прикидывать на клочке бумаги rus_verbs:затаиться{}, // затаиться на дереве rus_verbs:раздобыть{}, // раздобыть на складе rus_verbs:перебросить{}, // перебросить на вертолетах rus_verbs:захватывать{}, // захватывать на базе rus_verbs:сказаться{}, // сказаться на итоговых оценках rus_verbs:покачиваться{}, // покачиваться на волнах rus_verbs:крутиться{}, // крутиться на кухне rus_verbs:помещаться{}, // помещаться на полке rus_verbs:питаться{}, // питаться на помойке rus_verbs:отдохнуть{}, // отдохнуть на загородной вилле rus_verbs:кататься{}, // кататься на велике rus_verbs:поработать{}, // поработать на стройке rus_verbs:ограбить{}, // ограбить на пустыре rus_verbs:зарабатывать{}, // зарабатывать на бирже rus_verbs:преуспеть{}, // преуспеть на ниве искусства rus_verbs:заерзать{}, // заерзать на стуле rus_verbs:разъяснить{}, // разъяснить на полях rus_verbs:отчеканить{}, // отчеканить на медной пластине rus_verbs:торговать{}, // торговать на рынке rus_verbs:поколебаться{}, // поколебаться на пороге rus_verbs:прикинуть{}, // прикинуть на бумажке rus_verbs:рассечь{}, // рассечь на тупом конце rus_verbs:посмеяться{}, // посмеяться на переменке rus_verbs:остыть{}, // остыть на морозном воздухе rus_verbs:запереться{}, // запереться на чердаке rus_verbs:обогнать{}, // обогнать на повороте rus_verbs:подтянуться{}, // подтянуться на турнике rus_verbs:привозить{}, // привозить на машине rus_verbs:подбирать{}, // подбирать на полу rus_verbs:уничтожать{}, // уничтожать на подходе rus_verbs:притаиться{}, // притаиться на вершине rus_verbs:плясать{}, // плясать на костях rus_verbs:поджидать{}, // поджидать на вокзале rus_verbs:закончить{}, // Мы закончили игру на самом интересном месте (САМ не может быть первым прилагательным в цепочке!) rus_verbs:смениться{}, // смениться на посту rus_verbs:посчитать{}, // посчитать на пальцах rus_verbs:прицелиться{}, // прицелиться на бегу rus_verbs:нарисовать{}, // нарисовать на стене rus_verbs:прыгать{}, // прыгать на сцене rus_verbs:повертеть{}, // повертеть на пальце rus_verbs:попрощаться{}, // попрощаться на панихиде инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на диване rus_verbs:разобрать{}, // разобрать на столе rus_verbs:помереть{}, // помереть на чужбине rus_verbs:различить{}, // различить на нечеткой фотографии rus_verbs:рисовать{}, // рисовать на доске rus_verbs:проследить{}, // проследить на экране rus_verbs:задремать{}, // задремать на диване rus_verbs:ругаться{}, // ругаться на людях rus_verbs:сгореть{}, // сгореть на работе rus_verbs:зазвучать{}, // зазвучать на коротких волнах rus_verbs:задохнуться{}, // задохнуться на вершине горы rus_verbs:порождать{}, // порождать на поверхности небольшую рябь rus_verbs:отдыхать{}, // отдыхать на курорте rus_verbs:образовать{}, // образовать на дне толстый слой rus_verbs:поправиться{}, // поправиться на дармовых харчах rus_verbs:отмечать{}, // отмечать на календаре rus_verbs:реять{}, // реять на флагштоке rus_verbs:ползти{}, // ползти на коленях rus_verbs:продавать{}, // продавать на аукционе rus_verbs:сосредоточиться{}, // сосредоточиться на основной задаче rus_verbs:рыскать{}, // мышки рыскали на кухне rus_verbs:расстегнуть{}, // расстегнуть на куртке все пуговицы rus_verbs:напасть{}, // напасть на территории другого государства rus_verbs:издать{}, // издать на западе rus_verbs:оставаться{}, // оставаться на страже порядка rus_verbs:появиться{}, // наконец появиться на экране rus_verbs:лежать{}, // лежать на столе rus_verbs:ждать{}, // ждать на берегу инфинитив:писать{aux stress="пис^ать"}, // писать на бумаге глагол:писать{aux stress="пис^ать"}, rus_verbs:оказываться{}, // оказываться на полу rus_verbs:поставить{}, // поставить на столе rus_verbs:держать{}, // держать на крючке rus_verbs:выходить{}, // выходить на остановке rus_verbs:заговорить{}, // заговорить на китайском языке rus_verbs:ожидать{}, // ожидать на стоянке rus_verbs:закричать{}, // закричал на минарете муэдзин rus_verbs:простоять{}, // простоять на посту rus_verbs:продолжить{}, // продолжить на первом этаже rus_verbs:ощутить{}, // ощутить на себе влияние кризиса rus_verbs:состоять{}, // состоять на учете rus_verbs:готовиться{}, инфинитив:акклиматизироваться{вид:несоверш}, // альпинисты готовятся акклиматизироваться на новой высоте глагол:акклиматизироваться{вид:несоверш}, rus_verbs:арестовать{}, // грабители были арестованы на месте преступления rus_verbs:схватить{}, // грабители были схвачены на месте преступления инфинитив:атаковать{ вид:соверш }, // взвод был атакован на границе глагол:атаковать{ вид:соверш }, прилагательное:атакованный{ вид:соверш }, прилагательное:атаковавший{ вид:соверш }, rus_verbs:базировать{}, // установка будет базирована на границе rus_verbs:базироваться{}, // установка базируется на границе rus_verbs:барахтаться{}, // дети барахтались на мелководье rus_verbs:браконьерить{}, // Охотники браконьерили ночью на реке rus_verbs:браконьерствовать{}, // Охотники ночью браконьерствовали на реке rus_verbs:бренчать{}, // парень что-то бренчал на гитаре rus_verbs:бренькать{}, // парень что-то бренькает на гитаре rus_verbs:начать{}, // Рынок акций РФ начал торги на отрицательной территории. rus_verbs:буксовать{}, // Колеса буксуют на льду rus_verbs:вертеться{}, // Непоседливый ученик много вертится на стуле rus_verbs:взвести{}, // Боец взвел на оружии предохранитель rus_verbs:вилять{}, // Машина сильно виляла на дороге rus_verbs:висеть{}, // Яблоко висит на ветке rus_verbs:возлежать{}, // возлежать на лежанке rus_verbs:подниматься{}, // Мы поднимаемся на лифте rus_verbs:подняться{}, // Мы поднимемся на лифте rus_verbs:восседать{}, // Коля восседает на лошади rus_verbs:воссиять{}, // Луна воссияла на небе rus_verbs:воцариться{}, // Мир воцарился на всей земле rus_verbs:воцаряться{}, // Мир воцаряется на всей земле rus_verbs:вращать{}, // вращать на поясе rus_verbs:вращаться{}, // вращаться на поясе rus_verbs:встретить{}, // встретить друга на улице rus_verbs:встретиться{}, // встретиться на занятиях rus_verbs:встречать{}, // встречать на занятиях rus_verbs:въебывать{}, // въебывать на работе rus_verbs:въезжать{}, // въезжать на автомобиле rus_verbs:въехать{}, // въехать на автомобиле rus_verbs:выгорать{}, // ткань выгорает на солнце rus_verbs:выгореть{}, // ткань выгорела на солнце rus_verbs:выгравировать{}, // выгравировать на табличке надпись rus_verbs:выжить{}, // выжить на необитаемом острове rus_verbs:вылежаться{}, // помидоры вылежались на солнце rus_verbs:вылеживаться{}, // вылеживаться на солнце rus_verbs:выместить{}, // выместить на ком-то злобу rus_verbs:вымещать{}, // вымещать на ком-то свое раздражение rus_verbs:вымещаться{}, // вымещаться на ком-то rus_verbs:выращивать{}, // выращивать на грядке помидоры rus_verbs:выращиваться{}, // выращиваться на грядке инфинитив:вырезать{вид:соверш}, // вырезать на доске надпись глагол:вырезать{вид:соверш}, инфинитив:вырезать{вид:несоверш}, глагол:вырезать{вид:несоверш}, rus_verbs:вырисоваться{}, // вырисоваться на графике rus_verbs:вырисовываться{}, // вырисовываться на графике rus_verbs:высаживать{}, // высаживать на необитаемом острове rus_verbs:высаживаться{}, // высаживаться на острове rus_verbs:высвечивать{}, // высвечивать на дисплее температуру rus_verbs:высвечиваться{}, // высвечиваться на дисплее rus_verbs:выстроить{}, // выстроить на фундаменте rus_verbs:выстроиться{}, // выстроиться на плацу rus_verbs:выстудить{}, // выстудить на морозе rus_verbs:выстудиться{}, // выстудиться на морозе rus_verbs:выстужать{}, // выстужать на морозе rus_verbs:выстуживать{}, // выстуживать на морозе rus_verbs:выстуживаться{}, // выстуживаться на морозе rus_verbs:выстукать{}, // выстукать на клавиатуре rus_verbs:выстукивать{}, // выстукивать на клавиатуре rus_verbs:выстукиваться{}, // выстукиваться на клавиатуре rus_verbs:выступать{}, // выступать на сцене rus_verbs:выступить{}, // выступить на сцене rus_verbs:выстучать{}, // выстучать на клавиатуре rus_verbs:выстывать{}, // выстывать на морозе rus_verbs:выстыть{}, // выстыть на морозе rus_verbs:вытатуировать{}, // вытатуировать на руке якорь rus_verbs:говорить{}, // говорить на повышенных тонах rus_verbs:заметить{}, // заметить на берегу rus_verbs:стоять{}, // твёрдо стоять на ногах rus_verbs:оказаться{}, // оказаться на передовой линии rus_verbs:почувствовать{}, // почувствовать на своей шкуре rus_verbs:остановиться{}, // остановиться на первом пункте rus_verbs:показаться{}, // показаться на горизонте rus_verbs:чувствовать{}, // чувствовать на своей шкуре rus_verbs:искать{}, // искать на открытом пространстве rus_verbs:иметься{}, // иметься на складе rus_verbs:клясться{}, // клясться на Коране rus_verbs:прервать{}, // прервать на полуслове rus_verbs:играть{}, // играть на чувствах rus_verbs:спуститься{}, // спуститься на парашюте rus_verbs:понадобиться{}, // понадобиться на экзамене rus_verbs:служить{}, // служить на флоте rus_verbs:подобрать{}, // подобрать на улице rus_verbs:появляться{}, // появляться на сцене rus_verbs:селить{}, // селить на чердаке rus_verbs:поймать{}, // поймать на границе rus_verbs:увидать{}, // увидать на опушке rus_verbs:подождать{}, // подождать на перроне rus_verbs:прочесть{}, // прочесть на полях rus_verbs:тонуть{}, // тонуть на мелководье rus_verbs:ощущать{}, // ощущать на коже rus_verbs:отметить{}, // отметить на полях rus_verbs:показывать{}, // показывать на графике rus_verbs:разговаривать{}, // разговаривать на иностранном языке rus_verbs:прочитать{}, // прочитать на сайте rus_verbs:попробовать{}, // попробовать на практике rus_verbs:замечать{}, // замечать на коже грязь rus_verbs:нести{}, // нести на плечах rus_verbs:носить{}, // носить на голове rus_verbs:гореть{}, // гореть на работе rus_verbs:застыть{}, // застыть на пороге инфинитив:жениться{ вид:соверш }, // жениться на королеве глагол:жениться{ вид:соверш }, прилагательное:женатый{}, прилагательное:женившийся{}, rus_verbs:спрятать{}, // спрятать на чердаке rus_verbs:развернуться{}, // развернуться на плацу rus_verbs:строить{}, // строить на песке rus_verbs:устроить{}, // устроить на даче тестральный вечер rus_verbs:настаивать{}, // настаивать на выполнении приказа rus_verbs:находить{}, // находить на берегу rus_verbs:мелькнуть{}, // мелькнуть на экране rus_verbs:очутиться{}, // очутиться на опушке леса инфинитив:использовать{вид:соверш}, // использовать на работе глагол:использовать{вид:соверш}, инфинитив:использовать{вид:несоверш}, глагол:использовать{вид:несоверш}, прилагательное:использованный{}, прилагательное:использующий{}, прилагательное:использовавший{}, rus_verbs:лететь{}, // лететь на воздушном шаре rus_verbs:смеяться{}, // смеяться на сцене rus_verbs:ездить{}, // ездить на мопеде rus_verbs:заснуть{}, // заснуть на диване rus_verbs:застать{}, // застать на рабочем месте rus_verbs:очнуться{}, // очнуться на больничной койке rus_verbs:разглядеть{}, // разглядеть на фотографии rus_verbs:обойти{}, // обойти на вираже rus_verbs:удержаться{}, // удержаться на троне rus_verbs:побывать{}, // побывать на другой планете rus_verbs:заняться{}, // заняться на выходных делом rus_verbs:вянуть{}, // вянуть на солнце rus_verbs:постоять{}, // постоять на голове rus_verbs:приобрести{}, // приобрести на распродаже rus_verbs:попасться{}, // попасться на краже rus_verbs:продолжаться{}, // продолжаться на земле rus_verbs:открывать{}, // открывать на арене rus_verbs:создавать{}, // создавать на сцене rus_verbs:обсуждать{}, // обсуждать на кухне rus_verbs:отыскать{}, // отыскать на полу rus_verbs:уснуть{}, // уснуть на диване rus_verbs:задержаться{}, // задержаться на работе rus_verbs:курить{}, // курить на свежем воздухе rus_verbs:приподняться{}, // приподняться на локтях rus_verbs:установить{}, // установить на вершине rus_verbs:запереть{}, // запереть на балконе rus_verbs:синеть{}, // синеть на воздухе rus_verbs:убивать{}, // убивать на нейтральной территории rus_verbs:скрываться{}, // скрываться на даче rus_verbs:родить{}, // родить на полу rus_verbs:описать{}, // описать на страницах книги rus_verbs:перехватить{}, // перехватить на подлете rus_verbs:скрывать{}, // скрывать на даче rus_verbs:сменить{}, // сменить на посту rus_verbs:мелькать{}, // мелькать на экране rus_verbs:присутствовать{}, // присутствовать на мероприятии rus_verbs:украсть{}, // украсть на рынке rus_verbs:победить{}, // победить на ринге rus_verbs:упомянуть{}, // упомянуть на страницах романа rus_verbs:плыть{}, // плыть на старой лодке rus_verbs:повиснуть{}, // повиснуть на перекладине rus_verbs:нащупать{}, // нащупать на дне rus_verbs:затихнуть{}, // затихнуть на дне rus_verbs:построить{}, // построить на участке rus_verbs:поддерживать{}, // поддерживать на поверхности rus_verbs:заработать{}, // заработать на бирже rus_verbs:провалиться{}, // провалиться на экзамене rus_verbs:сохранить{}, // сохранить на диске rus_verbs:располагаться{}, // располагаться на софе rus_verbs:поклясться{}, // поклясться на библии rus_verbs:сражаться{}, // сражаться на арене rus_verbs:спускаться{}, // спускаться на дельтаплане rus_verbs:уничтожить{}, // уничтожить на подступах rus_verbs:изучить{}, // изучить на практике rus_verbs:рождаться{}, // рождаться на праздниках rus_verbs:прилететь{}, // прилететь на самолете rus_verbs:догнать{}, // догнать на перекрестке rus_verbs:изобразить{}, // изобразить на бумаге rus_verbs:проехать{}, // проехать на тракторе rus_verbs:приготовить{}, // приготовить на масле rus_verbs:споткнуться{}, // споткнуться на полу rus_verbs:собирать{}, // собирать на берегу rus_verbs:отсутствовать{}, // отсутствовать на тусовке rus_verbs:приземлиться{}, // приземлиться на военном аэродроме rus_verbs:сыграть{}, // сыграть на трубе rus_verbs:прятаться{}, // прятаться на даче rus_verbs:спрятаться{}, // спрятаться на чердаке rus_verbs:провозгласить{}, // провозгласить на митинге rus_verbs:изложить{}, // изложить на бумаге rus_verbs:использоваться{}, // использоваться на практике rus_verbs:замяться{}, // замяться на входе rus_verbs:раздаваться{}, // Крик ягуара раздается на краю болота rus_verbs:сверкнуть{}, // сверкнуть на солнце rus_verbs:сверкать{}, // сверкать на свету rus_verbs:задержать{}, // задержать на митинге rus_verbs:осечься{}, // осечься на первом слове rus_verbs:хранить{}, // хранить на банковском счету rus_verbs:шутить{}, // шутить на уроке rus_verbs:кружиться{}, // кружиться на балу rus_verbs:чертить{}, // чертить на доске rus_verbs:отразиться{}, // отразиться на оценках rus_verbs:греть{}, // греть на солнце rus_verbs:рассуждать{}, // рассуждать на страницах своей книги rus_verbs:окружать{}, // окружать на острове rus_verbs:сопровождать{}, // сопровождать на охоте rus_verbs:заканчиваться{}, // заканчиваться на самом интересном месте rus_verbs:содержаться{}, // содержаться на приусадебном участке rus_verbs:поселиться{}, // поселиться на даче rus_verbs:запеть{}, // запеть на сцене инфинитив:провозить{ вид:несоверш }, // провозить на теле глагол:провозить{ вид:несоверш }, прилагательное:провезенный{}, прилагательное:провозивший{вид:несоверш}, прилагательное:провозящий{вид:несоверш}, деепричастие:провозя{}, rus_verbs:мочить{}, // мочить на месте rus_verbs:преследовать{}, // преследовать на территории другого штата rus_verbs:пролететь{}, // пролетел на параплане rus_verbs:драться{}, // драться на рапирах rus_verbs:просидеть{}, // просидеть на занятиях rus_verbs:убираться{}, // убираться на балконе rus_verbs:таять{}, // таять на солнце rus_verbs:проверять{}, // проверять на полиграфе rus_verbs:убеждать{}, // убеждать на примере rus_verbs:скользить{}, // скользить на льду rus_verbs:приобретать{}, // приобретать на распродаже rus_verbs:летать{}, // летать на метле rus_verbs:толпиться{}, // толпиться на перроне rus_verbs:плавать{}, // плавать на надувном матрасе rus_verbs:описывать{}, // описывать на страницах повести rus_verbs:пробыть{}, // пробыть на солнце слишком долго rus_verbs:застрять{}, // застрять на верхнем этаже rus_verbs:метаться{}, // метаться на полу rus_verbs:сжечь{}, // сжечь на костре rus_verbs:расслабиться{}, // расслабиться на кушетке rus_verbs:услыхать{}, // услыхать на рынке rus_verbs:удержать{}, // удержать на прежнем уровне rus_verbs:образоваться{}, // образоваться на дне rus_verbs:рассмотреть{}, // рассмотреть на поверхности чипа rus_verbs:уезжать{}, // уезжать на попутке rus_verbs:похоронить{}, // похоронить на закрытом кладбище rus_verbs:настоять{}, // настоять на пересмотре оценок rus_verbs:растянуться{}, // растянуться на горячем песке rus_verbs:покрутить{}, // покрутить на шесте rus_verbs:обнаружиться{}, // обнаружиться на болоте rus_verbs:гулять{}, // гулять на свадьбе rus_verbs:утонуть{}, // утонуть на курорте rus_verbs:храниться{}, // храниться на депозите rus_verbs:танцевать{}, // танцевать на свадьбе rus_verbs:трудиться{}, // трудиться на заводе инфинитив:засыпать{переходность:непереходный вид:несоверш}, // засыпать на кровати глагол:засыпать{переходность:непереходный вид:несоверш}, деепричастие:засыпая{переходность:непереходный вид:несоверш}, прилагательное:засыпавший{переходность:непереходный вид:несоверш}, прилагательное:засыпающий{ вид:несоверш переходность:непереходный }, // ребенок, засыпающий на руках rus_verbs:сушить{}, // сушить на открытом воздухе rus_verbs:зашевелиться{}, // зашевелиться на чердаке rus_verbs:обдумывать{}, // обдумывать на досуге rus_verbs:докладывать{}, // докладывать на научной конференции rus_verbs:промелькнуть{}, // промелькнуть на экране // прилагательное:находящийся{ вид:несоверш }, // колонна, находящаяся на ничейной территории прилагательное:написанный{}, // слово, написанное на заборе rus_verbs:умещаться{}, // компьютер, умещающийся на ладони rus_verbs:открыть{}, // книга, открытая на последней странице rus_verbs:спать{}, // йог, спящий на гвоздях rus_verbs:пробуксовывать{}, // колесо, пробуксовывающее на обледенелом асфальте rus_verbs:забуксовать{}, // колесо, забуксовавшее на обледенелом асфальте rus_verbs:отобразиться{}, // удивление, отобразившееся на лице rus_verbs:увидеть{}, // на полу я увидел чьи-то следы rus_verbs:видеть{}, // на полу я вижу чьи-то следы rus_verbs:оставить{}, // Мел оставил на доске белый след. rus_verbs:оставлять{}, // Мел оставляет на доске белый след. rus_verbs:встречаться{}, // встречаться на лекциях rus_verbs:познакомиться{}, // познакомиться на занятиях rus_verbs:устроиться{}, // она устроилась на кровати rus_verbs:ложиться{}, // ложись на полу rus_verbs:останавливаться{}, // останавливаться на достигнутом rus_verbs:спотыкаться{}, // спотыкаться на ровном месте rus_verbs:распечатать{}, // распечатать на бумаге rus_verbs:распечатывать{}, // распечатывать на бумаге rus_verbs:просмотреть{}, // просмотреть на бумаге rus_verbs:закрепляться{}, // закрепляться на плацдарме rus_verbs:погреться{}, // погреться на солнышке rus_verbs:мешать{}, // Он мешал краски на палитре. rus_verbs:занять{}, // Он занял первое место на соревнованиях. rus_verbs:заговариваться{}, // Он заговаривался иногда на уроках. деепричастие:женившись{ вид:соверш }, rus_verbs:везти{}, // Он везёт песок на тачке. прилагательное:казненный{}, // Он был казнён на электрическом стуле. rus_verbs:прожить{}, // Он безвыездно прожил всё лето на даче. rus_verbs:принести{}, // Официантка принесла нам обед на подносе. rus_verbs:переписать{}, // Перепишите эту рукопись на машинке. rus_verbs:идти{}, // Поезд идёт на малой скорости. rus_verbs:петь{}, // птички поют на рассвете rus_verbs:смотреть{}, // Смотри на обороте. rus_verbs:прибрать{}, // прибрать на столе rus_verbs:прибраться{}, // прибраться на столе rus_verbs:растить{}, // растить капусту на огороде rus_verbs:тащить{}, // тащить ребенка на руках rus_verbs:убирать{}, // убирать на столе rus_verbs:простыть{}, // Я простыл на морозе. rus_verbs:сиять{}, // ясные звезды мирно сияли на безоблачном весеннем небе. rus_verbs:проводиться{}, // такие эксперименты не проводятся на воде rus_verbs:достать{}, // Я не могу достать до яблок на верхних ветках. rus_verbs:расплыться{}, // Чернила расплылись на плохой бумаге. rus_verbs:вскочить{}, // У него вскочил прыщ на носу. rus_verbs:свить{}, // У нас на балконе воробей свил гнездо. rus_verbs:оторваться{}, // У меня на пальто оторвалась пуговица. rus_verbs:восходить{}, // Солнце восходит на востоке. rus_verbs:блестеть{}, // Снег блестит на солнце. rus_verbs:побить{}, // Рысак побил всех лошадей на скачках. rus_verbs:литься{}, // Реки крови льются на войне. rus_verbs:держаться{}, // Ребёнок уже твёрдо держится на ногах. rus_verbs:клубиться{}, // Пыль клубится на дороге. инфинитив:написать{ aux stress="напис^ать" }, // Ты должен написать статью на английском языке глагол:написать{ aux stress="напис^ать" }, // Он написал статью на русском языке. // глагол:находиться{вид:несоверш}, // мой поезд находится на первом пути // инфинитив:находиться{вид:несоверш}, rus_verbs:жить{}, // Было интересно жить на курорте. rus_verbs:повидать{}, // Он много повидал на своём веку. rus_verbs:разъезжаться{}, // Ноги разъезжаются не только на льду. rus_verbs:расположиться{}, // Оба села расположились на берегу реки. rus_verbs:объясняться{}, // Они объясняются на иностранном языке. rus_verbs:прощаться{}, // Они долго прощались на вокзале. rus_verbs:работать{}, // Она работает на ткацкой фабрике. rus_verbs:купить{}, // Она купила молоко на рынке. rus_verbs:поместиться{}, // Все книги поместились на полке. глагол:проводить{вид:несоверш}, инфинитив:проводить{вид:несоверш}, // Нужно проводить теорию на практике. rus_verbs:пожить{}, // Недолго она пожила на свете. rus_verbs:краснеть{}, // Небо краснеет на закате. rus_verbs:бывать{}, // На Волге бывает сильное волнение. rus_verbs:ехать{}, // Мы туда ехали на автобусе. rus_verbs:провести{}, // Мы провели месяц на даче. rus_verbs:поздороваться{}, // Мы поздоровались при встрече на улице. rus_verbs:расти{}, // Арбузы растут теперь не только на юге. ГЛ_ИНФ(сидеть), // три больших пса сидят на траве ГЛ_ИНФ(сесть), // три больших пса сели на траву ГЛ_ИНФ(перевернуться), // На дороге перевернулся автомобиль ГЛ_ИНФ(повезти), // я повезу тебя на машине ГЛ_ИНФ(отвезти), // мы отвезем тебя на такси ГЛ_ИНФ(пить), // пить на кухне чай ГЛ_ИНФ(найти), // найти на острове ГЛ_ИНФ(быть), // на этих костях есть следы зубов ГЛ_ИНФ(высадиться), // помощники высадились на острове ГЛ_ИНФ(делать),прилагательное:делающий{}, прилагательное:делавший{}, деепричастие:делая{}, // смотрю фильм о том, что пираты делали на необитаемом острове ГЛ_ИНФ(случиться), // это случилось на опушке леса ГЛ_ИНФ(продать), ГЛ_ИНФ(есть) // кошки ели мой корм на песчаном берегу } #endregion VerbList // Чтобы разрешить связывание в паттернах типа: смотреть на youtube fact гл_предл { if context { Гл_НА_Предл предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_НА_Предл предлог:на{} *:*{падеж:предл} } then return true } // локатив fact гл_предл { if context { Гл_НА_Предл предлог:на{} *:*{падеж:мест} } then return true } #endregion ПРЕДЛОЖНЫЙ #region ВИНИТЕЛЬНЫЙ // НА+винительный падеж: // ЗАБИРАТЬСЯ НА ВЕРШИНУ ГОРЫ #region VerbList wordentry_set Гл_НА_Вин= { rus_verbs:переметнуться{}, // Ее взгляд растерянно переметнулся на Лили. rus_verbs:отогнать{}, // Водитель отогнал машину на стоянку. rus_verbs:фапать{}, // Не фапай на желтяк и не перебивай. rus_verbs:умножить{}, // Умножьте это количество примерно на 10. //rus_verbs:умножать{}, rus_verbs:откатить{}, // Откатил Шпак валун на шлях и перекрыл им дорогу. rus_verbs:откатывать{}, rus_verbs:доносить{}, // Вот и побежали на вас доносить. rus_verbs:донести{}, rus_verbs:разбирать{}, // Ворованные автомобили злоумышленники разбирали на запчасти и продавали. безлич_глагол:хватит{}, // - На одну атаку хватит. rus_verbs:скупиться{}, // Он сражался за жизнь, не скупясь на хитрости и усилия, и пока этот стиль давал неплохие результаты. rus_verbs:поскупиться{}, // Не поскупись на похвалы! rus_verbs:подыматься{}, rus_verbs:транспортироваться{}, rus_verbs:бахнуть{}, // Бахнуть стакан на пол rus_verbs:РАЗДЕЛИТЬ{}, // Президентские выборы разделили Венесуэлу на два непримиримых лагеря (РАЗДЕЛИТЬ) rus_verbs:НАЦЕЛИВАТЬСЯ{}, // Невдалеке пролетел кондор, нацеливаясь на бизонью тушу. (НАЦЕЛИВАТЬСЯ) rus_verbs:ВЫПЛЕСНУТЬ{}, // Низкий вибрирующий гул напоминал вулкан, вот-вот готовый выплеснуть на земную твердь потоки раскаленной лавы. (ВЫПЛЕСНУТЬ) rus_verbs:ИСЧЕЗНУТЬ{}, // Оно фыркнуло и исчезло в лесу на другой стороне дороги (ИСЧЕЗНУТЬ) rus_verbs:ВЫЗВАТЬ{}, // вызвать своего брата на поединок. (ВЫЗВАТЬ) rus_verbs:ПОБРЫЗГАТЬ{}, // Матрос побрызгал немного фимиама на крошечный огонь (ПОБРЫЗГАТЬ/БРЫЗГАТЬ/БРЫЗНУТЬ/КАПНУТЬ/КАПАТЬ/ПОКАПАТЬ) rus_verbs:БРЫЗГАТЬ{}, rus_verbs:БРЫЗНУТЬ{}, rus_verbs:КАПНУТЬ{}, rus_verbs:КАПАТЬ{}, rus_verbs:ПОКАПАТЬ{}, rus_verbs:ПООХОТИТЬСЯ{}, // Мы можем когда-нибудь вернуться и поохотиться на него. (ПООХОТИТЬСЯ/ОХОТИТЬСЯ) rus_verbs:ОХОТИТЬСЯ{}, // rus_verbs:ПОПАСТЬСЯ{}, // Не думал я, что они попадутся на это (ПОПАСТЬСЯ/НАРВАТЬСЯ/НАТОЛКНУТЬСЯ) rus_verbs:НАРВАТЬСЯ{}, // rus_verbs:НАТОЛКНУТЬСЯ{}, // rus_verbs:ВЫСЛАТЬ{}, // Он выслал разведчиков на большое расстояние от основного отряда. (ВЫСЛАТЬ) прилагательное:ПОХОЖИЙ{}, // Ты не выглядишь похожим на индейца (ПОХОЖИЙ) rus_verbs:РАЗОРВАТЬ{}, // Через минуту он был мертв и разорван на части. (РАЗОРВАТЬ) rus_verbs:СТОЛКНУТЬ{}, // Только быстрыми выпадами копья он сумел столкнуть их обратно на карниз. (СТОЛКНУТЬ/СТАЛКИВАТЬ) rus_verbs:СТАЛКИВАТЬ{}, // rus_verbs:СПУСТИТЬ{}, // Я побежал к ним, но они к тому времени спустили лодку на воду (СПУСТИТЬ) rus_verbs:ПЕРЕБРАСЫВАТЬ{}, // Сирия перебрасывает на юг страны воинские подкрепления (ПЕРЕБРАСЫВАТЬ, ПЕРЕБРОСИТЬ, НАБРАСЫВАТЬ, НАБРОСИТЬ) rus_verbs:ПЕРЕБРОСИТЬ{}, // rus_verbs:НАБРАСЫВАТЬ{}, // rus_verbs:НАБРОСИТЬ{}, // rus_verbs:СВЕРНУТЬ{}, // Он вывел машину на бульвар и поехал на восток, а затем свернул на юг. (СВЕРНУТЬ/СВОРАЧИВАТЬ/ПОВЕРНУТЬ/ПОВОРАЧИВАТЬ) rus_verbs:СВОРАЧИВАТЬ{}, // // rus_verbs:ПОВЕРНУТЬ{}, // rus_verbs:ПОВОРАЧИВАТЬ{}, // rus_verbs:наорать{}, rus_verbs:ПРОДВИНУТЬСЯ{}, // Полк продвинется на десятки километров (ПРОДВИНУТЬСЯ) rus_verbs:БРОСАТЬ{}, // Он бросает обещания на ветер (БРОСАТЬ) rus_verbs:ОДОЛЖИТЬ{}, // Я вам одолжу книгу на десять дней (ОДОЛЖИТЬ) rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое rus_verbs:перегонять{}, rus_verbs:выгонять{}, rus_verbs:выгнать{}, rus_verbs:СВОДИТЬСЯ{}, // сейчас панели кузовов расходятся по десяткам покрасочных постов и потом сводятся вновь на общий конвейер (СВОДИТЬСЯ) rus_verbs:ПОЖЕРТВОВАТЬ{}, // Бывший функционер компартии Эстонии пожертвовал деньги на расследования преступлений коммунизма (ПОЖЕРТВОВАТЬ) rus_verbs:ПРОВЕРЯТЬ{}, // Школьников будут принудительно проверять на курение (ПРОВЕРЯТЬ) rus_verbs:ОТПУСТИТЬ{}, // Приставы отпустят должников на отдых (ОТПУСТИТЬ) rus_verbs:использоваться{}, // имеющийся у государства денежный запас активно используется на поддержание рынка акций rus_verbs:назначаться{}, // назначаться на пост rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал rus_verbs:ШПИОНИТЬ{}, // Канадского офицера, шпионившего на Россию, приговорили к 20 годам тюрьмы (ШПИОНИТЬ НА вин) rus_verbs:ЗАПЛАНИРОВАТЬ{}, // все деньги , запланированные на сейсмоукрепление домов на Камчатке (ЗАПЛАНИРОВАТЬ НА) // rus_verbs:ПОХОДИТЬ{}, // больше походил на обвинительную речь , адресованную руководству республики (ПОХОДИТЬ НА) rus_verbs:ДЕЙСТВОВАТЬ{}, // выявленный контрабандный канал действовал на постоянной основе (ДЕЙСТВОВАТЬ НА) rus_verbs:ПЕРЕДАТЬ{}, // после чего должно быть передано на рассмотрение суда (ПЕРЕДАТЬ НА вин) rus_verbs:НАЗНАЧИТЬСЯ{}, // Зимой на эту должность пытался назначиться народный депутат (НАЗНАЧИТЬСЯ НА) rus_verbs:РЕШИТЬСЯ{}, // Франция решилась на одностороннее и рискованное военное вмешательство (РЕШИТЬСЯ НА) rus_verbs:ОРИЕНТИРОВАТЬ{}, // Этот браузер полностью ориентирован на планшеты и сенсорный ввод (ОРИЕНТИРОВАТЬ НА вин) rus_verbs:ЗАВЕСТИ{}, // на Витьку завели дело (ЗАВЕСТИ НА) rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА) rus_verbs:НАСТРАИВАТЬСЯ{}, // гетеродин, настраивающийся на волну (НАСТРАИВАТЬСЯ НА) rus_verbs:СУЩЕСТВОВАТЬ{}, // Он существует на средства родителей. (СУЩЕСТВОВАТЬ НА) прилагательное:способный{}, // Он способен на убийство. (СПОСОБНЫЙ НА) rus_verbs:посыпаться{}, // на Нину посыпались снежинки инфинитив:нарезаться{ вид:несоверш }, // Урожай собирают механически или вручную, стебли нарезаются на куски и быстро транспортируются на перерабатывающий завод. глагол:нарезаться{ вид:несоверш }, rus_verbs:пожаловать{}, // скандально известный певец пожаловал к нам на передачу rus_verbs:показать{}, // Вадим показал на Колю rus_verbs:съехаться{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА) прилагательное:тугой{}, // Бабушка туга на ухо. (ТУГОЙ НА) rus_verbs:свисать{}, // Волосы свисают на лоб. (свисать на) rus_verbs:ЦЕНИТЬСЯ{}, // Всякая рабочая рука ценилась на вес золота. (ЦЕНИТЬСЯ НА) rus_verbs:ШУМЕТЬ{}, // Вы шумите на весь дом! (ШУМЕТЬ НА) rus_verbs:протянуться{}, // Дорога протянулась на сотни километров. (протянуться на) rus_verbs:РАССЧИТАТЬ{}, // Книга рассчитана на массового читателя. (РАССЧИТАТЬ НА) rus_verbs:СОРИЕНТИРОВАТЬ{}, // мы сориентировали процесс на повышение котировок (СОРИЕНТИРОВАТЬ НА) rus_verbs:рыкнуть{}, // рыкнуть на остальных членов стаи (рыкнуть на) rus_verbs:оканчиваться{}, // оканчиваться на звонкую согласную (оканчиваться на) rus_verbs:выехать{}, // посигналить нарушителю, выехавшему на встречную полосу (выехать на) rus_verbs:прийтись{}, // Пятое число пришлось на субботу. rus_verbs:крениться{}, // корабль кренился на правый борт (крениться на) rus_verbs:приходиться{}, // основной налоговый гнет приходится на средний бизнес (приходиться на) rus_verbs:верить{}, // верить людям на слово (верить на слово) rus_verbs:выезжать{}, // Завтра вся семья выезжает на новую квартиру. rus_verbs:записать{}, // Запишите меня на завтрашний приём к доктору. rus_verbs:пасть{}, // Жребий пал на меня. rus_verbs:ездить{}, // Вчера мы ездили на оперу. rus_verbs:влезть{}, // Мальчик влез на дерево. rus_verbs:выбежать{}, // Мальчик выбежал из комнаты на улицу. rus_verbs:разбиться{}, // окно разбилось на мелкие осколки rus_verbs:бежать{}, // я бегу на урок rus_verbs:сбегаться{}, // сбегаться на происшествие rus_verbs:присылать{}, // присылать на испытание rus_verbs:надавить{}, // надавить на педать rus_verbs:внести{}, // внести законопроект на рассмотрение rus_verbs:вносить{}, // вносить законопроект на рассмотрение rus_verbs:поворачиваться{}, // поворачиваться на 180 градусов rus_verbs:сдвинуть{}, // сдвинуть на несколько сантиметров rus_verbs:опубликовать{}, // С.Митрохин опубликовал компромат на думских подельников Гудкова rus_verbs:вырасти{}, // Официальный курс доллара вырос на 26 копеек. rus_verbs:оглядываться{}, // оглядываться на девушек rus_verbs:расходиться{}, // расходиться на отдых rus_verbs:поскакать{}, // поскакать на службу rus_verbs:прыгать{}, // прыгать на сцену rus_verbs:приглашать{}, // приглашать на обед rus_verbs:рваться{}, // Кусок ткани рвется на части rus_verbs:понестись{}, // понестись на волю rus_verbs:распространяться{}, // распространяться на всех жителей штата инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на пол инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, деепричастие:просыпавшись{}, деепричастие:просыпаясь{}, rus_verbs:заехать{}, // заехать на пандус rus_verbs:разобрать{}, // разобрать на составляющие rus_verbs:опускаться{}, // опускаться на колени rus_verbs:переехать{}, // переехать на конспиративную квартиру rus_verbs:закрывать{}, // закрывать глаза на действия конкурентов rus_verbs:поместить{}, // поместить на поднос rus_verbs:отходить{}, // отходить на подготовленные позиции rus_verbs:сыпаться{}, // сыпаться на плечи rus_verbs:отвезти{}, // отвезти на занятия rus_verbs:накинуть{}, // накинуть на плечи rus_verbs:отлететь{}, // отлететь на пол rus_verbs:закинуть{}, // закинуть на чердак rus_verbs:зашипеть{}, // зашипеть на собаку rus_verbs:прогреметь{}, // прогреметь на всю страну rus_verbs:повалить{}, // повалить на стол rus_verbs:опереть{}, // опереть на фундамент rus_verbs:забросить{}, // забросить на антресоль rus_verbs:подействовать{}, // подействовать на материал rus_verbs:разделять{}, // разделять на части rus_verbs:прикрикнуть{}, // прикрикнуть на детей rus_verbs:разложить{}, // разложить на множители rus_verbs:провожать{}, // провожать на работу rus_verbs:катить{}, // катить на стройку rus_verbs:наложить{}, // наложить запрет на проведение операций с недвижимостью rus_verbs:сохранять{}, // сохранять на память rus_verbs:злиться{}, // злиться на друга rus_verbs:оборачиваться{}, // оборачиваться на свист rus_verbs:сползти{}, // сползти на землю rus_verbs:записывать{}, // записывать на ленту rus_verbs:загнать{}, // загнать на дерево rus_verbs:забормотать{}, // забормотать на ухо rus_verbs:протиснуться{}, // протиснуться на самый край rus_verbs:заторопиться{}, // заторопиться на вручение премии rus_verbs:гаркнуть{}, // гаркнуть на шалунов rus_verbs:навалиться{}, // навалиться на виновника всей толпой rus_verbs:проскользнуть{}, // проскользнуть на крышу дома rus_verbs:подтянуть{}, // подтянуть на палубу rus_verbs:скатиться{}, // скатиться на двойки rus_verbs:давить{}, // давить на жалость rus_verbs:намекнуть{}, // намекнуть на новые обстоятельства rus_verbs:замахнуться{}, // замахнуться на святое rus_verbs:заменить{}, // заменить на свежую салфетку rus_verbs:свалить{}, // свалить на землю rus_verbs:стекать{}, // стекать на оголенные провода rus_verbs:увеличиваться{}, // увеличиваться на сотню процентов rus_verbs:развалиться{}, // развалиться на части rus_verbs:сердиться{}, // сердиться на товарища rus_verbs:обронить{}, // обронить на пол rus_verbs:подсесть{}, // подсесть на наркоту rus_verbs:реагировать{}, // реагировать на импульсы rus_verbs:отпускать{}, // отпускать на волю rus_verbs:прогнать{}, // прогнать на рабочее место rus_verbs:ложить{}, // ложить на стол rus_verbs:рвать{}, // рвать на части rus_verbs:разлететься{}, // разлететься на кусочки rus_verbs:превышать{}, // превышать на существенную величину rus_verbs:сбиться{}, // сбиться на рысь rus_verbs:пристроиться{}, // пристроиться на хорошую работу rus_verbs:удрать{}, // удрать на пастбище rus_verbs:толкать{}, // толкать на преступление rus_verbs:посматривать{}, // посматривать на экран rus_verbs:набирать{}, // набирать на судно rus_verbs:отступать{}, // отступать на дерево rus_verbs:подуть{}, // подуть на молоко rus_verbs:плеснуть{}, // плеснуть на голову rus_verbs:соскользнуть{}, // соскользнуть на землю rus_verbs:затаить{}, // затаить на кого-то обиду rus_verbs:обижаться{}, // обижаться на Колю rus_verbs:смахнуть{}, // смахнуть на пол rus_verbs:застегнуть{}, // застегнуть на все пуговицы rus_verbs:спускать{}, // спускать на землю rus_verbs:греметь{}, // греметь на всю округу rus_verbs:скосить{}, // скосить на соседа глаз rus_verbs:отважиться{}, // отважиться на прыжок rus_verbs:литься{}, // литься на землю rus_verbs:порвать{}, // порвать на тряпки rus_verbs:проследовать{}, // проследовать на сцену rus_verbs:надевать{}, // надевать на голову rus_verbs:проскочить{}, // проскочить на красный свет rus_verbs:прилечь{}, // прилечь на диванчик rus_verbs:разделиться{}, // разделиться на небольшие группы rus_verbs:завыть{}, // завыть на луну rus_verbs:переносить{}, // переносить на другую машину rus_verbs:наговорить{}, // наговорить на сотню рублей rus_verbs:намекать{}, // намекать на новые обстоятельства rus_verbs:нападать{}, // нападать на охранников rus_verbs:убегать{}, // убегать на другое место rus_verbs:тратить{}, // тратить на развлечения rus_verbs:присаживаться{}, // присаживаться на корточки rus_verbs:переместиться{}, // переместиться на вторую линию rus_verbs:завалиться{}, // завалиться на диван rus_verbs:удалиться{}, // удалиться на покой rus_verbs:уменьшаться{}, // уменьшаться на несколько процентов rus_verbs:обрушить{}, // обрушить на голову rus_verbs:резать{}, // резать на части rus_verbs:умчаться{}, // умчаться на юг rus_verbs:навернуться{}, // навернуться на камень rus_verbs:примчаться{}, // примчаться на матч rus_verbs:издавать{}, // издавать на собственные средства rus_verbs:переключить{}, // переключить на другой язык rus_verbs:отправлять{}, // отправлять на пенсию rus_verbs:залечь{}, // залечь на дно rus_verbs:установиться{}, // установиться на диск rus_verbs:направлять{}, // направлять на дополнительное обследование rus_verbs:разрезать{}, // разрезать на части rus_verbs:оскалиться{}, // оскалиться на прохожего rus_verbs:рычать{}, // рычать на пьяных rus_verbs:погружаться{}, // погружаться на дно rus_verbs:опираться{}, // опираться на костыли rus_verbs:поторопиться{}, // поторопиться на учебу rus_verbs:сдвинуться{}, // сдвинуться на сантиметр rus_verbs:увеличить{}, // увеличить на процент rus_verbs:опускать{}, // опускать на землю rus_verbs:созвать{}, // созвать на митинг rus_verbs:делить{}, // делить на части rus_verbs:пробиться{}, // пробиться на заключительную часть rus_verbs:простираться{}, // простираться на много миль rus_verbs:забить{}, // забить на учебу rus_verbs:переложить{}, // переложить на чужие плечи rus_verbs:грохнуться{}, // грохнуться на землю rus_verbs:прорваться{}, // прорваться на сцену rus_verbs:разлить{}, // разлить на землю rus_verbs:укладываться{}, // укладываться на ночевку rus_verbs:уволить{}, // уволить на пенсию rus_verbs:наносить{}, // наносить на кожу rus_verbs:набежать{}, // набежать на берег rus_verbs:заявиться{}, // заявиться на стрельбище rus_verbs:налиться{}, // налиться на крышку rus_verbs:надвигаться{}, // надвигаться на берег rus_verbs:распустить{}, // распустить на каникулы rus_verbs:переключиться{}, // переключиться на другую задачу rus_verbs:чихнуть{}, // чихнуть на окружающих rus_verbs:шлепнуться{}, // шлепнуться на спину rus_verbs:устанавливать{}, // устанавливать на крышу rus_verbs:устанавливаться{}, // устанавливаться на крышу rus_verbs:устраиваться{}, // устраиваться на работу rus_verbs:пропускать{}, // пропускать на стадион инфинитив:сбегать{ вид:соверш }, глагол:сбегать{ вид:соверш }, // сбегать на фильм инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, деепричастие:сбегав{}, деепричастие:сбегая{}, rus_verbs:показываться{}, // показываться на глаза rus_verbs:прибегать{}, // прибегать на урок rus_verbs:съездить{}, // съездить на ферму rus_verbs:прославиться{}, // прославиться на всю страну rus_verbs:опрокинуться{}, // опрокинуться на спину rus_verbs:насыпать{}, // насыпать на землю rus_verbs:употреблять{}, // употреблять на корм скоту rus_verbs:пристроить{}, // пристроить на работу rus_verbs:заворчать{}, // заворчать на вошедшего rus_verbs:завязаться{}, // завязаться на поставщиков rus_verbs:сажать{}, // сажать на стул rus_verbs:напрашиваться{}, // напрашиваться на жесткие ответные меры rus_verbs:заменять{}, // заменять на исправную rus_verbs:нацепить{}, // нацепить на голову rus_verbs:сыпать{}, // сыпать на землю rus_verbs:закрываться{}, // закрываться на ремонт rus_verbs:распространиться{}, // распространиться на всю популяцию rus_verbs:поменять{}, // поменять на велосипед rus_verbs:пересесть{}, // пересесть на велосипеды rus_verbs:подоспеть{}, // подоспеть на разбор rus_verbs:шипеть{}, // шипеть на собак rus_verbs:поделить{}, // поделить на части rus_verbs:подлететь{}, // подлететь на расстояние выстрела rus_verbs:нажимать{}, // нажимать на все кнопки rus_verbs:распасться{}, // распасться на части rus_verbs:приволочь{}, // приволочь на диван rus_verbs:пожить{}, // пожить на один доллар rus_verbs:устремляться{}, // устремляться на свободу rus_verbs:смахивать{}, // смахивать на пол rus_verbs:забежать{}, // забежать на обед rus_verbs:увеличиться{}, // увеличиться на существенную величину rus_verbs:прокрасться{}, // прокрасться на склад rus_verbs:пущать{}, // пущать на постой rus_verbs:отклонить{}, // отклонить на несколько градусов rus_verbs:насмотреться{}, // насмотреться на безобразия rus_verbs:настроить{}, // настроить на короткие волны rus_verbs:уменьшиться{}, // уменьшиться на пару сантиметров rus_verbs:поменяться{}, // поменяться на другую книжку rus_verbs:расколоться{}, // расколоться на части rus_verbs:разлиться{}, // разлиться на землю rus_verbs:срываться{}, // срываться на жену rus_verbs:осудить{}, // осудить на пожизненное заключение rus_verbs:передвинуть{}, // передвинуть на первое место rus_verbs:допускаться{}, // допускаться на полигон rus_verbs:задвинуть{}, // задвинуть на полку rus_verbs:повлиять{}, // повлиять на оценку rus_verbs:отбавлять{}, // отбавлять на осмотр rus_verbs:сбрасывать{}, // сбрасывать на землю rus_verbs:накинуться{}, // накинуться на случайных прохожих rus_verbs:пролить{}, // пролить на кожу руки rus_verbs:затащить{}, // затащить на сеновал rus_verbs:перебежать{}, // перебежать на сторону противника rus_verbs:наливать{}, // наливать на скатерть rus_verbs:пролезть{}, // пролезть на сцену rus_verbs:откладывать{}, // откладывать на черный день rus_verbs:распадаться{}, // распадаться на небольшие фрагменты rus_verbs:перечислить{}, // перечислить на счет rus_verbs:закачаться{}, // закачаться на верхний уровень rus_verbs:накрениться{}, // накрениться на правый борт rus_verbs:подвинуться{}, // подвинуться на один уровень rus_verbs:разнести{}, // разнести на мелкие кусочки rus_verbs:зажить{}, // зажить на широкую ногу rus_verbs:оглохнуть{}, // оглохнуть на правое ухо rus_verbs:посетовать{}, // посетовать на бюрократизм rus_verbs:уводить{}, // уводить на осмотр rus_verbs:ускакать{}, // ускакать на забег rus_verbs:посветить{}, // посветить на стену rus_verbs:разрываться{}, // разрываться на части rus_verbs:побросать{}, // побросать на землю rus_verbs:карабкаться{}, // карабкаться на скалу rus_verbs:нахлынуть{}, // нахлынуть на кого-то rus_verbs:разлетаться{}, // разлетаться на мелкие осколочки rus_verbs:среагировать{}, // среагировать на сигнал rus_verbs:претендовать{}, // претендовать на приз rus_verbs:дунуть{}, // дунуть на одуванчик rus_verbs:переводиться{}, // переводиться на другую работу rus_verbs:перевезти{}, // перевезти на другую площадку rus_verbs:топать{}, // топать на урок rus_verbs:относить{}, // относить на склад rus_verbs:сбивать{}, // сбивать на землю rus_verbs:укладывать{}, // укладывать на спину rus_verbs:укатить{}, // укатить на отдых rus_verbs:убирать{}, // убирать на полку rus_verbs:опасть{}, // опасть на землю rus_verbs:ронять{}, // ронять на снег rus_verbs:пялиться{}, // пялиться на тело rus_verbs:глазеть{}, // глазеть на тело rus_verbs:снижаться{}, // снижаться на безопасную высоту rus_verbs:запрыгнуть{}, // запрыгнуть на платформу rus_verbs:разбиваться{}, // разбиваться на главы rus_verbs:сгодиться{}, // сгодиться на фарш rus_verbs:перескочить{}, // перескочить на другую страницу rus_verbs:нацелиться{}, // нацелиться на главную добычу rus_verbs:заезжать{}, // заезжать на бордюр rus_verbs:забираться{}, // забираться на крышу rus_verbs:проорать{}, // проорать на всё село rus_verbs:сбежаться{}, // сбежаться на шум rus_verbs:сменять{}, // сменять на хлеб rus_verbs:мотать{}, // мотать на ус rus_verbs:раскалываться{}, // раскалываться на две половинки rus_verbs:коситься{}, // коситься на режиссёра rus_verbs:плевать{}, // плевать на законы rus_verbs:ссылаться{}, // ссылаться на авторитетное мнение rus_verbs:наставить{}, // наставить на путь истинный rus_verbs:завывать{}, // завывать на Луну rus_verbs:опаздывать{}, // опаздывать на совещание rus_verbs:залюбоваться{}, // залюбоваться на пейзаж rus_verbs:повергнуть{}, // повергнуть на землю rus_verbs:надвинуть{}, // надвинуть на лоб rus_verbs:стекаться{}, // стекаться на площадь rus_verbs:обозлиться{}, // обозлиться на тренера rus_verbs:оттянуть{}, // оттянуть на себя rus_verbs:истратить{}, // истратить на дешевых шлюх rus_verbs:вышвырнуть{}, // вышвырнуть на улицу rus_verbs:затолкать{}, // затолкать на верхнюю полку rus_verbs:заскочить{}, // заскочить на огонек rus_verbs:проситься{}, // проситься на улицу rus_verbs:натыкаться{}, // натыкаться на борщевик rus_verbs:обрушиваться{}, // обрушиваться на митингующих rus_verbs:переписать{}, // переписать на чистовик rus_verbs:переноситься{}, // переноситься на другое устройство rus_verbs:напроситься{}, // напроситься на обидный ответ rus_verbs:натягивать{}, // натягивать на ноги rus_verbs:кидаться{}, // кидаться на прохожих rus_verbs:откликаться{}, // откликаться на призыв rus_verbs:поспевать{}, // поспевать на балет rus_verbs:обратиться{}, // обратиться на кафедру rus_verbs:полюбоваться{}, // полюбоваться на бюст rus_verbs:таращиться{}, // таращиться на мустангов rus_verbs:напороться{}, // напороться на колючки rus_verbs:раздать{}, // раздать на руки rus_verbs:дивиться{}, // дивиться на танцовщиц rus_verbs:назначать{}, // назначать на ответственнейший пост rus_verbs:кидать{}, // кидать на балкон rus_verbs:нахлобучить{}, // нахлобучить на башку rus_verbs:увлекать{}, // увлекать на луг rus_verbs:ругнуться{}, // ругнуться на животину rus_verbs:переселиться{}, // переселиться на хутор rus_verbs:разрывать{}, // разрывать на части rus_verbs:утащить{}, // утащить на дерево rus_verbs:наставлять{}, // наставлять на путь rus_verbs:соблазнить{}, // соблазнить на обмен rus_verbs:накладывать{}, // накладывать на рану rus_verbs:набрести{}, // набрести на грибную поляну rus_verbs:наведываться{}, // наведываться на прежнюю работу rus_verbs:погулять{}, // погулять на чужие деньги rus_verbs:уклоняться{}, // уклоняться на два градуса влево rus_verbs:слезать{}, // слезать на землю rus_verbs:клевать{}, // клевать на мотыля // rus_verbs:назначаться{}, // назначаться на пост rus_verbs:напялить{}, // напялить на голову rus_verbs:натянуться{}, // натянуться на рамку rus_verbs:разгневаться{}, // разгневаться на придворных rus_verbs:эмигрировать{}, // эмигрировать на Кипр rus_verbs:накатить{}, // накатить на основу rus_verbs:пригнать{}, // пригнать на пастбище rus_verbs:обречь{}, // обречь на мучения rus_verbs:сокращаться{}, // сокращаться на четверть rus_verbs:оттеснить{}, // оттеснить на пристань rus_verbs:подбить{}, // подбить на аферу rus_verbs:заманить{}, // заманить на дерево инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на кустик // деепричастие:пописав{ aux stress="поп^исать" }, rus_verbs:посходить{}, // посходить на перрон rus_verbs:налечь{}, // налечь на мясцо rus_verbs:отбирать{}, // отбирать на флот rus_verbs:нашептывать{}, // нашептывать на ухо rus_verbs:откладываться{}, // откладываться на будущее rus_verbs:залаять{}, // залаять на грабителя rus_verbs:настроиться{}, // настроиться на прием rus_verbs:разбивать{}, // разбивать на куски rus_verbs:пролиться{}, // пролиться на почву rus_verbs:сетовать{}, // сетовать на объективные трудности rus_verbs:подвезти{}, // подвезти на митинг rus_verbs:припереться{}, // припереться на праздник rus_verbs:подталкивать{}, // подталкивать на прыжок rus_verbs:прорываться{}, // прорываться на сцену rus_verbs:снижать{}, // снижать на несколько процентов rus_verbs:нацелить{}, // нацелить на танк rus_verbs:расколоть{}, // расколоть на два куска rus_verbs:увозить{}, // увозить на обкатку rus_verbs:оседать{}, // оседать на дно rus_verbs:съедать{}, // съедать на ужин rus_verbs:навлечь{}, // навлечь на себя rus_verbs:равняться{}, // равняться на лучших rus_verbs:сориентироваться{}, // сориентироваться на местности rus_verbs:снизить{}, // снизить на несколько процентов rus_verbs:перенестись{}, // перенестись на много лет назад rus_verbs:завезти{}, // завезти на склад rus_verbs:проложить{}, // проложить на гору rus_verbs:понадеяться{}, // понадеяться на удачу rus_verbs:заступить{}, // заступить на вахту rus_verbs:засеменить{}, // засеменить на выход rus_verbs:запирать{}, // запирать на ключ rus_verbs:скатываться{}, // скатываться на землю rus_verbs:дробить{}, // дробить на части rus_verbs:разваливаться{}, // разваливаться на кусочки rus_verbs:завозиться{}, // завозиться на склад rus_verbs:нанимать{}, // нанимать на дневную работу rus_verbs:поспеть{}, // поспеть на концерт rus_verbs:променять{}, // променять на сытость rus_verbs:переправить{}, // переправить на север rus_verbs:налетать{}, // налетать на силовое поле rus_verbs:затворить{}, // затворить на замок rus_verbs:подогнать{}, // подогнать на пристань rus_verbs:наехать{}, // наехать на камень rus_verbs:распевать{}, // распевать на разные голоса rus_verbs:разносить{}, // разносить на клочки rus_verbs:преувеличивать{}, // преувеличивать на много килограммов rus_verbs:хромать{}, // хромать на одну ногу rus_verbs:телеграфировать{}, // телеграфировать на базу rus_verbs:порезать{}, // порезать на лоскуты rus_verbs:порваться{}, // порваться на части rus_verbs:загонять{}, // загонять на дерево rus_verbs:отбывать{}, // отбывать на место службы rus_verbs:усаживаться{}, // усаживаться на трон rus_verbs:накопить{}, // накопить на квартиру rus_verbs:зыркнуть{}, // зыркнуть на визитера rus_verbs:копить{}, // копить на машину rus_verbs:помещать{}, // помещать на верхнюю грань rus_verbs:сползать{}, // сползать на снег rus_verbs:попроситься{}, // попроситься на улицу rus_verbs:перетащить{}, // перетащить на чердак rus_verbs:растащить{}, // растащить на сувениры rus_verbs:ниспадать{}, // ниспадать на землю rus_verbs:сфотографировать{}, // сфотографировать на память rus_verbs:нагонять{}, // нагонять на конкурентов страх rus_verbs:покушаться{}, // покушаться на понтифика rus_verbs:покуситься{}, rus_verbs:наняться{}, // наняться на службу rus_verbs:просачиваться{}, // просачиваться на поверхность rus_verbs:пускаться{}, // пускаться на ветер rus_verbs:отваживаться{}, // отваживаться на прыжок rus_verbs:досадовать{}, // досадовать на объективные трудности rus_verbs:унестись{}, // унестись на небо rus_verbs:ухудшаться{}, // ухудшаться на несколько процентов rus_verbs:насадить{}, // насадить на копьё rus_verbs:нагрянуть{}, // нагрянуть на праздник rus_verbs:зашвырнуть{}, // зашвырнуть на полку rus_verbs:грешить{}, // грешить на постояльцев rus_verbs:просочиться{}, // просочиться на поверхность rus_verbs:надоумить{}, // надоумить на глупость rus_verbs:намотать{}, // намотать на шпиндель rus_verbs:замкнуть{}, // замкнуть на корпус rus_verbs:цыкнуть{}, // цыкнуть на детей rus_verbs:переворачиваться{}, // переворачиваться на спину rus_verbs:соваться{}, // соваться на площать rus_verbs:отлучиться{}, // отлучиться на обед rus_verbs:пенять{}, // пенять на себя rus_verbs:нарезать{}, // нарезать на ломтики rus_verbs:поставлять{}, // поставлять на Кипр rus_verbs:залезать{}, // залезать на балкон rus_verbs:отлучаться{}, // отлучаться на обед rus_verbs:сбиваться{}, // сбиваться на шаг rus_verbs:таращить{}, // таращить глаза на вошедшего rus_verbs:прошмыгнуть{}, // прошмыгнуть на кухню rus_verbs:опережать{}, // опережать на пару сантиметров rus_verbs:переставить{}, // переставить на стол rus_verbs:раздирать{}, // раздирать на части rus_verbs:затвориться{}, // затвориться на засовы rus_verbs:материться{}, // материться на кого-то rus_verbs:наскочить{}, // наскочить на риф rus_verbs:набираться{}, // набираться на борт rus_verbs:покрикивать{}, // покрикивать на помощников rus_verbs:заменяться{}, // заменяться на более новый rus_verbs:подсадить{}, // подсадить на верхнюю полку rus_verbs:проковылять{}, // проковылять на кухню rus_verbs:прикатить{}, // прикатить на старт rus_verbs:залететь{}, // залететь на чужую территорию rus_verbs:загрузить{}, // загрузить на конвейер rus_verbs:уплывать{}, // уплывать на материк rus_verbs:опозорить{}, // опозорить на всю деревню rus_verbs:провоцировать{}, // провоцировать на ответную агрессию rus_verbs:забивать{}, // забивать на учебу rus_verbs:набегать{}, // набегать на прибрежные деревни rus_verbs:запираться{}, // запираться на ключ rus_verbs:фотографировать{}, // фотографировать на мыльницу rus_verbs:подымать{}, // подымать на недосягаемую высоту rus_verbs:съезжаться{}, // съезжаться на симпозиум rus_verbs:отвлекаться{}, // отвлекаться на игру rus_verbs:проливать{}, // проливать на брюки rus_verbs:спикировать{}, // спикировать на зазевавшегося зайца rus_verbs:уползти{}, // уползти на вершину холма rus_verbs:переместить{}, // переместить на вторую палубу rus_verbs:превысить{}, // превысить на несколько метров rus_verbs:передвинуться{}, // передвинуться на соседнюю клетку rus_verbs:спровоцировать{}, // спровоцировать на бросок rus_verbs:сместиться{}, // сместиться на соседнюю клетку rus_verbs:заготовить{}, // заготовить на зиму rus_verbs:плеваться{}, // плеваться на пол rus_verbs:переселить{}, // переселить на север rus_verbs:напирать{}, // напирать на дверь rus_verbs:переезжать{}, // переезжать на другой этаж rus_verbs:приподнимать{}, // приподнимать на несколько сантиметров rus_verbs:трогаться{}, // трогаться на красный свет rus_verbs:надвинуться{}, // надвинуться на глаза rus_verbs:засмотреться{}, // засмотреться на купальники rus_verbs:убыть{}, // убыть на фронт rus_verbs:передвигать{}, // передвигать на второй уровень rus_verbs:отвозить{}, // отвозить на свалку rus_verbs:обрекать{}, // обрекать на гибель rus_verbs:записываться{}, // записываться на танцы rus_verbs:настраивать{}, // настраивать на другой диапазон rus_verbs:переписывать{}, // переписывать на диск rus_verbs:израсходовать{}, // израсходовать на гонки rus_verbs:обменять{}, // обменять на перспективного игрока rus_verbs:трубить{}, // трубить на всю округу rus_verbs:набрасываться{}, // набрасываться на жертву rus_verbs:чихать{}, // чихать на правила rus_verbs:наваливаться{}, // наваливаться на рычаг rus_verbs:сподобиться{}, // сподобиться на повторный анализ rus_verbs:намазать{}, // намазать на хлеб rus_verbs:прореагировать{}, // прореагировать на вызов rus_verbs:зачислить{}, // зачислить на факультет rus_verbs:наведаться{}, // наведаться на склад rus_verbs:откидываться{}, // откидываться на спинку кресла rus_verbs:захромать{}, // захромать на левую ногу rus_verbs:перекочевать{}, // перекочевать на другой берег rus_verbs:накатываться{}, // накатываться на песчаный берег rus_verbs:приостановить{}, // приостановить на некоторое время rus_verbs:запрятать{}, // запрятать на верхнюю полочку rus_verbs:прихрамывать{}, // прихрамывать на правую ногу rus_verbs:упорхнуть{}, // упорхнуть на свободу rus_verbs:расстегивать{}, // расстегивать на пальто rus_verbs:напуститься{}, // напуститься на бродягу rus_verbs:накатывать{}, // накатывать на оригинал rus_verbs:наезжать{}, // наезжать на простофилю rus_verbs:тявкнуть{}, // тявкнуть на подошедшего человека rus_verbs:отрядить{}, // отрядить на починку rus_verbs:положиться{}, // положиться на главаря rus_verbs:опрокидывать{}, // опрокидывать на голову rus_verbs:поторапливаться{}, // поторапливаться на рейс rus_verbs:налагать{}, // налагать на заемщика rus_verbs:скопировать{}, // скопировать на диск rus_verbs:опадать{}, // опадать на землю rus_verbs:купиться{}, // купиться на посулы rus_verbs:гневаться{}, // гневаться на слуг rus_verbs:слететься{}, // слететься на раздачу rus_verbs:убавить{}, // убавить на два уровня rus_verbs:спихнуть{}, // спихнуть на соседа rus_verbs:накричать{}, // накричать на ребенка rus_verbs:приберечь{}, // приберечь на ужин rus_verbs:приклеить{}, // приклеить на ветровое стекло rus_verbs:ополчиться{}, // ополчиться на посредников rus_verbs:тратиться{}, // тратиться на сувениры rus_verbs:слетаться{}, // слетаться на свет rus_verbs:доставляться{}, // доставляться на базу rus_verbs:поплевать{}, // поплевать на руки rus_verbs:огрызаться{}, // огрызаться на замечание rus_verbs:попереться{}, // попереться на рынок rus_verbs:растягиваться{}, // растягиваться на полу rus_verbs:повергать{}, // повергать на землю rus_verbs:ловиться{}, // ловиться на мотыля rus_verbs:наседать{}, // наседать на обороняющихся rus_verbs:развалить{}, // развалить на кирпичи rus_verbs:разломить{}, // разломить на несколько частей rus_verbs:примерить{}, // примерить на себя rus_verbs:лепиться{}, // лепиться на стену rus_verbs:скопить{}, // скопить на старость rus_verbs:затратить{}, // затратить на ликвидацию последствий rus_verbs:притащиться{}, // притащиться на гулянку rus_verbs:осерчать{}, // осерчать на прислугу rus_verbs:натравить{}, // натравить на медведя rus_verbs:ссыпать{}, // ссыпать на землю rus_verbs:подвозить{}, // подвозить на пристань rus_verbs:мобилизовать{}, // мобилизовать на сборы rus_verbs:смотаться{}, // смотаться на работу rus_verbs:заглядеться{}, // заглядеться на девчонок rus_verbs:таскаться{}, // таскаться на работу rus_verbs:разгружать{}, // разгружать на транспортер rus_verbs:потреблять{}, // потреблять на кондиционирование инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять на базу деепричастие:сгоняв{}, rus_verbs:посылаться{}, // посылаться на разведку rus_verbs:окрыситься{}, // окрыситься на кого-то rus_verbs:отлить{}, // отлить на сковороду rus_verbs:шикнуть{}, // шикнуть на детишек rus_verbs:уповать{}, // уповать на бескорысную помощь rus_verbs:класться{}, // класться на стол rus_verbs:поковылять{}, // поковылять на выход rus_verbs:навевать{}, // навевать на собравшихся скуку rus_verbs:накладываться{}, // накладываться на грунтовку rus_verbs:наноситься{}, // наноситься на чистую кожу // rus_verbs:запланировать{}, // запланировать на среду rus_verbs:кувыркнуться{}, // кувыркнуться на землю rus_verbs:гавкнуть{}, // гавкнуть на хозяина rus_verbs:перестроиться{}, // перестроиться на новый лад rus_verbs:расходоваться{}, // расходоваться на образование rus_verbs:дуться{}, // дуться на бабушку rus_verbs:перетаскивать{}, // перетаскивать на рабочий стол rus_verbs:издаться{}, // издаться на деньги спонсоров rus_verbs:смещаться{}, // смещаться на несколько миллиметров rus_verbs:зазывать{}, // зазывать на новогоднюю распродажу rus_verbs:пикировать{}, // пикировать на окопы rus_verbs:чертыхаться{}, // чертыхаться на мешающихся детей rus_verbs:зудить{}, // зудить на ухо rus_verbs:подразделяться{}, // подразделяться на группы rus_verbs:изливаться{}, // изливаться на землю rus_verbs:помочиться{}, // помочиться на траву rus_verbs:примерять{}, // примерять на себя rus_verbs:разрядиться{}, // разрядиться на землю rus_verbs:мотнуться{}, // мотнуться на крышу rus_verbs:налегать{}, // налегать на весла rus_verbs:зацокать{}, // зацокать на куриц rus_verbs:наниматься{}, // наниматься на корабль rus_verbs:сплевывать{}, // сплевывать на землю rus_verbs:настучать{}, // настучать на саботажника rus_verbs:приземляться{}, // приземляться на брюхо rus_verbs:наталкиваться{}, // наталкиваться на объективные трудности rus_verbs:посигналить{}, // посигналить нарушителю, выехавшему на встречную полосу rus_verbs:серчать{}, // серчать на нерасторопную помощницу rus_verbs:сваливать{}, // сваливать на подоконник rus_verbs:засобираться{}, // засобираться на работу rus_verbs:распилить{}, // распилить на одинаковые бруски //rus_verbs:умножать{}, // умножать на константу rus_verbs:копировать{}, // копировать на диск rus_verbs:накрутить{}, // накрутить на руку rus_verbs:навалить{}, // навалить на телегу rus_verbs:натолкнуть{}, // натолкнуть на свежую мысль rus_verbs:шлепаться{}, // шлепаться на бетон rus_verbs:ухлопать{}, // ухлопать на скупку произведений искусства rus_verbs:замахиваться{}, // замахиваться на авторитетнейшее мнение rus_verbs:посягнуть{}, // посягнуть на святое rus_verbs:разменять{}, // разменять на мелочь rus_verbs:откатываться{}, // откатываться на заранее подготовленные позиции rus_verbs:усаживать{}, // усаживать на скамейку rus_verbs:натаскать{}, // натаскать на поиск наркотиков rus_verbs:зашикать{}, // зашикать на кошку rus_verbs:разломать{}, // разломать на равные части rus_verbs:приглашаться{}, // приглашаться на сцену rus_verbs:присягать{}, // присягать на верность rus_verbs:запрограммировать{}, // запрограммировать на постоянную уборку rus_verbs:расщедриться{}, // расщедриться на новый компьютер rus_verbs:насесть{}, // насесть на двоечников rus_verbs:созывать{}, // созывать на собрание rus_verbs:позариться{}, // позариться на чужое добро rus_verbs:перекидываться{}, // перекидываться на соседние здания rus_verbs:наползать{}, // наползать на неповрежденную ткань rus_verbs:изрубить{}, // изрубить на мелкие кусочки rus_verbs:наворачиваться{}, // наворачиваться на глаза rus_verbs:раскричаться{}, // раскричаться на всю округу rus_verbs:переползти{}, // переползти на светлую сторону rus_verbs:уполномочить{}, // уполномочить на разведовательную операцию rus_verbs:мочиться{}, // мочиться на трупы убитых врагов rus_verbs:радировать{}, // радировать на базу rus_verbs:промотать{}, // промотать на начало rus_verbs:заснять{}, // заснять на видео rus_verbs:подбивать{}, // подбивать на матч-реванш rus_verbs:наплевать{}, // наплевать на справедливость rus_verbs:подвывать{}, // подвывать на луну rus_verbs:расплескать{}, // расплескать на пол rus_verbs:польститься{}, // польститься на бесплатный сыр rus_verbs:помчать{}, // помчать на работу rus_verbs:съезжать{}, // съезжать на обочину rus_verbs:нашептать{}, // нашептать кому-то на ухо rus_verbs:наклеить{}, // наклеить на доску объявлений rus_verbs:завозить{}, // завозить на склад rus_verbs:заявляться{}, // заявляться на любимую работу rus_verbs:наглядеться{}, // наглядеться на воробьев rus_verbs:хлопнуться{}, // хлопнуться на живот rus_verbs:забредать{}, // забредать на поляну rus_verbs:посягать{}, // посягать на исконные права собственности rus_verbs:сдвигать{}, // сдвигать на одну позицию rus_verbs:спрыгивать{}, // спрыгивать на землю rus_verbs:сдвигаться{}, // сдвигаться на две позиции rus_verbs:разделать{}, // разделать на орехи rus_verbs:разлагать{}, // разлагать на элементарные элементы rus_verbs:обрушивать{}, // обрушивать на головы врагов rus_verbs:натечь{}, // натечь на пол rus_verbs:политься{}, // вода польется на землю rus_verbs:успеть{}, // Они успеют на поезд. инфинитив:мигрировать{ вид:несоверш }, глагол:мигрировать{ вид:несоверш }, деепричастие:мигрируя{}, инфинитив:мигрировать{ вид:соверш }, глагол:мигрировать{ вид:соверш }, деепричастие:мигрировав{}, rus_verbs:двинуться{}, // Мы скоро двинемся на дачу. rus_verbs:подойти{}, // Он не подойдёт на должность секретаря. rus_verbs:потянуть{}, // Он не потянет на директора. rus_verbs:тянуть{}, // Он не тянет на директора. rus_verbs:перескакивать{}, // перескакивать с одного примера на другой rus_verbs:жаловаться{}, // Он жалуется на нездоровье. rus_verbs:издать{}, // издать на деньги спонсоров rus_verbs:показаться{}, // показаться на глаза rus_verbs:высаживать{}, // высаживать на необитаемый остров rus_verbs:вознестись{}, // вознестись на самую вершину славы rus_verbs:залить{}, // залить на youtube rus_verbs:закачать{}, // закачать на youtube rus_verbs:сыграть{}, // сыграть на деньги rus_verbs:экстраполировать{}, // Формулу можно экстраполировать на случай нескольких переменных инфинитив:экстраполироваться{ вид:несоверш}, // Ситуация легко экстраполируется на случай нескольких переменных глагол:экстраполироваться{ вид:несоверш}, инфинитив:экстраполироваться{ вид:соверш}, глагол:экстраполироваться{ вид:соверш}, деепричастие:экстраполируясь{}, инфинитив:акцентировать{вид:соверш}, // оратор акцентировал внимание слушателей на новый аспект проблемы глагол:акцентировать{вид:соверш}, инфинитив:акцентировать{вид:несоверш}, глагол:акцентировать{вид:несоверш}, прилагательное:акцентировавший{вид:несоверш}, //прилагательное:акцентировавший{вид:соверш}, прилагательное:акцентирующий{}, деепричастие:акцентировав{}, деепричастие:акцентируя{}, rus_verbs:бабахаться{}, // он бабахался на пол rus_verbs:бабахнуться{}, // мальчил бабахнулся на асфальт rus_verbs:батрачить{}, // Крестьяне батрачили на хозяина rus_verbs:бахаться{}, // Наездники бахались на землю rus_verbs:бахнуться{}, // Наездник опять бахнулся на землю rus_verbs:благословить{}, // батюшка благословил отрока на подвиг rus_verbs:благословлять{}, // батюшка благословляет отрока на подвиг rus_verbs:блевануть{}, // Он блеванул на землю rus_verbs:блевать{}, // Он блюет на землю rus_verbs:бухнуться{}, // Наездник бухнулся на землю rus_verbs:валить{}, // Ветер валил деревья на землю rus_verbs:спилить{}, // Спиленное дерево валится на землю rus_verbs:ввезти{}, // Предприятие ввезло товар на таможню rus_verbs:вдохновить{}, // Фильм вдохновил мальчика на поход в лес rus_verbs:вдохновиться{}, // Мальчик вдохновился на поход rus_verbs:вдохновлять{}, // Фильм вдохновляет на поход в лес rus_verbs:вестись{}, // Не ведись на эти уловки! rus_verbs:вешать{}, // Гости вешают одежду на вешалку rus_verbs:вешаться{}, // Одежда вешается на вешалки rus_verbs:вещать{}, // радиостанция вещает на всю страну rus_verbs:взбираться{}, // Туристы взбираются на заросший лесом холм rus_verbs:взбредать{}, // Что иногда взбредает на ум rus_verbs:взбрести{}, // Что-то взбрело на ум rus_verbs:взвалить{}, // Мама взвалила на свои плечи всё домашнее хозяйство rus_verbs:взваливаться{}, // Все домашнее хозяйство взваливается на мамины плечи rus_verbs:взваливать{}, // Не надо взваливать всё на мои плечи rus_verbs:взглянуть{}, // Кошка взглянула на мышку rus_verbs:взгромождать{}, // Мальчик взгромождает стул на стол rus_verbs:взгромождаться{}, // Мальчик взгромождается на стол rus_verbs:взгромоздить{}, // Мальчик взгромоздил стул на стол rus_verbs:взгромоздиться{}, // Мальчик взгромоздился на стул rus_verbs:взирать{}, // Очевидцы взирали на непонятный объект rus_verbs:взлетать{}, // Фабрика фейерверков взлетает на воздух rus_verbs:взлететь{}, // Фабрика фейерверков взлетела на воздух rus_verbs:взобраться{}, // Туристы взобрались на гору rus_verbs:взойти{}, // Туристы взошли на гору rus_verbs:взъесться{}, // Отец взъелся на непутевого сына rus_verbs:взъяриться{}, // Отец взъярился на непутевого сына rus_verbs:вкатить{}, // рабочие вкатили бочку на пандус rus_verbs:вкатывать{}, // рабочик вкатывают бочку на пандус rus_verbs:влиять{}, // Это решение влияет на всех игроков рынка rus_verbs:водворить{}, // водворить нарушителя на место rus_verbs:водвориться{}, // водвориться на свое место rus_verbs:водворять{}, // водворять вещь на свое место rus_verbs:водворяться{}, // водворяться на свое место rus_verbs:водружать{}, // водружать флаг на флагшток rus_verbs:водружаться{}, // Флаг водружается на флагшток rus_verbs:водрузить{}, // водрузить флаг на флагшток rus_verbs:водрузиться{}, // Флаг водрузился на вершину горы rus_verbs:воздействовать{}, // Излучение воздействует на кожу rus_verbs:воззреть{}, // воззреть на поле боя rus_verbs:воззриться{}, // воззриться на поле боя rus_verbs:возить{}, // возить туристов на гору rus_verbs:возлагать{}, // Многочисленные посетители возлагают цветы на могилу rus_verbs:возлагаться{}, // Ответственность возлагается на начальство rus_verbs:возлечь{}, // возлечь на лежанку rus_verbs:возложить{}, // возложить цветы на могилу поэта rus_verbs:вознести{}, // вознести кого-то на вершину славы rus_verbs:возноситься{}, // возносится на вершину успеха rus_verbs:возносить{}, // возносить счастливчика на вершину успеха rus_verbs:подниматься{}, // Мы поднимаемся на восьмой этаж rus_verbs:подняться{}, // Мы поднялись на восьмой этаж rus_verbs:вонять{}, // Кусок сыра воняет на всю округу rus_verbs:воодушевлять{}, // Идеалы воодушевляют на подвиги rus_verbs:воодушевляться{}, // Люди воодушевляются на подвиги rus_verbs:ворчать{}, // Старый пес ворчит на прохожих rus_verbs:воспринимать{}, // воспринимать сообщение на слух rus_verbs:восприниматься{}, // сообщение плохо воспринимается на слух rus_verbs:воспринять{}, // воспринять сообщение на слух rus_verbs:восприняться{}, // восприняться на слух rus_verbs:воссесть{}, // Коля воссел на трон rus_verbs:вправить{}, // вправить мозг на место rus_verbs:вправлять{}, // вправлять мозги на место rus_verbs:временить{}, // временить с выходом на пенсию rus_verbs:врубать{}, // врубать на полную мощность rus_verbs:врубить{}, // врубить на полную мощность rus_verbs:врубиться{}, // врубиться на полную мощность rus_verbs:врываться{}, // врываться на собрание rus_verbs:вскарабкаться{}, // вскарабкаться на утёс rus_verbs:вскарабкиваться{}, // вскарабкиваться на утёс rus_verbs:вскочить{}, // вскочить на ноги rus_verbs:всплывать{}, // всплывать на поверхность воды rus_verbs:всплыть{}, // всплыть на поверхность воды rus_verbs:вспрыгивать{}, // вспрыгивать на платформу rus_verbs:вспрыгнуть{}, // вспрыгнуть на платформу rus_verbs:встать{}, // встать на защиту чести и достоинства rus_verbs:вторгаться{}, // вторгаться на чужую территорию rus_verbs:вторгнуться{}, // вторгнуться на чужую территорию rus_verbs:въезжать{}, // въезжать на пандус rus_verbs:наябедничать{}, // наябедничать на соседа по парте rus_verbs:выблевать{}, // выблевать завтрак на пол rus_verbs:выблеваться{}, // выблеваться на пол rus_verbs:выблевывать{}, // выблевывать завтрак на пол rus_verbs:выблевываться{}, // выблевываться на пол rus_verbs:вывезти{}, // вывезти мусор на свалку rus_verbs:вывесить{}, // вывесить белье на просушку rus_verbs:вывести{}, // вывести собаку на прогулку rus_verbs:вывешивать{}, // вывешивать белье на веревку rus_verbs:вывозить{}, // вывозить детей на природу rus_verbs:вызывать{}, // Начальник вызывает на ковер rus_verbs:выйти{}, // выйти на свободу rus_verbs:выкладывать{}, // выкладывать на всеобщее обозрение rus_verbs:выкладываться{}, // выкладываться на всеобщее обозрение rus_verbs:выливать{}, // выливать на землю rus_verbs:выливаться{}, // выливаться на землю rus_verbs:вылить{}, // вылить жидкость на землю rus_verbs:вылиться{}, // Топливо вылилось на землю rus_verbs:выложить{}, // выложить на берег rus_verbs:выменивать{}, // выменивать золото на хлеб rus_verbs:вымениваться{}, // Золото выменивается на хлеб rus_verbs:выменять{}, // выменять золото на хлеб rus_verbs:выпадать{}, // снег выпадает на землю rus_verbs:выплевывать{}, // выплевывать на землю rus_verbs:выплевываться{}, // выплевываться на землю rus_verbs:выплескать{}, // выплескать на землю rus_verbs:выплескаться{}, // выплескаться на землю rus_verbs:выплескивать{}, // выплескивать на землю rus_verbs:выплескиваться{}, // выплескиваться на землю rus_verbs:выплывать{}, // выплывать на поверхность rus_verbs:выплыть{}, // выплыть на поверхность rus_verbs:выплюнуть{}, // выплюнуть на пол rus_verbs:выползать{}, // выползать на свежий воздух rus_verbs:выпроситься{}, // выпроситься на улицу rus_verbs:выпрыгивать{}, // выпрыгивать на свободу rus_verbs:выпрыгнуть{}, // выпрыгнуть на перрон rus_verbs:выпускать{}, // выпускать на свободу rus_verbs:выпустить{}, // выпустить на свободу rus_verbs:выпучивать{}, // выпучивать на кого-то глаза rus_verbs:выпучиваться{}, // глаза выпучиваются на кого-то rus_verbs:выпучить{}, // выпучить глаза на кого-то rus_verbs:выпучиться{}, // выпучиться на кого-то rus_verbs:выронить{}, // выронить на землю rus_verbs:высадить{}, // высадить на берег rus_verbs:высадиться{}, // высадиться на берег rus_verbs:высаживаться{}, // высаживаться на остров rus_verbs:выскальзывать{}, // выскальзывать на землю rus_verbs:выскочить{}, // выскочить на сцену rus_verbs:высморкаться{}, // высморкаться на землю rus_verbs:высморкнуться{}, // высморкнуться на землю rus_verbs:выставить{}, // выставить на всеобщее обозрение rus_verbs:выставиться{}, // выставиться на всеобщее обозрение rus_verbs:выставлять{}, // выставлять на всеобщее обозрение rus_verbs:выставляться{}, // выставляться на всеобщее обозрение инфинитив:высыпать{вид:соверш}, // высыпать на землю инфинитив:высыпать{вид:несоверш}, глагол:высыпать{вид:соверш}, глагол:высыпать{вид:несоверш}, деепричастие:высыпав{}, деепричастие:высыпая{}, прилагательное:высыпавший{вид:соверш}, //++прилагательное:высыпавший{вид:несоверш}, прилагательное:высыпающий{вид:несоверш}, rus_verbs:высыпаться{}, // высыпаться на землю rus_verbs:вытаращивать{}, // вытаращивать глаза на медведя rus_verbs:вытаращиваться{}, // вытаращиваться на медведя rus_verbs:вытаращить{}, // вытаращить глаза на медведя rus_verbs:вытаращиться{}, // вытаращиться на медведя rus_verbs:вытекать{}, // вытекать на землю rus_verbs:вытечь{}, // вытечь на землю rus_verbs:выучиваться{}, // выучиваться на кого-то rus_verbs:выучиться{}, // выучиться на кого-то rus_verbs:посмотреть{}, // посмотреть на экран rus_verbs:нашить{}, // нашить что-то на одежду rus_verbs:придти{}, // придти на помощь кому-то инфинитив:прийти{}, // прийти на помощь кому-то глагол:прийти{}, деепричастие:придя{}, // Придя на вокзал, он поспешно взял билеты. rus_verbs:поднять{}, // поднять на вершину rus_verbs:согласиться{}, // согласиться на ничью rus_verbs:послать{}, // послать на фронт rus_verbs:слать{}, // слать на фронт rus_verbs:надеяться{}, // надеяться на лучшее rus_verbs:крикнуть{}, // крикнуть на шалунов rus_verbs:пройти{}, // пройти на пляж rus_verbs:прислать{}, // прислать на экспертизу rus_verbs:жить{}, // жить на подачки rus_verbs:становиться{}, // становиться на ноги rus_verbs:наслать{}, // наслать на кого-то rus_verbs:принять{}, // принять на заметку rus_verbs:собираться{}, // собираться на экзамен rus_verbs:оставить{}, // оставить на всякий случай rus_verbs:звать{}, // звать на помощь rus_verbs:направиться{}, // направиться на прогулку rus_verbs:отвечать{}, // отвечать на звонки rus_verbs:отправиться{}, // отправиться на прогулку rus_verbs:поставить{}, // поставить на пол rus_verbs:обернуться{}, // обернуться на зов rus_verbs:отозваться{}, // отозваться на просьбу rus_verbs:закричать{}, // закричать на собаку rus_verbs:опустить{}, // опустить на землю rus_verbs:принести{}, // принести на пляж свой жезлонг rus_verbs:указать{}, // указать на дверь rus_verbs:ходить{}, // ходить на занятия rus_verbs:уставиться{}, // уставиться на листок rus_verbs:приходить{}, // приходить на экзамен rus_verbs:махнуть{}, // махнуть на пляж rus_verbs:явиться{}, // явиться на допрос rus_verbs:оглянуться{}, // оглянуться на дорогу rus_verbs:уехать{}, // уехать на заработки rus_verbs:повести{}, // повести на штурм rus_verbs:опуститься{}, // опуститься на колени //rus_verbs:передать{}, // передать на проверку rus_verbs:побежать{}, // побежать на занятия rus_verbs:прибыть{}, // прибыть на место службы rus_verbs:кричать{}, // кричать на медведя rus_verbs:стечь{}, // стечь на землю rus_verbs:обратить{}, // обратить на себя внимание rus_verbs:подать{}, // подать на пропитание rus_verbs:привести{}, // привести на съемки rus_verbs:испытывать{}, // испытывать на животных rus_verbs:перевести{}, // перевести на жену rus_verbs:купить{}, // купить на заемные деньги rus_verbs:собраться{}, // собраться на встречу rus_verbs:заглянуть{}, // заглянуть на огонёк rus_verbs:нажать{}, // нажать на рычаг rus_verbs:поспешить{}, // поспешить на праздник rus_verbs:перейти{}, // перейти на русский язык rus_verbs:поверить{}, // поверить на честное слово rus_verbs:глянуть{}, // глянуть на обложку rus_verbs:зайти{}, // зайти на огонёк rus_verbs:проходить{}, // проходить на сцену rus_verbs:глядеть{}, // глядеть на актрису //rus_verbs:решиться{}, // решиться на прыжок rus_verbs:пригласить{}, // пригласить на танец rus_verbs:позвать{}, // позвать на экзамен rus_verbs:усесться{}, // усесться на стул rus_verbs:поступить{}, // поступить на математический факультет rus_verbs:лечь{}, // лечь на живот rus_verbs:потянуться{}, // потянуться на юг rus_verbs:присесть{}, // присесть на корточки rus_verbs:наступить{}, // наступить на змею rus_verbs:заорать{}, // заорать на попрошаек rus_verbs:надеть{}, // надеть на голову rus_verbs:поглядеть{}, // поглядеть на девчонок rus_verbs:принимать{}, // принимать на гарантийное обслуживание rus_verbs:привезти{}, // привезти на испытания rus_verbs:рухнуть{}, // рухнуть на асфальт rus_verbs:пускать{}, // пускать на корм rus_verbs:отвести{}, // отвести на приём rus_verbs:отправить{}, // отправить на утилизацию rus_verbs:двигаться{}, // двигаться на восток rus_verbs:нести{}, // нести на пляж rus_verbs:падать{}, // падать на руки rus_verbs:откинуться{}, // откинуться на спинку кресла rus_verbs:рявкнуть{}, // рявкнуть на детей rus_verbs:получать{}, // получать на проживание rus_verbs:полезть{}, // полезть на рожон rus_verbs:направить{}, // направить на дообследование rus_verbs:приводить{}, // приводить на проверку rus_verbs:потребоваться{}, // потребоваться на замену rus_verbs:кинуться{}, // кинуться на нападавшего rus_verbs:учиться{}, // учиться на токаря rus_verbs:приподнять{}, // приподнять на один метр rus_verbs:налить{}, // налить на стол rus_verbs:играть{}, // играть на деньги rus_verbs:рассчитывать{}, // рассчитывать на подмогу rus_verbs:шепнуть{}, // шепнуть на ухо rus_verbs:швырнуть{}, // швырнуть на землю rus_verbs:прыгнуть{}, // прыгнуть на оленя rus_verbs:предлагать{}, // предлагать на выбор rus_verbs:садиться{}, // садиться на стул rus_verbs:лить{}, // лить на землю rus_verbs:испытать{}, // испытать на животных rus_verbs:фыркнуть{}, // фыркнуть на детеныша rus_verbs:годиться{}, // мясо годится на фарш rus_verbs:проверить{}, // проверить высказывание на истинность rus_verbs:откликнуться{}, // откликнуться на призывы rus_verbs:полагаться{}, // полагаться на интуицию rus_verbs:покоситься{}, // покоситься на соседа rus_verbs:повесить{}, // повесить на гвоздь инфинитив:походить{вид:соверш}, // походить на занятия глагол:походить{вид:соверш}, деепричастие:походив{}, прилагательное:походивший{}, rus_verbs:помчаться{}, // помчаться на экзамен rus_verbs:ставить{}, // ставить на контроль rus_verbs:свалиться{}, // свалиться на землю rus_verbs:валиться{}, // валиться на землю rus_verbs:подарить{}, // подарить на день рожденья rus_verbs:сбежать{}, // сбежать на необитаемый остров rus_verbs:стрелять{}, // стрелять на поражение rus_verbs:обращать{}, // обращать на себя внимание rus_verbs:наступать{}, // наступать на те же грабли rus_verbs:сбросить{}, // сбросить на землю rus_verbs:обидеться{}, // обидеться на друга rus_verbs:устроиться{}, // устроиться на стажировку rus_verbs:погрузиться{}, // погрузиться на большую глубину rus_verbs:течь{}, // течь на землю rus_verbs:отбросить{}, // отбросить на землю rus_verbs:метать{}, // метать на дно rus_verbs:пустить{}, // пустить на переплавку rus_verbs:прожить{}, // прожить на пособие rus_verbs:полететь{}, // полететь на континент rus_verbs:пропустить{}, // пропустить на сцену rus_verbs:указывать{}, // указывать на ошибку rus_verbs:наткнуться{}, // наткнуться на клад rus_verbs:рвануть{}, // рвануть на юг rus_verbs:ступать{}, // ступать на землю rus_verbs:спрыгнуть{}, // спрыгнуть на берег rus_verbs:заходить{}, // заходить на огонёк rus_verbs:нырнуть{}, // нырнуть на глубину rus_verbs:рвануться{}, // рвануться на свободу rus_verbs:натянуть{}, // натянуть на голову rus_verbs:забраться{}, // забраться на стол rus_verbs:помахать{}, // помахать на прощание rus_verbs:содержать{}, // содержать на спонсорскую помощь rus_verbs:приезжать{}, // приезжать на праздники rus_verbs:проникнуть{}, // проникнуть на территорию rus_verbs:подъехать{}, // подъехать на митинг rus_verbs:устремиться{}, // устремиться на волю rus_verbs:посадить{}, // посадить на стул rus_verbs:ринуться{}, // ринуться на голкипера rus_verbs:подвигнуть{}, // подвигнуть на подвиг rus_verbs:отдавать{}, // отдавать на перевоспитание rus_verbs:отложить{}, // отложить на черный день rus_verbs:убежать{}, // убежать на танцы rus_verbs:поднимать{}, // поднимать на верхний этаж rus_verbs:переходить{}, // переходить на цифровой сигнал rus_verbs:отослать{}, // отослать на переаттестацию rus_verbs:отодвинуть{}, // отодвинуть на другую половину стола rus_verbs:назначить{}, // назначить на должность rus_verbs:осесть{}, // осесть на дно rus_verbs:торопиться{}, // торопиться на экзамен rus_verbs:менять{}, // менять на еду rus_verbs:доставить{}, // доставить на шестой этаж rus_verbs:заслать{}, // заслать на проверку rus_verbs:дуть{}, // дуть на воду rus_verbs:сослать{}, // сослать на каторгу rus_verbs:останавливаться{}, // останавливаться на отдых rus_verbs:сдаваться{}, // сдаваться на милость победителя rus_verbs:сослаться{}, // сослаться на презумпцию невиновности rus_verbs:рассердиться{}, // рассердиться на дочь rus_verbs:кинуть{}, // кинуть на землю rus_verbs:расположиться{}, // расположиться на ночлег rus_verbs:осмелиться{}, // осмелиться на подлог rus_verbs:шептать{}, // шептать на ушко rus_verbs:уронить{}, // уронить на землю rus_verbs:откинуть{}, // откинуть на спинку кресла rus_verbs:перенести{}, // перенести на рабочий стол rus_verbs:сдаться{}, // сдаться на милость победителя rus_verbs:светить{}, // светить на дорогу rus_verbs:мчаться{}, // мчаться на бал rus_verbs:нестись{}, // нестись на свидание rus_verbs:поглядывать{}, // поглядывать на экран rus_verbs:орать{}, // орать на детей rus_verbs:уложить{}, // уложить на лопатки rus_verbs:решаться{}, // решаться на поступок rus_verbs:попадать{}, // попадать на карандаш rus_verbs:сплюнуть{}, // сплюнуть на землю rus_verbs:снимать{}, // снимать на телефон rus_verbs:опоздать{}, // опоздать на работу rus_verbs:посылать{}, // посылать на проверку rus_verbs:погнать{}, // погнать на пастбище rus_verbs:поступать{}, // поступать на кибернетический факультет rus_verbs:спускаться{}, // спускаться на уровень моря rus_verbs:усадить{}, // усадить на диван rus_verbs:проиграть{}, // проиграть на спор rus_verbs:прилететь{}, // прилететь на фестиваль rus_verbs:повалиться{}, // повалиться на спину rus_verbs:огрызнуться{}, // Собака огрызнулась на хозяина rus_verbs:задавать{}, // задавать на выходные rus_verbs:запасть{}, // запасть на девочку rus_verbs:лезть{}, // лезть на забор rus_verbs:потащить{}, // потащить на выборы rus_verbs:направляться{}, // направляться на экзамен rus_verbs:определять{}, // определять на вкус rus_verbs:поползти{}, // поползти на стену rus_verbs:поплыть{}, // поплыть на берег rus_verbs:залезть{}, // залезть на яблоню rus_verbs:сдать{}, // сдать на мясокомбинат rus_verbs:приземлиться{}, // приземлиться на дорогу rus_verbs:лаять{}, // лаять на прохожих rus_verbs:перевернуть{}, // перевернуть на бок rus_verbs:ловить{}, // ловить на живца rus_verbs:отнести{}, // отнести животное на хирургический стол rus_verbs:плюнуть{}, // плюнуть на условности rus_verbs:передавать{}, // передавать на проверку rus_verbs:нанять{}, // Босс нанял на работу еще несколько человек rus_verbs:разозлиться{}, // Папа разозлился на сына из-за плохих оценок по математике инфинитив:рассыпаться{вид:несоверш}, // рассыпаться на мелкие детали инфинитив:рассыпаться{вид:соверш}, глагол:рассыпаться{вид:несоверш}, глагол:рассыпаться{вид:соверш}, деепричастие:рассыпавшись{}, деепричастие:рассыпаясь{}, прилагательное:рассыпавшийся{вид:несоверш}, прилагательное:рассыпавшийся{вид:соверш}, прилагательное:рассыпающийся{}, rus_verbs:зарычать{}, // Медведица зарычала на медвежонка rus_verbs:призвать{}, // призвать на сборы rus_verbs:увезти{}, // увезти на дачу rus_verbs:содержаться{}, // содержаться на пожертвования rus_verbs:навести{}, // навести на скопление телескоп rus_verbs:отправляться{}, // отправляться на утилизацию rus_verbs:улечься{}, // улечься на животик rus_verbs:налететь{}, // налететь на препятствие rus_verbs:перевернуться{}, // перевернуться на спину rus_verbs:улететь{}, // улететь на родину rus_verbs:ложиться{}, // ложиться на бок rus_verbs:класть{}, // класть на место rus_verbs:отреагировать{}, // отреагировать на выступление rus_verbs:доставлять{}, // доставлять на дом rus_verbs:отнять{}, // отнять на благо правящей верхушки rus_verbs:ступить{}, // ступить на землю rus_verbs:сводить{}, // сводить на концерт знаменитой рок-группы rus_verbs:унести{}, // унести на работу rus_verbs:сходить{}, // сходить на концерт rus_verbs:потратить{}, // потратить на корм и наполнитель для туалета все деньги rus_verbs:соскочить{}, // соскочить на землю rus_verbs:пожаловаться{}, // пожаловаться на соседей rus_verbs:тащить{}, // тащить на замену rus_verbs:замахать{}, // замахать руками на паренька rus_verbs:заглядывать{}, // заглядывать на обед rus_verbs:соглашаться{}, // соглашаться на равный обмен rus_verbs:плюхнуться{}, // плюхнуться на мягкий пуфик rus_verbs:увести{}, // увести на осмотр rus_verbs:успевать{}, // успевать на контрольную работу rus_verbs:опрокинуть{}, // опрокинуть на себя rus_verbs:подавать{}, // подавать на апелляцию rus_verbs:прибежать{}, // прибежать на вокзал rus_verbs:отшвырнуть{}, // отшвырнуть на замлю rus_verbs:привлекать{}, // привлекать на свою сторону rus_verbs:опереться{}, // опереться на палку rus_verbs:перебраться{}, // перебраться на маленький островок rus_verbs:уговорить{}, // уговорить на новые траты rus_verbs:гулять{}, // гулять на спонсорские деньги rus_verbs:переводить{}, // переводить на другой путь rus_verbs:заколебаться{}, // заколебаться на один миг rus_verbs:зашептать{}, // зашептать на ушко rus_verbs:привстать{}, // привстать на цыпочки rus_verbs:хлынуть{}, // хлынуть на берег rus_verbs:наброситься{}, // наброситься на еду rus_verbs:напасть{}, // повстанцы, напавшие на конвой rus_verbs:убрать{}, // книга, убранная на полку rus_verbs:попасть{}, // путешественники, попавшие на ничейную территорию rus_verbs:засматриваться{}, // засматриваться на девчонок rus_verbs:застегнуться{}, // застегнуться на все пуговицы rus_verbs:провериться{}, // провериться на заболевания rus_verbs:проверяться{}, // проверяться на заболевания rus_verbs:тестировать{}, // тестировать на профпригодность rus_verbs:протестировать{}, // протестировать на профпригодность rus_verbs:уходить{}, // отец, уходящий на работу rus_verbs:налипнуть{}, // снег, налипший на провода rus_verbs:налипать{}, // снег, налипающий на провода rus_verbs:улетать{}, // Многие птицы улетают осенью на юг. rus_verbs:поехать{}, // она поехала на встречу с заказчиком rus_verbs:переключать{}, // переключать на резервную линию rus_verbs:переключаться{}, // переключаться на резервную линию rus_verbs:подписаться{}, // подписаться на обновление rus_verbs:нанести{}, // нанести на кожу rus_verbs:нарываться{}, // нарываться на неприятности rus_verbs:выводить{}, // выводить на орбиту rus_verbs:вернуться{}, // вернуться на родину rus_verbs:возвращаться{}, // возвращаться на родину прилагательное:падкий{}, // Он падок на деньги. прилагательное:обиженный{}, // Он обижен на отца. rus_verbs:косить{}, // Он косит на оба глаза. rus_verbs:закрыть{}, // Он забыл закрыть дверь на замок. прилагательное:готовый{}, // Он готов на всякие жертвы. rus_verbs:говорить{}, // Он говорит на скользкую тему. прилагательное:глухой{}, // Он глух на одно ухо. rus_verbs:взять{}, // Он взял ребёнка себе на колени. rus_verbs:оказывать{}, // Лекарство не оказывало на него никакого действия. rus_verbs:вести{}, // Лестница ведёт на третий этаж. rus_verbs:уполномочивать{}, // уполномочивать на что-либо глагол:спешить{ вид:несоверш }, // Я спешу на поезд. rus_verbs:брать{}, // Я беру всю ответственность на себя. rus_verbs:произвести{}, // Это произвело на меня глубокое впечатление. rus_verbs:употребить{}, // Эти деньги можно употребить на ремонт фабрики. rus_verbs:наводить{}, // Эта песня наводит на меня сон и скуку. rus_verbs:разбираться{}, // Эта машина разбирается на части. rus_verbs:оказать{}, // Эта книга оказала на меня большое влияние. rus_verbs:разбить{}, // Учитель разбил учеников на несколько групп. rus_verbs:отразиться{}, // Усиленная работа отразилась на его здоровье. rus_verbs:перегрузить{}, // Уголь надо перегрузить на другое судно. rus_verbs:делиться{}, // Тридцать делится на пять без остатка. rus_verbs:удаляться{}, // Суд удаляется на совещание. rus_verbs:показывать{}, // Стрелка компаса всегда показывает на север. rus_verbs:сохранить{}, // Сохраните это на память обо мне. rus_verbs:уезжать{}, // Сейчас все студенты уезжают на экскурсию. rus_verbs:лететь{}, // Самолёт летит на север. rus_verbs:бить{}, // Ружьё бьёт на пятьсот метров. // rus_verbs:прийтись{}, // Пятое число пришлось на субботу. rus_verbs:вынести{}, // Они вынесли из лодки на берег все вещи. rus_verbs:смотреть{}, // Она смотрит на нас из окна. rus_verbs:отдать{}, // Она отдала мне деньги на сохранение. rus_verbs:налюбоваться{}, // Не могу налюбоваться на картину. rus_verbs:любоваться{}, // гости любовались на картину rus_verbs:попробовать{}, // Дайте мне попробовать на ощупь. прилагательное:действительный{}, // Прививка оспы действительна только на три года. rus_verbs:спуститься{}, // На город спустился смог прилагательное:нечистый{}, // Он нечист на руку. прилагательное:неспособный{}, // Он неспособен на такую низость. прилагательное:злой{}, // кот очень зол на хозяина rus_verbs:пойти{}, // Девочка не пошла на урок физультуры rus_verbs:прибывать{}, // мой поезд прибывает на первый путь rus_verbs:застегиваться{}, // пальто застегивается на двадцать одну пуговицу rus_verbs:идти{}, // Дело идёт на лад. rus_verbs:лазить{}, // Он лазил на чердак. rus_verbs:поддаваться{}, // Он легко поддаётся на уговоры. // rus_verbs:действовать{}, // действующий на нервы rus_verbs:выходить{}, // Балкон выходит на площадь. rus_verbs:работать{}, // Время работает на нас. глагол:написать{aux stress="напис^ать"}, // Он написал музыку на слова Пушкина. rus_verbs:бросить{}, // Они бросили все силы на строительство. // глагол:разрезать{aux stress="разр^езать"}, глагол:разрезать{aux stress="разрез^ать"}, // Она разрезала пирог на шесть кусков. rus_verbs:броситься{}, // Она радостно бросилась мне на шею. rus_verbs:оправдать{}, // Она оправдала неявку на занятия болезнью. rus_verbs:ответить{}, // Она не ответила на мой поклон. rus_verbs:нашивать{}, // Она нашивала заплату на локоть. rus_verbs:молиться{}, // Она молится на свою мать. rus_verbs:запереть{}, // Она заперла дверь на замок. rus_verbs:заявить{}, // Она заявила свои права на наследство. rus_verbs:уйти{}, // Все деньги ушли на путешествие. rus_verbs:вступить{}, // Водолаз вступил на берег. rus_verbs:сойти{}, // Ночь сошла на землю. rus_verbs:приехать{}, // Мы приехали на вокзал слишком рано. rus_verbs:рыдать{}, // Не рыдай так безумно над ним. rus_verbs:подписать{}, // Не забудьте подписать меня на газету. rus_verbs:держать{}, // Наш пароход держал курс прямо на север. rus_verbs:свезти{}, // На выставку свезли экспонаты со всего мира. rus_verbs:ехать{}, // Мы сейчас едем на завод. rus_verbs:выбросить{}, // Волнами лодку выбросило на берег. ГЛ_ИНФ(сесть), // сесть на снег ГЛ_ИНФ(записаться), ГЛ_ИНФ(положить) // положи книгу на стол } #endregion VerbList // Чтобы разрешить связывание в паттернах типа: залить на youtube fact гл_предл { if context { Гл_НА_Вин предлог:на{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { глагол:купить{} предлог:на{} 'деньги'{падеж:вин} } then return true } fact гл_предл { if context { Гл_НА_Вин предлог:на{} *:*{ падеж:вин } } then return true } // смещаться на несколько миллиметров fact гл_предл { if context { Гл_НА_Вин предлог:на{} наречие:*{} } then return true } // партия взяла на себя нереалистичные обязательства fact гл_предл { if context { глагол:взять{} предлог:на{} 'себя'{падеж:вин} } then return true } #endregion ВИНИТЕЛЬНЫЙ // Все остальные варианты с предлогом 'НА' по умолчанию запрещаем. fact гл_предл { if context { * предлог:на{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:на{} *:*{ падеж:мест } } then return false,-3 } fact гл_предл { if context { * предлог:на{} *:*{ падеж:вин } } then return false,-4 } // Этот вариант нужен для обработки конструкций с числительными: // Президентские выборы разделили Венесуэлу на два непримиримых лагеря fact гл_предл { if context { * предлог:на{} *:*{ падеж:род } } then return false,-4 } // Продавать на eBay fact гл_предл { if context { * предлог:на{} * } then return false,-6 } #endregion Предлог_НА #region Предлог_С // ------------- ПРЕДЛОГ 'С' ----------------- // У этого предлога предпочтительная семантика привязывает его обычно к существительному. // Поэтому запрещаем по умолчанию его привязку к глаголам, а разрешенные глаголы перечислим. #region ТВОРИТЕЛЬНЫЙ wordentry_set Гл_С_Твор={ rus_verbs:помогать{}, // будет готов помогать врачам в онкологическом центре с постановкой верных диагнозов rus_verbs:перепихнуться{}, // неужели ты не хочешь со мной перепихнуться rus_verbs:забраться{}, rus_verbs:ДРАТЬСЯ{}, // Мои же собственные ратники забросали бы меня гнилой капустой, и мне пришлось бы драться с каждым рыцарем в стране, чтобы доказать свою смелость. (ДРАТЬСЯ/БИТЬСЯ/ПОДРАТЬСЯ) rus_verbs:БИТЬСЯ{}, // rus_verbs:ПОДРАТЬСЯ{}, // прилагательное:СХОЖИЙ{}, // Не был ли он схожим с одним из живых языков Земли (СХОЖИЙ) rus_verbs:ВСТУПИТЬ{}, // Он намеревался вступить с Вольфом в ближний бой. (ВСТУПИТЬ) rus_verbs:КОРРЕЛИРОВАТЬ{}, // Это коррелирует с традиционно сильными направлениями московской математической школы. (КОРРЕЛИРОВАТЬ) rus_verbs:УВИДЕТЬСЯ{}, // Он проигнорирует истерические протесты жены и увидится сначала с доктором, а затем с психотерапевтом (УВИДЕТЬСЯ) rus_verbs:ОЧНУТЬСЯ{}, // Когда он очнулся с болью в левой стороне черепа, у него возникло пугающее ощущение. (ОЧНУТЬСЯ) прилагательное:сходный{}, // Мозг этих существ сходен по размерам с мозгом динозавра rus_verbs:накрыться{}, // Было холодно, и он накрылся с головой одеялом. rus_verbs:РАСПРЕДЕЛИТЬ{}, // Бюджет распределят с участием горожан (РАСПРЕДЕЛИТЬ) rus_verbs:НАБРОСИТЬСЯ{}, // Пьяный водитель набросился с ножом на сотрудников ГИБДД (НАБРОСИТЬСЯ) rus_verbs:БРОСИТЬСЯ{}, // она со смехом бросилась прочь (БРОСИТЬСЯ) rus_verbs:КОНТАКТИРОВАТЬ{}, // Электронным магазинам стоит контактировать с клиентами (КОНТАКТИРОВАТЬ) rus_verbs:ВИДЕТЬСЯ{}, // Тогда мы редко виделись друг с другом rus_verbs:сесть{}, // сел в него с дорожной сумкой , наполненной наркотиками rus_verbs:купить{}, // Мы купили с ним одну и ту же книгу rus_verbs:ПРИМЕНЯТЬ{}, // Меры по стимулированию спроса в РФ следует применять с осторожностью (ПРИМЕНЯТЬ) rus_verbs:УЙТИ{}, // ты мог бы уйти со мной (УЙТИ) rus_verbs:ЖДАТЬ{}, // С нарастающим любопытством ждем результатов аудита золотых хранилищ европейских и американских центробанков (ЖДАТЬ) rus_verbs:ГОСПИТАЛИЗИРОВАТЬ{}, // Мэра Твери, участвовавшего в спартакиаде, госпитализировали с инфарктом (ГОСПИТАЛИЗИРОВАТЬ) rus_verbs:ЗАХЛОПНУТЬСЯ{}, // она захлопнулась со звоном (ЗАХЛОПНУТЬСЯ) rus_verbs:ОТВЕРНУТЬСЯ{}, // она со вздохом отвернулась (ОТВЕРНУТЬСЯ) rus_verbs:отправить{}, // вы можете отправить со мной человека rus_verbs:выступать{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам rus_verbs:ВЫЕЗЖАТЬ{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку (ВЫЕЗЖАТЬ С твор) rus_verbs:ПОКОНЧИТЬ{}, // со всем этим покончено (ПОКОНЧИТЬ С) rus_verbs:ПОБЕЖАТЬ{}, // Дмитрий побежал со всеми (ПОБЕЖАТЬ С) прилагательное:несовместимый{}, // характер ранений был несовместим с жизнью (НЕСОВМЕСТИМЫЙ С) rus_verbs:ПОСЕТИТЬ{}, // Его кабинет местные тележурналисты посетили со скрытой камерой (ПОСЕТИТЬ С) rus_verbs:СЛОЖИТЬСЯ{}, // сами банки принимают меры по урегулированию сложившейся с вкладчиками ситуации (СЛОЖИТЬСЯ С) rus_verbs:ЗАСТАТЬ{}, // Молодой человек убил пенсионера , застав его в постели с женой (ЗАСТАТЬ С) rus_verbs:ОЗНАКАМЛИВАТЬСЯ{}, // при заполнении заявления владельцы судов ознакамливаются с режимом (ОЗНАКАМЛИВАТЬСЯ С) rus_verbs:СООБРАЗОВЫВАТЬ{}, // И все свои задачи мы сообразовываем с этим пониманием (СООБРАЗОВЫВАТЬ С) rus_verbs:СВЫКАТЬСЯ{}, rus_verbs:стаскиваться{}, rus_verbs:спиливаться{}, rus_verbs:КОНКУРИРОВАТЬ{}, // Бедные и менее развитые страны не могут конкурировать с этими субсидиями (КОНКУРИРОВАТЬ С) rus_verbs:ВЫРВАТЬСЯ{}, // тот с трудом вырвался (ВЫРВАТЬСЯ С твор) rus_verbs:СОБРАТЬСЯ{}, // нужно собраться с силами (СОБРАТЬСЯ С) rus_verbs:УДАВАТЬСЯ{}, // удавалось это с трудом (УДАВАТЬСЯ С) rus_verbs:РАСПАХНУТЬСЯ{}, // дверь с треском распахнулась (РАСПАХНУТЬСЯ С) rus_verbs:НАБЛЮДАТЬ{}, // Олег наблюдал с любопытством (НАБЛЮДАТЬ С) rus_verbs:ПОТЯНУТЬ{}, // затем с силой потянул (ПОТЯНУТЬ С) rus_verbs:КИВНУТЬ{}, // Питер с трудом кивнул (КИВНУТЬ С) rus_verbs:СГЛОТНУТЬ{}, // Борис с трудом сглотнул (СГЛОТНУТЬ С) rus_verbs:ЗАБРАТЬ{}, // забрать его с собой (ЗАБРАТЬ С) rus_verbs:ОТКРЫТЬСЯ{}, // дверь с шипением открылась (ОТКРЫТЬСЯ С) rus_verbs:ОТОРВАТЬ{}, // с усилием оторвал взгляд (ОТОРВАТЬ С твор) rus_verbs:ОГЛЯДЕТЬСЯ{}, // Рома с любопытством огляделся (ОГЛЯДЕТЬСЯ С) rus_verbs:ФЫРКНУТЬ{}, // турок фыркнул с отвращением (ФЫРКНУТЬ С) rus_verbs:согласиться{}, // с этим согласились все (согласиться с) rus_verbs:ПОСЫПАТЬСЯ{}, // с грохотом посыпались камни (ПОСЫПАТЬСЯ С твор) rus_verbs:ВЗДОХНУТЬ{}, // Алиса вздохнула с облегчением (ВЗДОХНУТЬ С) rus_verbs:ОБЕРНУТЬСЯ{}, // та с удивлением обернулась (ОБЕРНУТЬСЯ С) rus_verbs:ХМЫКНУТЬ{}, // Алексей хмыкнул с сомнением (ХМЫКНУТЬ С твор) rus_verbs:ВЫЕХАТЬ{}, // они выехали с рассветом (ВЫЕХАТЬ С твор) rus_verbs:ВЫДОХНУТЬ{}, // Владимир выдохнул с облегчением (ВЫДОХНУТЬ С) rus_verbs:УХМЫЛЬНУТЬСЯ{}, // Кеша ухмыльнулся с сомнением (УХМЫЛЬНУТЬСЯ С) rus_verbs:НЕСТИСЬ{}, // тот несся с криком (НЕСТИСЬ С твор) rus_verbs:ПАДАТЬ{}, // падают с глухим стуком (ПАДАТЬ С твор) rus_verbs:ТВОРИТЬСЯ{}, // странное творилось с глазами (ТВОРИТЬСЯ С твор) rus_verbs:УХОДИТЬ{}, // с ними уходили эльфы (УХОДИТЬ С твор) rus_verbs:СКАКАТЬ{}, // скакали тут с топорами (СКАКАТЬ С твор) rus_verbs:ЕСТЬ{}, // здесь едят с зеленью (ЕСТЬ С твор) rus_verbs:ПОЯВИТЬСЯ{}, // с рассветом появились птицы (ПОЯВИТЬСЯ С твор) rus_verbs:ВСКОЧИТЬ{}, // Олег вскочил с готовностью (ВСКОЧИТЬ С твор) rus_verbs:БЫТЬ{}, // хочу быть с тобой (БЫТЬ С твор) rus_verbs:ПОКАЧАТЬ{}, // с сомнением покачал головой. (ПОКАЧАТЬ С СОМНЕНИЕМ) rus_verbs:ВЫРУГАТЬСЯ{}, // капитан с чувством выругался (ВЫРУГАТЬСЯ С ЧУВСТВОМ) rus_verbs:ОТКРЫТЬ{}, // с трудом открыл глаза (ОТКРЫТЬ С ТРУДОМ, таких много) rus_verbs:ПОЛУЧИТЬСЯ{}, // забавно получилось с ним (ПОЛУЧИТЬСЯ С) rus_verbs:ВЫБЕЖАТЬ{}, // старый выбежал с копьем (ВЫБЕЖАТЬ С) rus_verbs:ГОТОВИТЬСЯ{}, // Большинство компотов готовится с использованием сахара (ГОТОВИТЬСЯ С) rus_verbs:ПОДИСКУТИРОВАТЬ{}, // я бы подискутировал с Андрюхой (ПОДИСКУТИРОВАТЬ С) rus_verbs:ТУСИТЬ{}, // кто тусил со Светкой (ТУСИТЬ С) rus_verbs:БЕЖАТЬ{}, // куда она бежит со всеми? (БЕЖАТЬ С твор) rus_verbs:ГОРЕТЬ{}, // ты горел со своим кораблем? (ГОРЕТЬ С) rus_verbs:ВЫПИТЬ{}, // хотите выпить со мной чаю? (ВЫПИТЬ С) rus_verbs:МЕНЯТЬСЯ{}, // Я меняюсь с товарищем книгами. (МЕНЯТЬСЯ С) rus_verbs:ВАЛЯТЬСЯ{}, // Он уже неделю валяется с гриппом. (ВАЛЯТЬСЯ С) rus_verbs:ПИТЬ{}, // вы даже будете пить со мной пиво. (ПИТЬ С) инфинитив:кристаллизоваться{ вид:соверш }, // После этого пересыщенный раствор кристаллизуется с образованием кристаллов сахара. инфинитив:кристаллизоваться{ вид:несоверш }, глагол:кристаллизоваться{ вид:соверш }, глагол:кристаллизоваться{ вид:несоверш }, rus_verbs:ПООБЩАТЬСЯ{}, // пообщайся с Борисом (ПООБЩАТЬСЯ С) rus_verbs:ОБМЕНЯТЬСЯ{}, // Миша обменялся с Петей марками (ОБМЕНЯТЬСЯ С) rus_verbs:ПРОХОДИТЬ{}, // мы с тобой сегодня весь день проходили с вещами. (ПРОХОДИТЬ С) rus_verbs:ВСТАТЬ{}, // Он занимался всю ночь и встал с головной болью. (ВСТАТЬ С) rus_verbs:ПОВРЕМЕНИТЬ{}, // МВФ рекомендует Ирландии повременить с мерами экономии (ПОВРЕМЕНИТЬ С) rus_verbs:ГЛЯДЕТЬ{}, // Её глаза глядели с мягкой грустью. (ГЛЯДЕТЬ С + твор) rus_verbs:ВЫСКОЧИТЬ{}, // Зачем ты выскочил со своим замечанием? (ВЫСКОЧИТЬ С) rus_verbs:НЕСТИ{}, // плот несло со страшной силой. (НЕСТИ С) rus_verbs:приближаться{}, // стена приближалась со страшной быстротой. (приближаться с) rus_verbs:заниматься{}, // После уроков я занимался с отстающими учениками. (заниматься с) rus_verbs:разработать{}, // Этот лекарственный препарат разработан с использованием рецептов традиционной китайской медицины. (разработать с) rus_verbs:вестись{}, // Разработка месторождения ведется с использованием большого количества техники. (вестись с) rus_verbs:конфликтовать{}, // Маша конфликтует с Петей (конфликтовать с) rus_verbs:мешать{}, // мешать воду с мукой (мешать с) rus_verbs:иметь{}, // мне уже приходилось несколько раз иметь с ним дело. rus_verbs:синхронизировать{}, // синхронизировать с эталонным генератором rus_verbs:засинхронизировать{}, // засинхронизировать с эталонным генератором rus_verbs:синхронизироваться{}, // синхронизироваться с эталонным генератором rus_verbs:засинхронизироваться{}, // засинхронизироваться с эталонным генератором rus_verbs:стирать{}, // стирать с мылом рубашку в тазу rus_verbs:прыгать{}, // парашютист прыгает с парашютом rus_verbs:выступить{}, // Он выступил с приветствием съезду. rus_verbs:ходить{}, // В чужой монастырь со своим уставом не ходят. rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой. rus_verbs:отзываться{}, // Он отзывается об этой книге с большой похвалой. rus_verbs:вставать{}, // он встаёт с зарёй rus_verbs:мирить{}, // Его ум мирил всех с его дурным характером. rus_verbs:продолжаться{}, // стрельба тем временем продолжалась с прежней точностью. rus_verbs:договориться{}, // мы договоримся с вами rus_verbs:побыть{}, // он хотел побыть с тобой rus_verbs:расти{}, // Мировые производственные мощности растут с беспрецедентной скоростью rus_verbs:вязаться{}, // вязаться с фактами rus_verbs:отнестись{}, // отнестись к животным с сочуствием rus_verbs:относиться{}, // относиться с пониманием rus_verbs:пойти{}, // Спектакль пойдёт с участием известных артистов. rus_verbs:бракосочетаться{}, // Потомственный кузнец бракосочетался с разорившейся графиней rus_verbs:гулять{}, // бабушка гуляет с внуком rus_verbs:разбираться{}, // разбираться с задачей rus_verbs:сверить{}, // Данные были сверены с эталонными значениями rus_verbs:делать{}, // Что делать со старым телефоном rus_verbs:осматривать{}, // осматривать с удивлением rus_verbs:обсудить{}, // обсудить с приятелем прохождение уровня в новой игре rus_verbs:попрощаться{}, // попрощаться с талантливым актером rus_verbs:задремать{}, // задремать с кружкой чая в руке rus_verbs:связать{}, // связать катастрофу с действиями конкурентов rus_verbs:носиться{}, // носиться с безумной идеей rus_verbs:кончать{}, // кончать с собой rus_verbs:обмениваться{}, // обмениваться с собеседниками rus_verbs:переговариваться{}, // переговариваться с маяком rus_verbs:общаться{}, // общаться с полицией rus_verbs:завершить{}, // завершить с ошибкой rus_verbs:обняться{}, // обняться с подругой rus_verbs:сливаться{}, // сливаться с фоном rus_verbs:смешаться{}, // смешаться с толпой rus_verbs:договариваться{}, // договариваться с потерпевшим rus_verbs:обедать{}, // обедать с гостями rus_verbs:сообщаться{}, // сообщаться с подземной рекой rus_verbs:сталкиваться{}, // сталкиваться со стаей птиц rus_verbs:читаться{}, // читаться с трудом rus_verbs:смириться{}, // смириться с утратой rus_verbs:разделить{}, // разделить с другими ответственность rus_verbs:роднить{}, // роднить с медведем rus_verbs:медлить{}, // медлить с ответом rus_verbs:скрестить{}, // скрестить с ужом rus_verbs:покоиться{}, // покоиться с миром rus_verbs:делиться{}, // делиться с друзьями rus_verbs:познакомить{}, // познакомить с Олей rus_verbs:порвать{}, // порвать с Олей rus_verbs:завязать{}, // завязать с Олей знакомство rus_verbs:суетиться{}, // суетиться с изданием романа rus_verbs:соединиться{}, // соединиться с сервером rus_verbs:справляться{}, // справляться с нуждой rus_verbs:замешкаться{}, // замешкаться с ответом rus_verbs:поссориться{}, // поссориться с подругой rus_verbs:ссориться{}, // ссориться с друзьями rus_verbs:торопить{}, // торопить с решением rus_verbs:поздравить{}, // поздравить с победой rus_verbs:проститься{}, // проститься с человеком rus_verbs:поработать{}, // поработать с деревом rus_verbs:приключиться{}, // приключиться с Колей rus_verbs:сговориться{}, // сговориться с Ваней rus_verbs:отъехать{}, // отъехать с ревом rus_verbs:объединять{}, // объединять с другой кампанией rus_verbs:употребить{}, // употребить с молоком rus_verbs:перепутать{}, // перепутать с другой книгой rus_verbs:запоздать{}, // запоздать с ответом rus_verbs:подружиться{}, // подружиться с другими детьми rus_verbs:дружить{}, // дружить с Сережей rus_verbs:поравняться{}, // поравняться с финишной чертой rus_verbs:ужинать{}, // ужинать с гостями rus_verbs:расставаться{}, // расставаться с приятелями rus_verbs:завтракать{}, // завтракать с семьей rus_verbs:объединиться{}, // объединиться с соседями rus_verbs:сменяться{}, // сменяться с напарником rus_verbs:соединить{}, // соединить с сетью rus_verbs:разговориться{}, // разговориться с охранником rus_verbs:преподнести{}, // преподнести с помпой rus_verbs:напечатать{}, // напечатать с картинками rus_verbs:соединять{}, // соединять с сетью rus_verbs:расправиться{}, // расправиться с беззащитным человеком rus_verbs:распрощаться{}, // распрощаться с деньгами rus_verbs:сравнить{}, // сравнить с конкурентами rus_verbs:ознакомиться{}, // ознакомиться с выступлением инфинитив:сочетаться{ вид:несоверш }, глагол:сочетаться{ вид:несоверш }, // сочетаться с сумочкой деепричастие:сочетаясь{}, прилагательное:сочетающийся{}, прилагательное:сочетавшийся{}, rus_verbs:изнасиловать{}, // изнасиловать с применением чрезвычайного насилия rus_verbs:прощаться{}, // прощаться с боевым товарищем rus_verbs:сравнивать{}, // сравнивать с конкурентами rus_verbs:складывать{}, // складывать с весом упаковки rus_verbs:повестись{}, // повестись с ворами rus_verbs:столкнуть{}, // столкнуть с отбойником rus_verbs:переглядываться{}, // переглядываться с соседом rus_verbs:поторопить{}, // поторопить с откликом rus_verbs:развлекаться{}, // развлекаться с подружками rus_verbs:заговаривать{}, // заговаривать с незнакомцами rus_verbs:поцеловаться{}, // поцеловаться с первой девушкой инфинитив:согласоваться{ вид:несоверш }, глагол:согласоваться{ вид:несоверш }, // согласоваться с подлежащим деепричастие:согласуясь{}, прилагательное:согласующийся{}, rus_verbs:совпасть{}, // совпасть с оригиналом rus_verbs:соединяться{}, // соединяться с куратором rus_verbs:повстречаться{}, // повстречаться с героями rus_verbs:поужинать{}, // поужинать с родителями rus_verbs:развестись{}, // развестись с первым мужем rus_verbs:переговорить{}, // переговорить с коллегами rus_verbs:сцепиться{}, // сцепиться с бродячей собакой rus_verbs:сожрать{}, // сожрать с потрохами rus_verbs:побеседовать{}, // побеседовать со шпаной rus_verbs:поиграть{}, // поиграть с котятами rus_verbs:сцепить{}, // сцепить с тягачом rus_verbs:помириться{}, // помириться с подружкой rus_verbs:связываться{}, // связываться с бандитами rus_verbs:совещаться{}, // совещаться с мастерами rus_verbs:обрушиваться{}, // обрушиваться с беспощадной критикой rus_verbs:переплестись{}, // переплестись с кустами rus_verbs:мутить{}, // мутить с одногрупницами rus_verbs:приглядываться{}, // приглядываться с интересом rus_verbs:сблизиться{}, // сблизиться с врагами rus_verbs:перешептываться{}, // перешептываться с симпатичной соседкой rus_verbs:растереть{}, // растереть с солью rus_verbs:смешиваться{}, // смешиваться с известью rus_verbs:соприкоснуться{}, // соприкоснуться с тайной rus_verbs:ладить{}, // ладить с родственниками rus_verbs:сотрудничать{}, // сотрудничать с органами дознания rus_verbs:съехаться{}, // съехаться с родственниками rus_verbs:перекинуться{}, // перекинуться с коллегами парой слов rus_verbs:советоваться{}, // советоваться с отчимом rus_verbs:сравниться{}, // сравниться с лучшими rus_verbs:знакомиться{}, // знакомиться с абитуриентами rus_verbs:нырять{}, // нырять с аквалангом rus_verbs:забавляться{}, // забавляться с куклой rus_verbs:перекликаться{}, // перекликаться с другой статьей rus_verbs:тренироваться{}, // тренироваться с партнершей rus_verbs:поспорить{}, // поспорить с казночеем инфинитив:сладить{ вид:соверш }, глагол:сладить{ вид:соверш }, // сладить с бычком деепричастие:сладив{}, прилагательное:сладивший{ вид:соверш }, rus_verbs:примириться{}, // примириться с утратой rus_verbs:раскланяться{}, // раскланяться с фрейлинами rus_verbs:слечь{}, // слечь с ангиной rus_verbs:соприкасаться{}, // соприкасаться со стеной rus_verbs:смешать{}, // смешать с грязью rus_verbs:пересекаться{}, // пересекаться с трассой rus_verbs:путать{}, // путать с государственной шерстью rus_verbs:поболтать{}, // поболтать с ученицами rus_verbs:здороваться{}, // здороваться с профессором rus_verbs:просчитаться{}, // просчитаться с покупкой rus_verbs:сторожить{}, // сторожить с собакой rus_verbs:обыскивать{}, // обыскивать с собаками rus_verbs:переплетаться{}, // переплетаться с другой веткой rus_verbs:обниматься{}, // обниматься с Ксюшей rus_verbs:объединяться{}, // объединяться с конкурентами rus_verbs:погорячиться{}, // погорячиться с покупкой rus_verbs:мыться{}, // мыться с мылом rus_verbs:свериться{}, // свериться с эталоном rus_verbs:разделаться{}, // разделаться с кем-то rus_verbs:чередоваться{}, // чередоваться с партнером rus_verbs:налететь{}, // налететь с соратниками rus_verbs:поспать{}, // поспать с включенным светом rus_verbs:управиться{}, // управиться с собакой rus_verbs:согрешить{}, // согрешить с замужней rus_verbs:определиться{}, // определиться с победителем rus_verbs:перемешаться{}, // перемешаться с гранулами rus_verbs:затрудняться{}, // затрудняться с ответом rus_verbs:обождать{}, // обождать со стартом rus_verbs:фыркать{}, // фыркать с презрением rus_verbs:засидеться{}, // засидеться с приятелем rus_verbs:крепнуть{}, // крепнуть с годами rus_verbs:пировать{}, // пировать с дружиной rus_verbs:щебетать{}, // щебетать с сестричками rus_verbs:маяться{}, // маяться с кашлем rus_verbs:сближать{}, // сближать с центральным светилом rus_verbs:меркнуть{}, // меркнуть с возрастом rus_verbs:заспорить{}, // заспорить с оппонентами rus_verbs:граничить{}, // граничить с Ливаном rus_verbs:перестараться{}, // перестараться со стимуляторами rus_verbs:объединить{}, // объединить с филиалом rus_verbs:свыкнуться{}, // свыкнуться с утратой rus_verbs:посоветоваться{}, // посоветоваться с адвокатами rus_verbs:напутать{}, // напутать с ведомостями rus_verbs:нагрянуть{}, // нагрянуть с обыском rus_verbs:посовещаться{}, // посовещаться с судьей rus_verbs:провернуть{}, // провернуть с друганом rus_verbs:разделяться{}, // разделяться с сотрапезниками rus_verbs:пересечься{}, // пересечься с второй колонной rus_verbs:опережать{}, // опережать с большим запасом rus_verbs:перепутаться{}, // перепутаться с другой линией rus_verbs:соотноситься{}, // соотноситься с затратами rus_verbs:смешивать{}, // смешивать с золой rus_verbs:свидеться{}, // свидеться с тобой rus_verbs:переспать{}, // переспать с графиней rus_verbs:поладить{}, // поладить с соседями rus_verbs:протащить{}, // протащить с собой rus_verbs:разминуться{}, // разминуться с встречным потоком rus_verbs:перемежаться{}, // перемежаться с успехами rus_verbs:рассчитаться{}, // рассчитаться с кредиторами rus_verbs:срастись{}, // срастись с телом rus_verbs:знакомить{}, // знакомить с родителями rus_verbs:поругаться{}, // поругаться с родителями rus_verbs:совладать{}, // совладать с чувствами rus_verbs:обручить{}, // обручить с богатой невестой rus_verbs:сближаться{}, // сближаться с вражеским эсминцем rus_verbs:замутить{}, // замутить с Ксюшей rus_verbs:повозиться{}, // повозиться с настройкой rus_verbs:торговаться{}, // торговаться с продавцами rus_verbs:уединиться{}, // уединиться с девчонкой rus_verbs:переборщить{}, // переборщить с добавкой rus_verbs:ознакомить{}, // ознакомить с пожеланиями rus_verbs:прочесывать{}, // прочесывать с собаками rus_verbs:переписываться{}, // переписываться с корреспондентами rus_verbs:повздорить{}, // повздорить с сержантом rus_verbs:разлучить{}, // разлучить с семьей rus_verbs:соседствовать{}, // соседствовать с цыганами rus_verbs:застукать{}, // застукать с проститутками rus_verbs:напуститься{}, // напуститься с кулаками rus_verbs:сдружиться{}, // сдружиться с ребятами rus_verbs:соперничать{}, // соперничать с параллельным классом rus_verbs:прочесать{}, // прочесать с собаками rus_verbs:кокетничать{}, // кокетничать с гимназистками rus_verbs:мириться{}, // мириться с убытками rus_verbs:оплошать{}, // оплошать с билетами rus_verbs:отождествлять{}, // отождествлять с литературным героем rus_verbs:хитрить{}, // хитрить с зарплатой rus_verbs:провозиться{}, // провозиться с задачкой rus_verbs:коротать{}, // коротать с друзьями rus_verbs:соревноваться{}, // соревноваться с машиной rus_verbs:уживаться{}, // уживаться с местными жителями rus_verbs:отождествляться{}, // отождествляться с литературным героем rus_verbs:сопоставить{}, // сопоставить с эталоном rus_verbs:пьянствовать{}, // пьянствовать с друзьями rus_verbs:залетать{}, // залетать с паленой водкой rus_verbs:гастролировать{}, // гастролировать с новой цирковой программой rus_verbs:запаздывать{}, // запаздывать с кормлением rus_verbs:таскаться{}, // таскаться с сумками rus_verbs:контрастировать{}, // контрастировать с туфлями rus_verbs:сшибиться{}, // сшибиться с форвардом rus_verbs:состязаться{}, // состязаться с лучшей командой rus_verbs:затрудниться{}, // затрудниться с объяснением rus_verbs:объясниться{}, // объясниться с пострадавшими rus_verbs:разводиться{}, // разводиться со сварливой женой rus_verbs:препираться{}, // препираться с адвокатами rus_verbs:сосуществовать{}, // сосуществовать с крупными хищниками rus_verbs:свестись{}, // свестись с нулевым счетом rus_verbs:обговорить{}, // обговорить с директором rus_verbs:обвенчаться{}, // обвенчаться с ведьмой rus_verbs:экспериментировать{}, // экспериментировать с генами rus_verbs:сверять{}, // сверять с таблицей rus_verbs:сверяться{}, // свериться с таблицей rus_verbs:сблизить{}, // сблизить с точкой rus_verbs:гармонировать{}, // гармонировать с обоями rus_verbs:перемешивать{}, // перемешивать с молоком rus_verbs:трепаться{}, // трепаться с сослуживцами rus_verbs:перемигиваться{}, // перемигиваться с соседкой rus_verbs:разоткровенничаться{}, // разоткровенничаться с незнакомцем rus_verbs:распить{}, // распить с собутыльниками rus_verbs:скрестись{}, // скрестись с дикой лошадью rus_verbs:передраться{}, // передраться с дворовыми собаками rus_verbs:умыть{}, // умыть с мылом rus_verbs:грызться{}, // грызться с соседями rus_verbs:переругиваться{}, // переругиваться с соседями rus_verbs:доиграться{}, // доиграться со спичками rus_verbs:заладиться{}, // заладиться с подругой rus_verbs:скрещиваться{}, // скрещиваться с дикими видами rus_verbs:повидаться{}, // повидаться с дедушкой rus_verbs:повоевать{}, // повоевать с орками rus_verbs:сразиться{}, // сразиться с лучшим рыцарем rus_verbs:кипятить{}, // кипятить с отбеливателем rus_verbs:усердствовать{}, // усердствовать с наказанием rus_verbs:схлестнуться{}, // схлестнуться с лучшим боксером rus_verbs:пошептаться{}, // пошептаться с судьями rus_verbs:сравняться{}, // сравняться с лучшими экземплярами rus_verbs:церемониться{}, // церемониться с пьяницами rus_verbs:консультироваться{}, // консультироваться со специалистами rus_verbs:переусердствовать{}, // переусердствовать с наказанием rus_verbs:проноситься{}, // проноситься с собой rus_verbs:перемешать{}, // перемешать с гипсом rus_verbs:темнить{}, // темнить с долгами rus_verbs:сталкивать{}, // сталкивать с черной дырой rus_verbs:увольнять{}, // увольнять с волчьим билетом rus_verbs:заигрывать{}, // заигрывать с совершенно диким животным rus_verbs:сопоставлять{}, // сопоставлять с эталонными образцами rus_verbs:расторгнуть{}, // расторгнуть с нерасторопными поставщиками долгосрочный контракт rus_verbs:созвониться{}, // созвониться с мамой rus_verbs:спеться{}, // спеться с отъявленными хулиганами rus_verbs:интриговать{}, // интриговать с придворными rus_verbs:приобрести{}, // приобрести со скидкой rus_verbs:задержаться{}, // задержаться со сдачей работы rus_verbs:плавать{}, // плавать со спасательным кругом rus_verbs:якшаться{}, // Не якшайся с врагами инфинитив:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги инфинитив:ассоциировать{вид:несоверш}, глагол:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги глагол:ассоциировать{вид:несоверш}, //+прилагательное:ассоциировавший{вид:несоверш}, прилагательное:ассоциировавший{вид:соверш}, прилагательное:ассоциирующий{}, деепричастие:ассоциируя{}, деепричастие:ассоциировав{}, rus_verbs:ассоциироваться{}, // герой книги ассоциируется с реальным персонажем rus_verbs:аттестовывать{}, // Они аттестовывают сотрудников с помощью наборра тестов rus_verbs:аттестовываться{}, // Сотрудники аттестовываются с помощью набора тестов //+инфинитив:аффилировать{вид:соверш}, // эти предприятия были аффилированы с олигархом //+глагол:аффилировать{вид:соверш}, прилагательное:аффилированный{}, rus_verbs:баловаться{}, // мальчик баловался с молотком rus_verbs:балясничать{}, // женщина балясничала с товарками rus_verbs:богатеть{}, // Провинция богатеет от торговли с соседями rus_verbs:бодаться{}, // теленок бодается с деревом rus_verbs:боксировать{}, // Майкл дважды боксировал с ним rus_verbs:брататься{}, // Солдаты братались с бойцами союзников rus_verbs:вальсировать{}, // Мальчик вальсирует с девочкой rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу rus_verbs:происходить{}, // Что происходит с мировой экономикой? rus_verbs:произойти{}, // Что произошло с экономикой? rus_verbs:взаимодействовать{}, // Электроны взаимодействуют с фотонами rus_verbs:вздорить{}, // Эта женщина часто вздорила с соседями rus_verbs:сойтись{}, // Мальчик сошелся с бандой хулиганов rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями rus_verbs:водиться{}, // Няня водится с детьми rus_verbs:воевать{}, // Фермеры воевали с волками rus_verbs:возиться{}, // Няня возится с детьми rus_verbs:ворковать{}, // Голубь воркует с голубкой rus_verbs:воссоединиться{}, // Дети воссоединились с семьей rus_verbs:воссоединяться{}, // Дети воссоединяются с семьей rus_verbs:вошкаться{}, // Не вошкайся с этой ерундой rus_verbs:враждовать{}, // враждовать с соседями rus_verbs:временить{}, // временить с выходом на пенсию rus_verbs:расстаться{}, // я не могу расстаться с тобой rus_verbs:выдирать{}, // выдирать с мясом rus_verbs:выдираться{}, // выдираться с мясом rus_verbs:вытворить{}, // вытворить что-либо с чем-либо rus_verbs:вытворять{}, // вытворять что-либо с чем-либо rus_verbs:сделать{}, // сделать с чем-то rus_verbs:домыть{}, // домыть с мылом rus_verbs:случиться{}, // случиться с кем-то rus_verbs:остаться{}, // остаться с кем-то rus_verbs:случать{}, // случать с породистым кобельком rus_verbs:послать{}, // послать с весточкой rus_verbs:работать{}, // работать с роботами rus_verbs:провести{}, // провести с девчонками время rus_verbs:заговорить{}, // заговорить с незнакомкой rus_verbs:прошептать{}, // прошептать с придыханием rus_verbs:читать{}, // читать с выражением rus_verbs:слушать{}, // слушать с повышенным вниманием rus_verbs:принести{}, // принести с собой rus_verbs:спать{}, // спать с женщинами rus_verbs:закончить{}, // закончить с приготовлениями rus_verbs:помочь{}, // помочь с перестановкой rus_verbs:уехать{}, // уехать с семьей rus_verbs:случаться{}, // случаться с кем-то rus_verbs:кутить{}, // кутить с проститутками rus_verbs:разговаривать{}, // разговаривать с ребенком rus_verbs:погодить{}, // погодить с ликвидацией rus_verbs:считаться{}, // считаться с чужим мнением rus_verbs:носить{}, // носить с собой rus_verbs:хорошеть{}, // хорошеть с каждым днем rus_verbs:приводить{}, // приводить с собой rus_verbs:прыгнуть{}, // прыгнуть с парашютом rus_verbs:петь{}, // петь с чувством rus_verbs:сложить{}, // сложить с результатом rus_verbs:познакомиться{}, // познакомиться с другими студентами rus_verbs:обращаться{}, // обращаться с животными rus_verbs:съесть{}, // съесть с хлебом rus_verbs:ошибаться{}, // ошибаться с дозировкой rus_verbs:столкнуться{}, // столкнуться с медведем rus_verbs:справиться{}, // справиться с нуждой rus_verbs:торопиться{}, // торопиться с ответом rus_verbs:поздравлять{}, // поздравлять с победой rus_verbs:объясняться{}, // объясняться с начальством rus_verbs:пошутить{}, // пошутить с подругой rus_verbs:поздороваться{}, // поздороваться с коллегами rus_verbs:поступать{}, // Как поступать с таким поведением? rus_verbs:определяться{}, // определяться с кандидатами rus_verbs:связаться{}, // связаться с поставщиком rus_verbs:спорить{}, // спорить с собеседником rus_verbs:разобраться{}, // разобраться с делами rus_verbs:ловить{}, // ловить с удочкой rus_verbs:помедлить{}, // Кандидат помедлил с ответом на заданный вопрос rus_verbs:шутить{}, // шутить с диким зверем rus_verbs:разорвать{}, // разорвать с поставщиком контракт rus_verbs:увезти{}, // увезти с собой rus_verbs:унести{}, // унести с собой rus_verbs:сотворить{}, // сотворить с собой что-то нехорошее rus_verbs:складываться{}, // складываться с первым импульсом rus_verbs:соглашаться{}, // соглашаться с предложенным договором //rus_verbs:покончить{}, // покончить с развратом rus_verbs:прихватить{}, // прихватить с собой rus_verbs:похоронить{}, // похоронить с почестями rus_verbs:связывать{}, // связывать с компанией свою судьбу rus_verbs:совпадать{}, // совпадать с предсказанием rus_verbs:танцевать{}, // танцевать с девушками rus_verbs:поделиться{}, // поделиться с выжившими rus_verbs:оставаться{}, // я не хотел оставаться с ним в одной комнате. rus_verbs:беседовать{}, // преподаватель, беседующий со студентами rus_verbs:бороться{}, // человек, борющийся со смертельной болезнью rus_verbs:шептаться{}, // девочка, шепчущаяся с подругой rus_verbs:сплетничать{}, // женщина, сплетничавшая с товарками rus_verbs:поговорить{}, // поговорить с виновниками rus_verbs:сказать{}, // сказать с трудом rus_verbs:произнести{}, // произнести с трудом rus_verbs:говорить{}, // говорить с акцентом rus_verbs:произносить{}, // произносить с трудом rus_verbs:встречаться{}, // кто с Антонио встречался? rus_verbs:посидеть{}, // посидеть с друзьями rus_verbs:расквитаться{}, // расквитаться с обидчиком rus_verbs:поквитаться{}, // поквитаться с обидчиком rus_verbs:ругаться{}, // ругаться с женой rus_verbs:поскандалить{}, // поскандалить с женой rus_verbs:потанцевать{}, // потанцевать с подругой rus_verbs:скандалить{}, // скандалить с соседями rus_verbs:разругаться{}, // разругаться с другом rus_verbs:болтать{}, // болтать с подругами rus_verbs:потрепаться{}, // потрепаться с соседкой rus_verbs:войти{}, // войти с регистрацией rus_verbs:входить{}, // входить с регистрацией rus_verbs:возвращаться{}, // возвращаться с триумфом rus_verbs:опоздать{}, // Он опоздал с подачей сочинения. rus_verbs:молчать{}, // Он молчал с ледяным спокойствием. rus_verbs:сражаться{}, // Он героически сражался с врагами. rus_verbs:выходить{}, // Он всегда выходит с зонтиком. rus_verbs:сличать{}, // сличать перевод с оригиналом rus_verbs:начать{}, // я начал с товарищем спор о религии rus_verbs:согласовать{}, // Маша согласовала с Петей дальнейшие поездки rus_verbs:приходить{}, // Приходите с нею. rus_verbs:жить{}, // кто с тобой жил? rus_verbs:расходиться{}, // Маша расходится с Петей rus_verbs:сцеплять{}, // сцеплять карабин с обвязкой rus_verbs:торговать{}, // мы торгуем с ними нефтью rus_verbs:уединяться{}, // уединяться с подругой в доме rus_verbs:уладить{}, // уладить конфликт с соседями rus_verbs:идти{}, // Я шел туда с тяжёлым сердцем. rus_verbs:разделять{}, // Я разделяю с вами горе и радость. rus_verbs:обратиться{}, // Я обратился к нему с просьбой о помощи. rus_verbs:захватить{}, // Я не захватил с собой денег. прилагательное:знакомый{}, // Я знаком с ними обоими. rus_verbs:вести{}, // Я веду с ней переписку. прилагательное:сопряженный{}, // Это сопряжено с большими трудностями. прилагательное:связанный{причастие}, // Это дело связано с риском. rus_verbs:поехать{}, // Хотите поехать со мной в театр? rus_verbs:проснуться{}, // Утром я проснулся с ясной головой. rus_verbs:лететь{}, // Самолёт летел со скоростью звука. rus_verbs:играть{}, // С огнём играть опасно! rus_verbs:поделать{}, // С ним ничего не поделаешь. rus_verbs:стрястись{}, // С ней стряслось несчастье. rus_verbs:смотреться{}, // Пьеса смотрится с удовольствием. rus_verbs:смотреть{}, // Она смотрела на меня с явным неудовольствием. rus_verbs:разойтись{}, // Она разошлась с мужем. rus_verbs:пристать{}, // Она пристала ко мне с расспросами. rus_verbs:посмотреть{}, // Она посмотрела на меня с удивлением. rus_verbs:поступить{}, // Она плохо поступила с ним. rus_verbs:выйти{}, // Она вышла с усталым и недовольным видом. rus_verbs:взять{}, // Возьмите с собой только самое необходимое. rus_verbs:наплакаться{}, // Наплачется она с ним. rus_verbs:лежать{}, // Он лежит с воспалением лёгких. rus_verbs:дышать{}, // дышащий с трудом rus_verbs:брать{}, // брать с собой rus_verbs:мчаться{}, // Автомобиль мчится с необычайной быстротой. rus_verbs:упасть{}, // Ваза упала со звоном. rus_verbs:вернуться{}, // мы вернулись вчера домой с полным лукошком rus_verbs:сидеть{}, // Она сидит дома с ребенком rus_verbs:встретиться{}, // встречаться с кем-либо ГЛ_ИНФ(придти), прилагательное:пришедший{}, // пришедший с другом ГЛ_ИНФ(постирать), прилагательное:постиранный{}, деепричастие:постирав{}, rus_verbs:мыть{} } fact гл_предл { if context { Гл_С_Твор предлог:с{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_С_Твор предлог:с{} *:*{падеж:твор} } then return true } #endregion ТВОРИТЕЛЬНЫЙ #region РОДИТЕЛЬНЫЙ wordentry_set Гл_С_Род= { rus_verbs:УХОДИТЬ{}, // Но с базы не уходить. rus_verbs:РВАНУТЬ{}, // Водитель прорычал проклятие и рванул машину с места. (РВАНУТЬ) rus_verbs:ОХВАТИТЬ{}, // огонь охватил его со всех сторон (ОХВАТИТЬ) rus_verbs:ЗАМЕТИТЬ{}, // Он понимал, что свет из тайника невозможно заметить с палубы (ЗАМЕТИТЬ/РАЗГЛЯДЕТЬ) rus_verbs:РАЗГЛЯДЕТЬ{}, // rus_verbs:СПЛАНИРОВАТЬ{}, // Птицы размером с орлицу, вероятно, не могли бы подняться в воздух, не спланировав с высокого утеса. (СПЛАНИРОВАТЬ) rus_verbs:УМЕРЕТЬ{}, // Он умрет с голоду. (УМЕРЕТЬ) rus_verbs:ВСПУГНУТЬ{}, // Оба упали с лязгом, вспугнувшим птиц с ближайших деревьев (ВСПУГНУТЬ) rus_verbs:РЕВЕТЬ{}, // Время от времени какой-то ящер ревел с берега или самой реки. (РЕВЕТЬ/ЗАРЕВЕТЬ/ПРОРЕВЕТЬ/ЗАОРАТЬ/ПРООРАТЬ/ОРАТЬ/ПРОКРИЧАТЬ/ЗАКРИЧАТЬ/ВОПИТЬ/ЗАВОПИТЬ) rus_verbs:ЗАРЕВЕТЬ{}, // rus_verbs:ПРОРЕВЕТЬ{}, // rus_verbs:ЗАОРАТЬ{}, // rus_verbs:ПРООРАТЬ{}, // rus_verbs:ОРАТЬ{}, // rus_verbs:ЗАКРИЧАТЬ{}, rus_verbs:ВОПИТЬ{}, // rus_verbs:ЗАВОПИТЬ{}, // rus_verbs:СТАЩИТЬ{}, // Я видела как они стащили его с валуна и увели с собой. (СТАЩИТЬ/СТАСКИВАТЬ) rus_verbs:СТАСКИВАТЬ{}, // rus_verbs:ПРОВЫТЬ{}, // Призрак трубного зова провыл с другой стороны дверей. (ПРОВЫТЬ, ЗАВЫТЬ, ВЫТЬ) rus_verbs:ЗАВЫТЬ{}, // rus_verbs:ВЫТЬ{}, // rus_verbs:СВЕТИТЬ{}, // Полуденное майское солнце ярко светило с голубых небес Аризоны. (СВЕТИТЬ) rus_verbs:ОТСВЕЧИВАТЬ{}, // Солнце отсвечивало с белых лошадей, белых щитов и белых перьев и искрилось на наконечниках пик. (ОТСВЕЧИВАТЬ С, ИСКРИТЬСЯ НА) rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое rus_verbs:собирать{}, // мальчики начали собирать со столов посуду rus_verbs:разглядывать{}, // ты ее со всех сторон разглядывал rus_verbs:СЖИМАТЬ{}, // меня плотно сжимали со всех сторон (СЖИМАТЬ) rus_verbs:СОБРАТЬСЯ{}, // со всего света собрались! (СОБРАТЬСЯ) rus_verbs:ИЗГОНЯТЬ{}, // Вино в пакетах изгоняют с рынка (ИЗГОНЯТЬ) rus_verbs:ВЛЮБИТЬСЯ{}, // влюбился в нее с первого взгляда (ВЛЮБИТЬСЯ) rus_verbs:РАЗДАВАТЬСЯ{}, // теперь крик раздавался со всех сторон (РАЗДАВАТЬСЯ) rus_verbs:ПОСМОТРЕТЬ{}, // Посмотрите на это с моей точки зрения (ПОСМОТРЕТЬ С род) rus_verbs:СХОДИТЬ{}, // принимать участие во всех этих событиях - значит продолжать сходить с ума (СХОДИТЬ С род) rus_verbs:РУХНУТЬ{}, // В Башкирии микроавтобус рухнул с моста (РУХНУТЬ С) rus_verbs:УВОЛИТЬ{}, // рекомендовать уволить их с работы (УВОЛИТЬ С) rus_verbs:КУПИТЬ{}, // еда , купленная с рук (КУПИТЬ С род) rus_verbs:УБРАТЬ{}, // помочь убрать со стола? (УБРАТЬ С) rus_verbs:ТЯНУТЬ{}, // с моря тянуло ветром (ТЯНУТЬ С) rus_verbs:ПРИХОДИТЬ{}, // приходит с работы муж (ПРИХОДИТЬ С) rus_verbs:ПРОПАСТЬ{}, // изображение пропало с экрана (ПРОПАСТЬ С) rus_verbs:ПОТЯНУТЬ{}, // с балкона потянуло холодом (ПОТЯНУТЬ С род) rus_verbs:РАЗДАТЬСЯ{}, // с палубы раздался свист (РАЗДАТЬСЯ С род) rus_verbs:ЗАЙТИ{}, // зашел с другой стороны (ЗАЙТИ С род) rus_verbs:НАЧАТЬ{}, // давай начнем с этого (НАЧАТЬ С род) rus_verbs:УВЕСТИ{}, // дала увести с развалин (УВЕСТИ С род) rus_verbs:ОПУСКАТЬСЯ{}, // с гор опускалась ночь (ОПУСКАТЬСЯ С) rus_verbs:ВСКОЧИТЬ{}, // Тристан вскочил с места (ВСКОЧИТЬ С род) rus_verbs:БРАТЬ{}, // беру с него пример (БРАТЬ С род) rus_verbs:ПРИПОДНЯТЬСЯ{}, // голова приподнялась с плеча (ПРИПОДНЯТЬСЯ С род) rus_verbs:ПОЯВИТЬСЯ{}, // всадники появились с востока (ПОЯВИТЬСЯ С род) rus_verbs:НАЛЕТЕТЬ{}, // с моря налетел ветер (НАЛЕТЕТЬ С род) rus_verbs:ВЗВИТЬСЯ{}, // Натан взвился с места (ВЗВИТЬСЯ С род) rus_verbs:ПОДОБРАТЬ{}, // подобрал с земли копье (ПОДОБРАТЬ С) rus_verbs:ДЕРНУТЬСЯ{}, // Кирилл дернулся с места (ДЕРНУТЬСЯ С род) rus_verbs:ВОЗВРАЩАТЬСЯ{}, // они возвращались с реки (ВОЗВРАЩАТЬСЯ С род) rus_verbs:ПЛЫТЬ{}, // плыли они с запада (ПЛЫТЬ С род) rus_verbs:ЗНАТЬ{}, // одно знали с древности (ЗНАТЬ С) rus_verbs:НАКЛОНИТЬСЯ{}, // всадник наклонился с лошади (НАКЛОНИТЬСЯ С) rus_verbs:НАЧАТЬСЯ{}, // началось все со скуки (НАЧАТЬСЯ С) прилагательное:ИЗВЕСТНЫЙ{}, // Культура его известна со времен глубокой древности (ИЗВЕСТНЫЙ С) rus_verbs:СБИТЬ{}, // Порыв ветра сбил Ваньку с ног (ts СБИТЬ С) rus_verbs:СОБИРАТЬСЯ{}, // они собираются сюда со всей равнины. (СОБИРАТЬСЯ С род) rus_verbs:смыть{}, // Дождь должен смыть с листьев всю пыль. (СМЫТЬ С) rus_verbs:привстать{}, // Мартин привстал со своего стула. (привстать с) rus_verbs:спасть{}, // тяжесть спала с души. (спасть с) rus_verbs:выглядеть{}, // так оно со стороны выглядело. (ВЫГЛЯДЕТЬ С) rus_verbs:повернуть{}, // к вечеру они повернули с нее направо. (ПОВЕРНУТЬ С) rus_verbs:ТЯНУТЬСЯ{}, // со стороны реки ко мне тянулись языки тумана. (ТЯНУТЬСЯ С) rus_verbs:ВОЕВАТЬ{}, // Генерал воевал с юных лет. (ВОЕВАТЬ С чего-то) rus_verbs:БОЛЕТЬ{}, // Голова болит с похмелья. (БОЛЕТЬ С) rus_verbs:приближаться{}, // со стороны острова приближалась лодка. rus_verbs:ПОТЯНУТЬСЯ{}, // со всех сторон к нему потянулись руки. (ПОТЯНУТЬСЯ С) rus_verbs:пойти{}, // низкий гул пошел со стороны долины. (пошел с) rus_verbs:зашевелиться{}, // со всех сторон зашевелились кусты. (зашевелиться с) rus_verbs:МЧАТЬСЯ{}, // со стороны леса мчались всадники. (МЧАТЬСЯ С) rus_verbs:БЕЖАТЬ{}, // люди бежали со всех ног. (БЕЖАТЬ С) rus_verbs:СЛЫШАТЬСЯ{}, // шум слышался со стороны моря. (СЛЫШАТЬСЯ С) rus_verbs:ЛЕТЕТЬ{}, // со стороны деревни летела птица. (ЛЕТЕТЬ С) rus_verbs:ПЕРЕТЬ{}, // враги прут со всех сторон. (ПЕРЕТЬ С) rus_verbs:ПОСЫПАТЬСЯ{}, // вопросы посыпались со всех сторон. (ПОСЫПАТЬСЯ С) rus_verbs:ИДТИ{}, // угроза шла со стороны моря. (ИДТИ С + род.п.) rus_verbs:ПОСЛЫШАТЬСЯ{}, // со стен послышались крики ужаса. (ПОСЛЫШАТЬСЯ С) rus_verbs:ОБРУШИТЬСЯ{}, // звуки обрушились со всех сторон. (ОБРУШИТЬСЯ С) rus_verbs:УДАРИТЬ{}, // голоса ударили со всех сторон. (УДАРИТЬ С) rus_verbs:ПОКАЗАТЬСЯ{}, // со стороны деревни показались земляне. (ПОКАЗАТЬСЯ С) rus_verbs:прыгать{}, // придется прыгать со второго этажа. (прыгать с) rus_verbs:СТОЯТЬ{}, // со всех сторон стоял лес. (СТОЯТЬ С) rus_verbs:доноситься{}, // шум со двора доносился чудовищный. (доноситься с) rus_verbs:мешать{}, // мешать воду с мукой (мешать с) rus_verbs:вестись{}, // Переговоры ведутся с позиции силы. (вестись с) rus_verbs:вставать{}, // Он не встает с кровати. (вставать с) rus_verbs:окружать{}, // зеленые щупальца окружали ее со всех сторон. (окружать с) rus_verbs:причитаться{}, // С вас причитается 50 рублей. rus_verbs:соскользнуть{}, // его острый клюв соскользнул с ее руки. rus_verbs:сократить{}, // Его сократили со службы. rus_verbs:поднять{}, // рука подняла с пола rus_verbs:поднимать{}, rus_verbs:тащить{}, // тем временем другие пришельцы тащили со всех сторон камни. rus_verbs:полететь{}, // Мальчик полетел с лестницы. rus_verbs:литься{}, // вода льется с неба rus_verbs:натечь{}, // натечь с сапог rus_verbs:спрыгивать{}, // спрыгивать с движущегося трамвая rus_verbs:съезжать{}, // съезжать с заявленной темы rus_verbs:покатываться{}, // покатываться со смеху rus_verbs:перескакивать{}, // перескакивать с одного примера на другой rus_verbs:сдирать{}, // сдирать с тела кожу rus_verbs:соскальзывать{}, // соскальзывать с крючка rus_verbs:сметать{}, // сметать с прилавков rus_verbs:кувыркнуться{}, // кувыркнуться со ступеньки rus_verbs:прокаркать{}, // прокаркать с ветки rus_verbs:стряхивать{}, // стряхивать с одежды rus_verbs:сваливаться{}, // сваливаться с лестницы rus_verbs:слизнуть{}, // слизнуть с лица rus_verbs:доставляться{}, // доставляться с фермы rus_verbs:обступать{}, // обступать с двух сторон rus_verbs:повскакивать{}, // повскакивать с мест rus_verbs:обозревать{}, // обозревать с вершины rus_verbs:слинять{}, // слинять с урока rus_verbs:смывать{}, // смывать с лица rus_verbs:спихнуть{}, // спихнуть со стола rus_verbs:обозреть{}, // обозреть с вершины rus_verbs:накупить{}, // накупить с рук rus_verbs:схлынуть{}, // схлынуть с берега rus_verbs:спикировать{}, // спикировать с километровой высоты rus_verbs:уползти{}, // уползти с поля боя rus_verbs:сбиваться{}, // сбиваться с пути rus_verbs:отлучиться{}, // отлучиться с поста rus_verbs:сигануть{}, // сигануть с крыши rus_verbs:сместить{}, // сместить с поста rus_verbs:списать{}, // списать с оригинального устройства инфинитив:слетать{ вид:несоверш }, глагол:слетать{ вид:несоверш }, // слетать с трассы деепричастие:слетая{}, rus_verbs:напиваться{}, // напиваться с горя rus_verbs:свесить{}, // свесить с крыши rus_verbs:заполучить{}, // заполучить со склада rus_verbs:спадать{}, // спадать с глаз rus_verbs:стартовать{}, // стартовать с мыса rus_verbs:спереть{}, // спереть со склада rus_verbs:согнать{}, // согнать с живота rus_verbs:скатываться{}, // скатываться со стога rus_verbs:сняться{}, // сняться с выборов rus_verbs:слезать{}, // слезать со стола rus_verbs:деваться{}, // деваться с подводной лодки rus_verbs:огласить{}, // огласить с трибуны rus_verbs:красть{}, // красть со склада rus_verbs:расширить{}, // расширить с торца rus_verbs:угадывать{}, // угадывать с полуслова rus_verbs:оскорбить{}, // оскорбить со сцены rus_verbs:срывать{}, // срывать с головы rus_verbs:сшибить{}, // сшибить с коня rus_verbs:сбивать{}, // сбивать с одежды rus_verbs:содрать{}, // содрать с посетителей rus_verbs:столкнуть{}, // столкнуть с горы rus_verbs:отряхнуть{}, // отряхнуть с одежды rus_verbs:сбрасывать{}, // сбрасывать с борта rus_verbs:расстреливать{}, // расстреливать с борта вертолета rus_verbs:придти{}, // мать скоро придет с работы rus_verbs:съехать{}, // Миша съехал с горки rus_verbs:свисать{}, // свисать с веток rus_verbs:стянуть{}, // стянуть с кровати rus_verbs:скинуть{}, // скинуть снег с плеча rus_verbs:загреметь{}, // загреметь со стула rus_verbs:сыпаться{}, // сыпаться с неба rus_verbs:стряхнуть{}, // стряхнуть с головы rus_verbs:сползти{}, // сползти со стула rus_verbs:стереть{}, // стереть с экрана rus_verbs:прогнать{}, // прогнать с фермы rus_verbs:смахнуть{}, // смахнуть со стола rus_verbs:спускать{}, // спускать с поводка rus_verbs:деться{}, // деться с подводной лодки rus_verbs:сдернуть{}, // сдернуть с себя rus_verbs:сдвинуться{}, // сдвинуться с места rus_verbs:слететь{}, // слететь с катушек rus_verbs:обступить{}, // обступить со всех сторон rus_verbs:снести{}, // снести с плеч инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, // сбегать с уроков деепричастие:сбегая{}, прилагательное:сбегающий{}, // прилагательное:сбегавший{ вид:несоверш }, rus_verbs:запить{}, // запить с горя rus_verbs:рубануть{}, // рубануть с плеча rus_verbs:чертыхнуться{}, // чертыхнуться с досады rus_verbs:срываться{}, // срываться с цепи rus_verbs:смыться{}, // смыться с уроков rus_verbs:похитить{}, // похитить со склада rus_verbs:смести{}, // смести со своего пути rus_verbs:отгружать{}, // отгружать со склада rus_verbs:отгрузить{}, // отгрузить со склада rus_verbs:бросаться{}, // Дети бросались в воду с моста rus_verbs:броситься{}, // самоубийца бросился с моста в воду rus_verbs:взимать{}, // Билетер взимает плату с каждого посетителя rus_verbs:взиматься{}, // Плата взимается с любого посетителя rus_verbs:взыскать{}, // Приставы взыскали долг с бедолаги rus_verbs:взыскивать{}, // Приставы взыскивают с бедолаги все долги rus_verbs:взыскиваться{}, // Долги взыскиваются с алиментщиков rus_verbs:вспархивать{}, // вспархивать с цветка rus_verbs:вспорхнуть{}, // вспорхнуть с ветки rus_verbs:выбросить{}, // выбросить что-то с балкона rus_verbs:выводить{}, // выводить с одежды пятна rus_verbs:снять{}, // снять с головы rus_verbs:начинать{}, // начинать с эскиза rus_verbs:двинуться{}, // двинуться с места rus_verbs:начинаться{}, // начинаться с гардероба rus_verbs:стечь{}, // стечь с крыши rus_verbs:слезть{}, // слезть с кучи rus_verbs:спуститься{}, // спуститься с крыши rus_verbs:сойти{}, // сойти с пьедестала rus_verbs:свернуть{}, // свернуть с пути rus_verbs:сорвать{}, // сорвать с цепи rus_verbs:сорваться{}, // сорваться с поводка rus_verbs:тронуться{}, // тронуться с места rus_verbs:угадать{}, // угадать с первой попытки rus_verbs:спустить{}, // спустить с лестницы rus_verbs:соскочить{}, // соскочить с крючка rus_verbs:сдвинуть{}, // сдвинуть с места rus_verbs:подниматься{}, // туман, поднимающийся с болота rus_verbs:подняться{}, // туман, поднявшийся с болота rus_verbs:валить{}, // Резкий порывистый ветер валит прохожих с ног. rus_verbs:свалить{}, // Резкий порывистый ветер свалит тебя с ног. rus_verbs:донестись{}, // С улицы донесся шум дождя. rus_verbs:опасть{}, // Опавшие с дерева листья. rus_verbs:махнуть{}, // Он махнул с берега в воду. rus_verbs:исчезнуть{}, // исчезнуть с экрана rus_verbs:свалиться{}, // свалиться со сцены rus_verbs:упасть{}, // упасть с дерева rus_verbs:вернуться{}, // Он ещё не вернулся с работы. rus_verbs:сдувать{}, // сдувать пух с одуванчиков rus_verbs:свергать{}, // свергать царя с трона rus_verbs:сбиться{}, // сбиться с пути rus_verbs:стирать{}, // стирать тряпкой надпись с доски rus_verbs:убирать{}, // убирать мусор c пола rus_verbs:удалять{}, // удалять игрока с поля rus_verbs:окружить{}, // Япония окружена со всех сторон морями. rus_verbs:снимать{}, // Я снимаю с себя всякую ответственность за его поведение. глагол:писаться{ aux stress="пис^аться" }, // Собственные имена пишутся с большой буквы. прилагательное:спокойный{}, // С этой стороны я спокоен. rus_verbs:спросить{}, // С тебя за всё спросят. rus_verbs:течь{}, // С него течёт пот. rus_verbs:дуть{}, // С моря дует ветер. rus_verbs:капать{}, // С его лица капали крупные капли пота. rus_verbs:опустить{}, // Она опустила ребёнка с рук на пол. rus_verbs:спрыгнуть{}, // Она легко спрыгнула с коня. rus_verbs:встать{}, // Все встали со стульев. rus_verbs:сбросить{}, // Войдя в комнату, он сбросил с себя пальто. rus_verbs:взять{}, // Возьми книгу с полки. rus_verbs:спускаться{}, // Мы спускались с горы. rus_verbs:уйти{}, // Он нашёл себе заместителя и ушёл со службы. rus_verbs:порхать{}, // Бабочка порхает с цветка на цветок. rus_verbs:отправляться{}, // Ваш поезд отправляется со второй платформы. rus_verbs:двигаться{}, // Он не двигался с места. rus_verbs:отходить{}, // мой поезд отходит с первого пути rus_verbs:попасть{}, // Майкл попал в кольцо с десятиметровой дистанции rus_verbs:падать{}, // снег падает с ветвей rus_verbs:скрыться{} // Ее водитель, бросив машину, скрылся с места происшествия. } fact гл_предл { if context { Гл_С_Род предлог:с{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_С_Род предлог:с{} *:*{падеж:род} } then return true } fact гл_предл { if context { Гл_С_Род предлог:с{} *:*{падеж:парт} } then return true } #endregion РОДИТЕЛЬНЫЙ fact гл_предл { if context { * предлог:с{} *:*{ падеж:твор } } then return false,-3 } fact гл_предл { if context { * предлог:с{} *:*{ падеж:род } } then return false,-4 } fact гл_предл { if context { * предлог:с{} * } then return false,-5 } #endregion Предлог_С /* #region Предлог_ПОД // -------------- ПРЕДЛОГ 'ПОД' ----------------------- fact гл_предл { if context { * предлог:под{} @regex("[a-z]+[0-9]*") } then return true } // ПОД+вин.п. не может присоединяться к существительным, поэтому // он присоединяется к любым глаголам. fact гл_предл { if context { * предлог:под{} *:*{ падеж:вин } } then return true } wordentry_set Гл_ПОД_твор= { rus_verbs:извиваться{}, // извивалась под его длинными усами rus_verbs:РАСПРОСТРАНЯТЬСЯ{}, // Под густым ковром травы и плотным сплетением корней (РАСПРОСТРАНЯТЬСЯ) rus_verbs:БРОСИТЬ{}, // чтобы ты его под деревом бросил? (БРОСИТЬ) rus_verbs:БИТЬСЯ{}, // под моей щекой сильно билось его сердце (БИТЬСЯ) rus_verbs:ОПУСТИТЬСЯ{}, // глаза его опустились под ее желтым взглядом (ОПУСТИТЬСЯ) rus_verbs:ВЗДЫМАТЬСЯ{}, // его грудь судорожно вздымалась под ее рукой (ВЗДЫМАТЬСЯ) rus_verbs:ПРОМЧАТЬСЯ{}, // Она промчалась под ними и исчезла за изгибом горы. (ПРОМЧАТЬСЯ) rus_verbs:всплыть{}, // Наконец он всплыл под нависавшей кормой, так и не отыскав того, что хотел. (всплыть) rus_verbs:КОНЧАТЬСЯ{}, // Он почти вертикально уходит в реку и кончается глубоко под водой. (КОНЧАТЬСЯ) rus_verbs:ПОЛЗТИ{}, // Там они ползли под спутанным терновником и сквозь переплетавшиеся кусты (ПОЛЗТИ) rus_verbs:ПРОХОДИТЬ{}, // Вольф проходил под гигантскими ветвями деревьев и мхов, свисавших с ветвей зелеными водопадами. (ПРОХОДИТЬ, ПРОПОЛЗТИ, ПРОПОЛЗАТЬ) rus_verbs:ПРОПОЛЗТИ{}, // rus_verbs:ПРОПОЛЗАТЬ{}, // rus_verbs:ИМЕТЬ{}, // Эти предположения не имеют под собой никакой почвы (ИМЕТЬ) rus_verbs:НОСИТЬ{}, // она носит под сердцем ребенка (НОСИТЬ) rus_verbs:ПАСТЬ{}, // Рим пал под натиском варваров (ПАСТЬ) rus_verbs:УТОНУТЬ{}, // Выступавшие старческие вены снова утонули под гладкой твердой плотью. (УТОНУТЬ) rus_verbs:ВАЛЯТЬСЯ{}, // Под его кривыми серыми ветвями и пестрыми коричнево-зелеными листьями валялись пустые ореховые скорлупки и сердцевины плодов. (ВАЛЯТЬСЯ) rus_verbs:вздрогнуть{}, // она вздрогнула под его взглядом rus_verbs:иметься{}, // у каждого под рукой имелся арбалет rus_verbs:ЖДАТЬ{}, // Сашка уже ждал под дождем (ЖДАТЬ) rus_verbs:НОЧЕВАТЬ{}, // мне приходилось ночевать под открытым небом (НОЧЕВАТЬ) rus_verbs:УЗНАТЬ{}, // вы должны узнать меня под этим именем (УЗНАТЬ) rus_verbs:ЗАДЕРЖИВАТЬСЯ{}, // мне нельзя задерживаться под землей! (ЗАДЕРЖИВАТЬСЯ) rus_verbs:ПОГИБНУТЬ{}, // под их копытами погибли целые армии! (ПОГИБНУТЬ) rus_verbs:РАЗДАВАТЬСЯ{}, // под ногами у меня раздавался сухой хруст (РАЗДАВАТЬСЯ) rus_verbs:КРУЖИТЬСЯ{}, // поверхность планеты кружилась у него под ногами (КРУЖИТЬСЯ) rus_verbs:ВИСЕТЬ{}, // под глазами у него висели тяжелые складки кожи (ВИСЕТЬ) rus_verbs:содрогнуться{}, // содрогнулся под ногами каменный пол (СОДРОГНУТЬСЯ) rus_verbs:СОБИРАТЬСЯ{}, // темнота уже собиралась под деревьями (СОБИРАТЬСЯ) rus_verbs:УПАСТЬ{}, // толстяк упал под градом ударов (УПАСТЬ) rus_verbs:ДВИНУТЬСЯ{}, // лодка двинулась под водой (ДВИНУТЬСЯ) rus_verbs:ЦАРИТЬ{}, // под его крышей царила холодная зима (ЦАРИТЬ) rus_verbs:ПРОВАЛИТЬСЯ{}, // под копытами его лошади провалился мост (ПРОВАЛИТЬСЯ ПОД твор) rus_verbs:ЗАДРОЖАТЬ{}, // земля задрожала под ногами (ЗАДРОЖАТЬ) rus_verbs:НАХМУРИТЬСЯ{}, // государь нахмурился под маской (НАХМУРИТЬСЯ) rus_verbs:РАБОТАТЬ{}, // работать под угрозой нельзя (РАБОТАТЬ) rus_verbs:ШЕВЕЛЬНУТЬСЯ{}, // под ногой шевельнулся камень (ШЕВЕЛЬНУТЬСЯ) rus_verbs:ВИДЕТЬ{}, // видел тебя под камнем. (ВИДЕТЬ) rus_verbs:ОСТАТЬСЯ{}, // второе осталось под водой (ОСТАТЬСЯ) rus_verbs:КИПЕТЬ{}, // вода кипела под копытами (КИПЕТЬ) rus_verbs:СИДЕТЬ{}, // может сидит под деревом (СИДЕТЬ) rus_verbs:МЕЛЬКНУТЬ{}, // под нами мелькнуло море (МЕЛЬКНУТЬ) rus_verbs:ПОСЛЫШАТЬСЯ{}, // под окном послышался шум (ПОСЛЫШАТЬСЯ) rus_verbs:ТЯНУТЬСЯ{}, // под нами тянулись облака (ТЯНУТЬСЯ) rus_verbs:ДРОЖАТЬ{}, // земля дрожала под ним (ДРОЖАТЬ) rus_verbs:ПРИЙТИСЬ{}, // хуже пришлось под землей (ПРИЙТИСЬ) rus_verbs:ГОРЕТЬ{}, // лампа горела под потолком (ГОРЕТЬ) rus_verbs:ПОЛОЖИТЬ{}, // положил под деревом плащ (ПОЛОЖИТЬ) rus_verbs:ЗАГОРЕТЬСЯ{}, // под деревьями загорелся костер (ЗАГОРЕТЬСЯ) rus_verbs:ПРОНОСИТЬСЯ{}, // под нами проносились крыши (ПРОНОСИТЬСЯ) rus_verbs:ПОТЯНУТЬСЯ{}, // под кораблем потянулись горы (ПОТЯНУТЬСЯ) rus_verbs:БЕЖАТЬ{}, // беги под серой стеной ночи (БЕЖАТЬ) rus_verbs:РАЗДАТЬСЯ{}, // под окном раздалось тяжелое дыхание (РАЗДАТЬСЯ) rus_verbs:ВСПЫХНУТЬ{}, // под потолком вспыхнула яркая лампа (ВСПЫХНУТЬ) rus_verbs:СМОТРЕТЬ{}, // просто смотрите под другим углом (СМОТРЕТЬ ПОД) rus_verbs:ДУТЬ{}, // теперь под деревьями дул ветерок (ДУТЬ) rus_verbs:СКРЫТЬСЯ{}, // оно быстро скрылось под водой (СКРЫТЬСЯ ПОД) rus_verbs:ЩЕЛКНУТЬ{}, // далеко под ними щелкнул выстрел (ЩЕЛКНУТЬ) rus_verbs:ТРЕЩАТЬ{}, // осколки стекла трещали под ногами (ТРЕЩАТЬ) rus_verbs:РАСПОЛАГАТЬСЯ{}, // под ними располагались разноцветные скамьи (РАСПОЛАГАТЬСЯ) rus_verbs:ВЫСТУПИТЬ{}, // под ногтями выступили капельки крови (ВЫСТУПИТЬ) rus_verbs:НАСТУПИТЬ{}, // под куполом базы наступила тишина (НАСТУПИТЬ) rus_verbs:ОСТАНОВИТЬСЯ{}, // повозка остановилась под самым окном (ОСТАНОВИТЬСЯ) rus_verbs:РАСТАЯТЬ{}, // магазин растаял под ночным дождем (РАСТАЯТЬ) rus_verbs:ДВИГАТЬСЯ{}, // под водой двигалось нечто огромное (ДВИГАТЬСЯ) rus_verbs:БЫТЬ{}, // под снегом могут быть трещины (БЫТЬ) rus_verbs:ЗИЯТЬ{}, // под ней зияла ужасная рана (ЗИЯТЬ) rus_verbs:ЗАЗВОНИТЬ{}, // под рукой водителя зазвонил телефон (ЗАЗВОНИТЬ) rus_verbs:ПОКАЗАТЬСЯ{}, // внезапно под ними показалась вода (ПОКАЗАТЬСЯ) rus_verbs:ЗАМЕРЕТЬ{}, // эхо замерло под высоким потолком (ЗАМЕРЕТЬ) rus_verbs:ПОЙТИ{}, // затем под кораблем пошла пустыня (ПОЙТИ) rus_verbs:ДЕЙСТВОВАТЬ{}, // боги всегда действуют под маской (ДЕЙСТВОВАТЬ) rus_verbs:БЛЕСТЕТЬ{}, // мокрый мех блестел под луной (БЛЕСТЕТЬ) rus_verbs:ЛЕТЕТЬ{}, // под ним летела серая земля (ЛЕТЕТЬ) rus_verbs:СОГНУТЬСЯ{}, // содрогнулся под ногами каменный пол (СОГНУТЬСЯ) rus_verbs:КИВНУТЬ{}, // четвертый слегка кивнул под капюшоном (КИВНУТЬ) rus_verbs:УМЕРЕТЬ{}, // колдун умер под грудой каменных глыб (УМЕРЕТЬ) rus_verbs:ОКАЗЫВАТЬСЯ{}, // внезапно под ногами оказывается знакомая тропинка (ОКАЗЫВАТЬСЯ) rus_verbs:ИСЧЕЗАТЬ{}, // серая лента дороги исчезала под воротами (ИСЧЕЗАТЬ) rus_verbs:СВЕРКНУТЬ{}, // голубые глаза сверкнули под густыми бровями (СВЕРКНУТЬ) rus_verbs:СИЯТЬ{}, // под ним сияла белая пелена облаков (СИЯТЬ) rus_verbs:ПРОНЕСТИСЬ{}, // тихий смех пронесся под куполом зала (ПРОНЕСТИСЬ) rus_verbs:СКОЛЬЗИТЬ{}, // обломки судна медленно скользили под ними (СКОЛЬЗИТЬ) rus_verbs:ВЗДУТЬСЯ{}, // под серой кожей вздулись шары мускулов (ВЗДУТЬСЯ) rus_verbs:ПРОЙТИ{}, // обломок отлично пройдет под колесами слева (ПРОЙТИ) rus_verbs:РАЗВЕВАТЬСЯ{}, // светлые волосы развевались под дыханием ветра (РАЗВЕВАТЬСЯ) rus_verbs:СВЕРКАТЬ{}, // глаза огнем сверкали под темными бровями (СВЕРКАТЬ) rus_verbs:КАЗАТЬСЯ{}, // деревянный док казался очень твердым под моими ногами (КАЗАТЬСЯ) rus_verbs:ПОСТАВИТЬ{}, // четвертый маг торопливо поставил под зеркалом широкую чашу (ПОСТАВИТЬ) rus_verbs:ОСТАВАТЬСЯ{}, // запасы остаются под давлением (ОСТАВАТЬСЯ ПОД) rus_verbs:ПЕТЬ{}, // просто мы под землей любим петь. (ПЕТЬ ПОД) rus_verbs:ПОЯВИТЬСЯ{}, // под их крыльями внезапно появился дым. (ПОЯВИТЬСЯ ПОД) rus_verbs:ОКАЗАТЬСЯ{}, // мы снова оказались под солнцем. (ОКАЗАТЬСЯ ПОД) rus_verbs:ПОДХОДИТЬ{}, // мы подходили под другим углом? (ПОДХОДИТЬ ПОД) rus_verbs:СКРЫВАТЬСЯ{}, // кто под ней скрывается? (СКРЫВАТЬСЯ ПОД) rus_verbs:ХЛЮПАТЬ{}, // под ногами Аллы хлюпала грязь (ХЛЮПАТЬ ПОД) rus_verbs:ШАГАТЬ{}, // их отряд весело шагал под дождем этой музыки. (ШАГАТЬ ПОД) rus_verbs:ТЕЧЬ{}, // под ее поверхностью медленно текла ярость. (ТЕЧЬ ПОД твор) rus_verbs:ОЧУТИТЬСЯ{}, // мы очутились под стенами замка. (ОЧУТИТЬСЯ ПОД) rus_verbs:ПОБЛЕСКИВАТЬ{}, // их латы поблескивали под солнцем. (ПОБЛЕСКИВАТЬ ПОД) rus_verbs:ДРАТЬСЯ{}, // под столами дрались за кости псы. (ДРАТЬСЯ ПОД) rus_verbs:КАЧНУТЬСЯ{}, // палуба качнулась у нас под ногами. (КАЧНУЛАСЬ ПОД) rus_verbs:ПРИСЕСТЬ{}, // конь даже присел под тяжелым телом. (ПРИСЕСТЬ ПОД) rus_verbs:ЖИТЬ{}, // они живут под землей. (ЖИТЬ ПОД) rus_verbs:ОБНАРУЖИТЬ{}, // вы можете обнаружить ее под водой? (ОБНАРУЖИТЬ ПОД) rus_verbs:ПЛЫТЬ{}, // Орёл плывёт под облаками. (ПЛЫТЬ ПОД) rus_verbs:ИСЧЕЗНУТЬ{}, // потом они исчезли под водой. (ИСЧЕЗНУТЬ ПОД) rus_verbs:держать{}, // оружие все держали под рукой. (держать ПОД) rus_verbs:ВСТРЕТИТЬСЯ{}, // они встретились под водой. (ВСТРЕТИТЬСЯ ПОД) rus_verbs:уснуть{}, // Миша уснет под одеялом rus_verbs:пошевелиться{}, // пошевелиться под одеялом rus_verbs:задохнуться{}, // задохнуться под слоем снега rus_verbs:потечь{}, // потечь под избыточным давлением rus_verbs:уцелеть{}, // уцелеть под завалами rus_verbs:мерцать{}, // мерцать под лучами софитов rus_verbs:поискать{}, // поискать под кроватью rus_verbs:гудеть{}, // гудеть под нагрузкой rus_verbs:посидеть{}, // посидеть под навесом rus_verbs:укрыться{}, // укрыться под навесом rus_verbs:утихнуть{}, // утихнуть под одеялом rus_verbs:заскрипеть{}, // заскрипеть под тяжестью rus_verbs:шелохнуться{}, // шелохнуться под одеялом инфинитив:срезать{ вид:несоверш }, глагол:срезать{ вид:несоверш }, // срезать под корень деепричастие:срезав{}, прилагательное:срезающий{ вид:несоверш }, инфинитив:срезать{ вид:соверш }, глагол:срезать{ вид:соверш }, деепричастие:срезая{}, прилагательное:срезавший{ вид:соверш }, rus_verbs:пониматься{}, // пониматься под успехом rus_verbs:подразумеваться{}, // подразумеваться под правильным решением rus_verbs:промокнуть{}, // промокнуть под проливным дождем rus_verbs:засосать{}, // засосать под ложечкой rus_verbs:подписаться{}, // подписаться под воззванием rus_verbs:укрываться{}, // укрываться под навесом rus_verbs:запыхтеть{}, // запыхтеть под одеялом rus_verbs:мокнуть{}, // мокнуть под лождем rus_verbs:сгибаться{}, // сгибаться под тяжестью снега rus_verbs:намокнуть{}, // намокнуть под дождем rus_verbs:подписываться{}, // подписываться под обращением rus_verbs:тарахтеть{}, // тарахтеть под окнами инфинитив:находиться{вид:несоверш}, глагол:находиться{вид:несоверш}, // Она уже несколько лет находится под наблюдением врача. деепричастие:находясь{}, прилагательное:находившийся{вид:несоверш}, прилагательное:находящийся{}, rus_verbs:лежать{}, // лежать под капельницей rus_verbs:вымокать{}, // вымокать под дождём rus_verbs:вымокнуть{}, // вымокнуть под дождём rus_verbs:проворчать{}, // проворчать под нос rus_verbs:хмыкнуть{}, // хмыкнуть под нос rus_verbs:отыскать{}, // отыскать под кроватью rus_verbs:дрогнуть{}, // дрогнуть под ударами rus_verbs:проявляться{}, // проявляться под нагрузкой rus_verbs:сдержать{}, // сдержать под контролем rus_verbs:ложиться{}, // ложиться под клиента rus_verbs:таять{}, // таять под весенним солнцем rus_verbs:покатиться{}, // покатиться под откос rus_verbs:лечь{}, // он лег под навесом rus_verbs:идти{}, // идти под дождем прилагательное:известный{}, // Он известен под этим именем. rus_verbs:стоять{}, // Ящик стоит под столом. rus_verbs:отступить{}, // Враг отступил под ударами наших войск. rus_verbs:царапаться{}, // Мышь царапается под полом. rus_verbs:спать{}, // заяц спокойно спал у себя под кустом rus_verbs:загорать{}, // мы загораем под солнцем ГЛ_ИНФ(мыть), // мыть руки под струёй воды ГЛ_ИНФ(закопать), ГЛ_ИНФ(спрятать), ГЛ_ИНФ(прятать), ГЛ_ИНФ(перепрятать) } fact гл_предл { if context { Гл_ПОД_твор предлог:под{} *:*{ падеж:твор } } then return true } // для глаголов вне списка - запрещаем. fact гл_предл { if context { * предлог:под{} *:*{ падеж:твор } } then return false,-10 } fact гл_предл { if context { * предлог:под{} *:*{} } then return false,-11 } #endregion Предлог_ПОД */ #region Предлог_ОБ // -------------- ПРЕДЛОГ 'ОБ' ----------------------- wordentry_set Гл_ОБ_предл= { rus_verbs:СВИДЕТЕЛЬСТВОВАТЬ{}, // Об их присутствии свидетельствовало лишь тусклое пурпурное пятно, проступавшее на камне. (СВИДЕТЕЛЬСТВОВАТЬ) rus_verbs:ЗАДУМАТЬСЯ{}, // Промышленные гиганты задумались об экологии (ЗАДУМАТЬСЯ) rus_verbs:СПРОСИТЬ{}, // Он спросил нескольких из пляжников об их кажущейся всеобщей юности. (СПРОСИТЬ) rus_verbs:спрашивать{}, // как ты можешь еще спрашивать у меня об этом? rus_verbs:забывать{}, // Мы не можем забывать об их участи. rus_verbs:ГАДАТЬ{}, // теперь об этом можно лишь гадать (ГАДАТЬ) rus_verbs:ПОВЕДАТЬ{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам (ПОВЕДАТЬ ОБ) rus_verbs:СООБЩИТЬ{}, // Иран сообщил МАГАТЭ об ускорении обогащения урана (СООБЩИТЬ) rus_verbs:ЗАЯВИТЬ{}, // Об их успешном окончании заявил генеральный директор (ЗАЯВИТЬ ОБ) rus_verbs:слышать{}, // даже они слышали об этом человеке. (СЛЫШАТЬ ОБ) rus_verbs:ДОЛОЖИТЬ{}, // вернувшиеся разведчики доложили об увиденном (ДОЛОЖИТЬ ОБ) rus_verbs:ПОГОВОРИТЬ{}, // давай поговорим об этом. (ПОГОВОРИТЬ ОБ) rus_verbs:ДОГАДАТЬСЯ{}, // об остальном нетрудно догадаться. (ДОГАДАТЬСЯ ОБ) rus_verbs:ПОЗАБОТИТЬСЯ{}, // обещал обо всем позаботиться. (ПОЗАБОТИТЬСЯ ОБ) rus_verbs:ПОЗАБЫТЬ{}, // Шура позабыл обо всем. (ПОЗАБЫТЬ ОБ) rus_verbs:вспоминать{}, // Впоследствии он не раз вспоминал об этом приключении. (вспоминать об) rus_verbs:сообщать{}, // Газета сообщает об открытии сессии парламента. (сообщать об) rus_verbs:просить{}, // мы просили об отсрочке платежей (просить ОБ) rus_verbs:ПЕТЬ{}, // эта же девушка пела обо всем совершенно открыто. (ПЕТЬ ОБ) rus_verbs:сказать{}, // ты скажешь об этом капитану? (сказать ОБ) rus_verbs:знать{}, // бы хотелось знать как можно больше об этом районе. rus_verbs:кричать{}, // Все газеты кричат об этом событии. rus_verbs:советоваться{}, // Она обо всём советуется с матерью. rus_verbs:говориться{}, // об остальном говорилось легко. rus_verbs:подумать{}, // нужно крепко обо всем подумать. rus_verbs:напомнить{}, // черный дым напомнил об опасности. rus_verbs:забыть{}, // забудь об этой роскоши. rus_verbs:думать{}, // приходится обо всем думать самой. rus_verbs:отрапортовать{}, // отрапортовать об успехах rus_verbs:информировать{}, // информировать об изменениях rus_verbs:оповестить{}, // оповестить об отказе rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:заговорить{}, // заговорить об оплате rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой. rus_verbs:попросить{}, // попросить об услуге rus_verbs:объявить{}, // объявить об отставке rus_verbs:предупредить{}, // предупредить об аварии rus_verbs:предупреждать{}, // предупреждать об опасности rus_verbs:твердить{}, // твердить об обязанностях rus_verbs:заявлять{}, // заявлять об экспериментальном подтверждении rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц. rus_verbs:читать{}, // он читал об этом в журнале rus_verbs:прочитать{}, // он читал об этом в учебнике rus_verbs:узнать{}, // он узнал об этом из фильмов rus_verbs:рассказать{}, // рассказать об экзаменах rus_verbs:рассказывать{}, rus_verbs:договориться{}, // договориться об оплате rus_verbs:договариваться{}, // договариваться об обмене rus_verbs:болтать{}, // Не болтай об этом! rus_verbs:проболтаться{}, // Не проболтайся об этом! rus_verbs:заботиться{}, // кто заботится об урегулировании rus_verbs:беспокоиться{}, // вы беспокоитесь об обороне rus_verbs:помнить{}, // всем советую об этом помнить rus_verbs:мечтать{} // Мечтать об успехе } fact гл_предл { if context { Гл_ОБ_предл предлог:об{} *:*{ падеж:предл } } then return true } fact гл_предл { if context { * предлог:о{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { * предлог:об{} @regex("[a-z]+[0-9]*") } then return true } // остальные глаголы не могут связываться fact гл_предл { if context { * предлог:об{} *:*{ падеж:предл } } then return false, -4 } wordentry_set Гл_ОБ_вин= { rus_verbs:СЛОМАТЬ{}, // потом об колено сломал (СЛОМАТЬ) rus_verbs:разбить{}, // ты разбил щеку об угол ящика. (РАЗБИТЬ ОБ) rus_verbs:опереться{}, // Он опёрся об стену. rus_verbs:опираться{}, rus_verbs:постучать{}, // постучал лбом об пол. rus_verbs:удариться{}, // бутылка глухо ударилась об землю. rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:царапаться{} // Днище лодки царапалось обо что-то. } fact гл_предл { if context { Гл_ОБ_вин предлог:об{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { * предлог:об{} *:*{ падеж:вин } } then return false,-4 } fact гл_предл { if context { * предлог:об{} *:*{} } then return false,-5 } #endregion Предлог_ОБ #region Предлог_О // ------------------- С ПРЕДЛОГОМ 'О' ---------------------- wordentry_set Гл_О_Вин={ rus_verbs:шмякнуть{}, // Ей хотелось шмякнуть ими о стену. rus_verbs:болтать{}, // Болтали чаще всего о пустяках. rus_verbs:шваркнуть{}, // Она шваркнула трубкой о рычаг. rus_verbs:опираться{}, // Мать приподнялась, с трудом опираясь о стол. rus_verbs:бахнуться{}, // Бахнуться головой о стол. rus_verbs:ВЫТЕРЕТЬ{}, // Вытащи нож и вытри его о траву. (ВЫТЕРЕТЬ/ВЫТИРАТЬ) rus_verbs:ВЫТИРАТЬ{}, // rus_verbs:РАЗБИТЬСЯ{}, // Прибой накатился и с шумом разбился о белый песок. (РАЗБИТЬСЯ) rus_verbs:СТУКНУТЬ{}, // Сердце его глухо стукнуло о грудную кость (СТУКНУТЬ) rus_verbs:ЛЯЗГНУТЬ{}, // Он кинулся наземь, покатился, и копье лязгнуло о стену. (ЛЯЗГНУТЬ/ЛЯЗГАТЬ) rus_verbs:ЛЯЗГАТЬ{}, // rus_verbs:звенеть{}, // стрелы уже звенели о прутья клетки rus_verbs:ЩЕЛКНУТЬ{}, // камень щелкнул о скалу (ЩЕЛКНУТЬ) rus_verbs:БИТЬ{}, // волна бьет о берег (БИТЬ) rus_verbs:ЗАЗВЕНЕТЬ{}, // зазвенели мечи о щиты (ЗАЗВЕНЕТЬ) rus_verbs:колотиться{}, // сердце его колотилось о ребра rus_verbs:стучать{}, // глухо стучали о щиты рукояти мечей. rus_verbs:биться{}, // биться головой о стену? (биться о) rus_verbs:ударить{}, // вода ударила его о стену коридора. (ударила о) rus_verbs:разбиваться{}, // волны разбивались о скалу rus_verbs:разбивать{}, // Разбивает голову о прутья клетки. rus_verbs:облокотиться{}, // облокотиться о стену rus_verbs:точить{}, // точить о точильный камень rus_verbs:спотыкаться{}, // спотыкаться о спрятавшийся в траве пень rus_verbs:потереться{}, // потереться о дерево rus_verbs:ушибиться{}, // ушибиться о дерево rus_verbs:тереться{}, // тереться о ствол rus_verbs:шмякнуться{}, // шмякнуться о землю rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:тереть{}, // тереть о камень rus_verbs:потереть{}, // потереть о колено rus_verbs:удариться{}, // удариться о край rus_verbs:споткнуться{}, // споткнуться о камень rus_verbs:запнуться{}, // запнуться о камень rus_verbs:запинаться{}, // запинаться о камни rus_verbs:ударяться{}, // ударяться о бортик rus_verbs:стукнуться{}, // стукнуться о бортик rus_verbs:стукаться{}, // стукаться о бортик rus_verbs:опереться{}, // Он опёрся локтями о стол. rus_verbs:плескаться{} // Вода плещется о берег. } fact гл_предл { if context { Гл_О_Вин предлог:о{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { * предлог:о{} *:*{ падеж:вин } } then return false,-5 } wordentry_set Гл_О_предл={ rus_verbs:КРИЧАТЬ{}, // она кричала о смерти! (КРИЧАТЬ) rus_verbs:РАССПРОСИТЬ{}, // Я расспросил о нем нескольких горожан. (РАССПРОСИТЬ/РАССПРАШИВАТЬ) rus_verbs:РАССПРАШИВАТЬ{}, // rus_verbs:слушать{}, // ты будешь слушать о них? rus_verbs:вспоминать{}, // вспоминать о том разговоре ему было неприятно rus_verbs:МОЛЧАТЬ{}, // О чём молчат девушки (МОЛЧАТЬ) rus_verbs:ПЛАКАТЬ{}, // она плакала о себе (ПЛАКАТЬ) rus_verbs:сложить{}, // о вас сложены легенды rus_verbs:ВОЛНОВАТЬСЯ{}, // Я волнуюсь о том, что что-то серьёзно пошло не так (ВОЛНОВАТЬСЯ О) rus_verbs:УПОМЯНУТЬ{}, // упомянул о намерении команды приобрести несколько новых футболистов (УПОМЯНУТЬ О) rus_verbs:ОТЧИТЫВАТЬСЯ{}, // Судебные приставы продолжают отчитываться о борьбе с неплательщиками (ОТЧИТЫВАТЬСЯ О) rus_verbs:ДОЛОЖИТЬ{}, // провести тщательное расследование взрыва в маршрутном такси во Владикавказе и доложить о результатах (ДОЛОЖИТЬ О) rus_verbs:ПРОБОЛТАТЬ{}, // правительство страны больше проболтало о военной реформе (ПРОБОЛТАТЬ О) rus_verbs:ЗАБОТИТЬСЯ{}, // Четверть россиян заботятся о здоровье путем просмотра телевизора (ЗАБОТИТЬСЯ О) rus_verbs:ИРОНИЗИРОВАТЬ{}, // Вы иронизируете о ностальгии по тем временем (ИРОНИЗИРОВАТЬ О) rus_verbs:СИГНАЛИЗИРОВАТЬ{}, // Кризис цен на продукты питания сигнализирует о неминуемой гиперинфляции (СИГНАЛИЗИРОВАТЬ О) rus_verbs:СПРОСИТЬ{}, // Он спросил о моём здоровье. (СПРОСИТЬ О) rus_verbs:НАПОМНИТЬ{}, // больной зуб опять напомнил о себе. (НАПОМНИТЬ О) rus_verbs:осведомиться{}, // офицер осведомился о цели визита rus_verbs:объявить{}, // В газете объявили о конкурсе. (объявить о) rus_verbs:ПРЕДСТОЯТЬ{}, // о чем предстоит разговор? (ПРЕДСТОЯТЬ О) rus_verbs:объявлять{}, // объявлять о всеобщей забастовке (объявлять о) rus_verbs:зайти{}, // Разговор зашёл о политике. rus_verbs:порассказать{}, // порассказать о своих путешествиях инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть о неразделенной любви деепричастие:спев{}, прилагательное:спевший{ вид:соверш }, прилагательное:спетый{}, rus_verbs:напеть{}, rus_verbs:разговаривать{}, // разговаривать с другом о жизни rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях //rus_verbs:заботиться{}, // заботиться о престарелых родителях rus_verbs:раздумывать{}, // раздумывать о новой работе rus_verbs:договариваться{}, // договариваться о сумме компенсации rus_verbs:молить{}, // молить о пощаде rus_verbs:отзываться{}, // отзываться о книге rus_verbs:подумывать{}, // подумывать о новом подходе rus_verbs:поговаривать{}, // поговаривать о загадочном звере rus_verbs:обмолвиться{}, // обмолвиться о проклятии rus_verbs:условиться{}, // условиться о поддержке rus_verbs:призадуматься{}, // призадуматься о последствиях rus_verbs:известить{}, // известить о поступлении rus_verbs:отрапортовать{}, // отрапортовать об успехах rus_verbs:напевать{}, // напевать о любви rus_verbs:помышлять{}, // помышлять о новом деле rus_verbs:переговорить{}, // переговорить о правилах rus_verbs:повествовать{}, // повествовать о событиях rus_verbs:слыхивать{}, // слыхивать о чудище rus_verbs:потолковать{}, // потолковать о планах rus_verbs:проговориться{}, // проговориться о планах rus_verbs:умолчать{}, // умолчать о штрафах rus_verbs:хлопотать{}, // хлопотать о премии rus_verbs:уведомить{}, // уведомить о поступлении rus_verbs:горевать{}, // горевать о потере rus_verbs:запамятовать{}, // запамятовать о важном мероприятии rus_verbs:заикнуться{}, // заикнуться о прибавке rus_verbs:информировать{}, // информировать о событиях rus_verbs:проболтаться{}, // проболтаться о кладе rus_verbs:поразмыслить{}, // поразмыслить о судьбе rus_verbs:заикаться{}, // заикаться о деньгах rus_verbs:оповестить{}, // оповестить об отказе rus_verbs:печься{}, // печься о всеобщем благе rus_verbs:разглагольствовать{}, // разглагольствовать о правах rus_verbs:размечтаться{}, // размечтаться о будущем rus_verbs:лепетать{}, // лепетать о невиновности rus_verbs:грезить{}, // грезить о большой и чистой любви rus_verbs:залепетать{}, // залепетать о сокровищах rus_verbs:пронюхать{}, // пронюхать о бесплатной одежде rus_verbs:протрубить{}, // протрубить о победе rus_verbs:извещать{}, // извещать о поступлении rus_verbs:трубить{}, // трубить о поимке разбойников rus_verbs:осведомляться{}, // осведомляться о судьбе rus_verbs:поразмышлять{}, // поразмышлять о неизбежном rus_verbs:слагать{}, // слагать о подвигах викингов rus_verbs:ходатайствовать{}, // ходатайствовать о выделении материальной помощи rus_verbs:побеспокоиться{}, // побеспокоиться о правильном стимулировании rus_verbs:закидывать{}, // закидывать сообщениями об ошибках rus_verbs:базарить{}, // пацаны базарили о телках rus_verbs:балагурить{}, // мужики балагурили о новом председателе rus_verbs:балакать{}, // мужики балакали о новом председателе rus_verbs:беспокоиться{}, // Она беспокоится о детях rus_verbs:рассказать{}, // Кумир рассказал о криминале в Москве rus_verbs:возмечтать{}, // возмечтать о счастливом мире rus_verbs:вопить{}, // Кто-то вопил о несправедливости rus_verbs:сказать{}, // сказать что-то новое о ком-то rus_verbs:знать{}, // знать о ком-то что-то пикантное rus_verbs:подумать{}, // подумать о чём-то rus_verbs:думать{}, // думать о чём-то rus_verbs:узнать{}, // узнать о происшествии rus_verbs:помнить{}, // помнить о задании rus_verbs:просить{}, // просить о коде доступа rus_verbs:забыть{}, // забыть о своих обязанностях rus_verbs:сообщить{}, // сообщить о заложенной мине rus_verbs:заявить{}, // заявить о пропаже rus_verbs:задуматься{}, // задуматься о смерти rus_verbs:спрашивать{}, // спрашивать о поступлении товара rus_verbs:догадаться{}, // догадаться о причинах rus_verbs:договориться{}, // договориться о собеседовании rus_verbs:мечтать{}, // мечтать о сцене rus_verbs:поговорить{}, // поговорить о наболевшем rus_verbs:размышлять{}, // размышлять о насущном rus_verbs:напоминать{}, // напоминать о себе rus_verbs:пожалеть{}, // пожалеть о содеянном rus_verbs:ныть{}, // ныть о прибавке rus_verbs:сообщать{}, // сообщать о победе rus_verbs:догадываться{}, // догадываться о первопричине rus_verbs:поведать{}, // поведать о тайнах rus_verbs:умолять{}, // умолять о пощаде rus_verbs:сожалеть{}, // сожалеть о случившемся rus_verbs:жалеть{}, // жалеть о случившемся rus_verbs:забывать{}, // забывать о случившемся rus_verbs:упоминать{}, // упоминать о предках rus_verbs:позабыть{}, // позабыть о своем обещании rus_verbs:запеть{}, // запеть о любви rus_verbs:скорбеть{}, // скорбеть о усопшем rus_verbs:задумываться{}, // задумываться о смене работы rus_verbs:позаботиться{}, // позаботиться о престарелых родителях rus_verbs:докладывать{}, // докладывать о планах строительства целлюлозно-бумажного комбината rus_verbs:попросить{}, // попросить о замене rus_verbs:предупредить{}, // предупредить о замене rus_verbs:предупреждать{}, // предупреждать о замене rus_verbs:твердить{}, // твердить о замене rus_verbs:заявлять{}, // заявлять о подлоге rus_verbs:петь{}, // певица, поющая о лете rus_verbs:проинформировать{}, // проинформировать о переговорах rus_verbs:порассказывать{}, // порассказывать о событиях rus_verbs:послушать{}, // послушать о новинках rus_verbs:заговорить{}, // заговорить о плате rus_verbs:отозваться{}, // Он отозвался о книге с большой похвалой. rus_verbs:оставить{}, // Он оставил о себе печальную память. rus_verbs:свидетельствовать{}, // страшно исхудавшее тело свидетельствовало о долгих лишениях rus_verbs:спорить{}, // они спорили о законе глагол:написать{ aux stress="напис^ать" }, инфинитив:написать{ aux stress="напис^ать" }, // Он написал о том, что видел во время путешествия. глагол:писать{ aux stress="пис^ать" }, инфинитив:писать{ aux stress="пис^ать" }, // Он писал о том, что видел во время путешествия. rus_verbs:прочитать{}, // Я прочитал о тебе rus_verbs:услышать{}, // Я услышал о нем rus_verbs:помечтать{}, // Девочки помечтали о принце rus_verbs:слышать{}, // Мальчик слышал о приведениях rus_verbs:вспомнить{}, // Девочки вспомнили о завтраке rus_verbs:грустить{}, // Я грущу о тебе rus_verbs:осведомить{}, // о последних достижениях науки rus_verbs:рассказывать{}, // Антонио рассказывает о работе rus_verbs:говорить{}, // говорим о трех больших псах rus_verbs:идти{} // Вопрос идёт о войне. } fact гл_предл { if context { Гл_О_предл предлог:о{} *:*{ падеж:предл } } then return true } // Мы поделились впечатлениями о выставке. // ^^^^^^^^^^ ^^^^^^^^^^ fact гл_предл { if context { * предлог:о{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:о{} *:*{} } then return false,-5 } #endregion Предлог_О #region Предлог_ПО // ------------------- С ПРЕДЛОГОМ 'ПО' ---------------------- // для этих глаголов - запрещаем связывание с ПО+дат.п. wordentry_set Глаг_ПО_Дат_Запр= { rus_verbs:предпринять{}, // предпринять шаги по стимулированию продаж rus_verbs:увлечь{}, // увлечь в прогулку по парку rus_verbs:закончить{}, rus_verbs:мочь{}, rus_verbs:хотеть{} } fact гл_предл { if context { Глаг_ПО_Дат_Запр предлог:по{} *:*{ падеж:дат } } then return false,-10 } // По умолчанию разрешаем связывание в паттернах типа // Я иду по шоссе fact гл_предл { if context { * предлог:по{} *:*{ падеж:дат } } then return true } wordentry_set Глаг_ПО_Вин= { rus_verbs:ВОЙТИ{}, // лезвие вошло по рукоять (ВОЙТИ) rus_verbs:иметь{}, // все месяцы имели по тридцать дней. (ИМЕТЬ ПО) rus_verbs:материализоваться{}, // материализоваться по другую сторону барьера rus_verbs:засадить{}, // засадить по рукоятку rus_verbs:увязнуть{} // увязнуть по колено } fact гл_предл { if context { Глаг_ПО_Вин предлог:по{} *:*{ падеж:вин } } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:по{} *:*{ падеж:вин } } then return false,-5 } #endregion Предлог_ПО #region Предлог_К // ------------------- С ПРЕДЛОГОМ 'К' ---------------------- wordentry_set Гл_К_Дат={ rus_verbs:заявиться{}, // Сразу же после обеда к нам заявилась Юлия Михайловна. rus_verbs:приставлять{} , // Приставляет дуло пистолета к виску. прилагательное:НЕПРИГОДНЫЙ{}, // большинство компьютеров из этой партии оказались непригодными к эксплуатации (НЕПРИГОДНЫЙ) rus_verbs:СБЕГАТЬСЯ{}, // Они чуяли воду и сбегались к ней отовсюду. (СБЕГАТЬСЯ) rus_verbs:СБЕЖАТЬСЯ{}, // К бетонной скамье начали сбегаться люди. (СБЕГАТЬСЯ/СБЕЖАТЬСЯ) rus_verbs:ПРИТИРАТЬСЯ{}, // Менее стойких водителей буквально сметало на другую полосу, и они впритык притирались к другим машинам. (ПРИТИРАТЬСЯ) rus_verbs:РУХНУТЬ{}, // а потом ты без чувств рухнул к моим ногам (РУХНУТЬ) rus_verbs:ПЕРЕНЕСТИ{}, // Они перенесли мясо к ручью и поджарили его на костре. (ПЕРЕНЕСТИ) rus_verbs:ЗАВЕСТИ{}, // как путь мой завел меня к нему? (ЗАВЕСТИ) rus_verbs:НАГРЯНУТЬ{}, // ФБР нагрянуло с обыском к сестре бостонских террористов (НАГРЯНУТЬ) rus_verbs:ПРИСЛОНЯТЬСЯ{}, // Рабы ложились на пол, прислонялись к стене и спали. (ПРИСЛОНЯТЬСЯ,ПРИНОРАВЛИВАТЬСЯ,ПРИНОРОВИТЬСЯ) rus_verbs:ПРИНОРАВЛИВАТЬСЯ{}, // rus_verbs:ПРИНОРОВИТЬСЯ{}, // rus_verbs:СПЛАНИРОВАТЬ{}, // Вскоре она остановила свое падение и спланировала к ним. (СПЛАНИРОВАТЬ,СПИКИРОВАТЬ,РУХНУТЬ) rus_verbs:СПИКИРОВАТЬ{}, // rus_verbs:ЗАБРАТЬСЯ{}, // Поэтому он забрался ко мне в квартиру с имевшимся у него полумесяцем. (ЗАБРАТЬСЯ К, В, С) rus_verbs:ПРОТЯГИВАТЬ{}, // Оно протягивало свои длинные руки к молодому человеку, стоявшему на плоской вершине валуна. (ПРОТЯГИВАТЬ/ПРОТЯНУТЬ/ТЯНУТЬ) rus_verbs:ПРОТЯНУТЬ{}, // rus_verbs:ТЯНУТЬ{}, // rus_verbs:ПЕРЕБИРАТЬСЯ{}, // Ее губы медленно перебирались к его уху. (ПЕРЕБИРАТЬСЯ,ПЕРЕБРАТЬСЯ,ПЕРЕБАЗИРОВАТЬСЯ,ПЕРЕМЕСТИТЬСЯ,ПЕРЕМЕЩАТЬСЯ) rus_verbs:ПЕРЕБРАТЬСЯ{}, // ,,, rus_verbs:ПЕРЕБАЗИРОВАТЬСЯ{}, // rus_verbs:ПЕРЕМЕСТИТЬСЯ{}, // rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // rus_verbs:ТРОНУТЬСЯ{}, // Он отвернулся от нее и тронулся к пляжу. (ТРОНУТЬСЯ) rus_verbs:ПРИСТАВИТЬ{}, // Он поднял одну из них и приставил верхний конец к краю шахты в потолке. rus_verbs:ПРОБИТЬСЯ{}, // Отряд с невероятными приключениями, пытается пробиться к своему полку, попадает в плен и другие передряги (ПРОБИТЬСЯ) rus_verbs:хотеть{}, rus_verbs:СДЕЛАТЬ{}, // Сделайте всё к понедельнику (СДЕЛАТЬ) rus_verbs:ИСПЫТЫВАТЬ{}, // она испытывает ко мне только отвращение (ИСПЫТЫВАТЬ) rus_verbs:ОБЯЗЫВАТЬ{}, // Это меня ни к чему не обязывает (ОБЯЗЫВАТЬ) rus_verbs:КАРАБКАТЬСЯ{}, // карабкаться по горе от подножия к вершине (КАРАБКАТЬСЯ) rus_verbs:СТОЯТЬ{}, // мужчина стоял ко мне спиной (СТОЯТЬ) rus_verbs:ПОДАТЬСЯ{}, // наконец люк подался ко мне (ПОДАТЬСЯ) rus_verbs:ПРИРАВНЯТЬ{}, // Усилия нельзя приравнять к результату (ПРИРАВНЯТЬ) rus_verbs:ПРИРАВНИВАТЬ{}, // Усилия нельзя приравнивать к результату (ПРИРАВНИВАТЬ) rus_verbs:ВОЗЛОЖИТЬ{}, // Путин в Пскове возложил цветы к памятнику воинам-десантникам, погибшим в Чечне (ВОЗЛОЖИТЬ) rus_verbs:запустить{}, // Индия запустит к Марсу свой космический аппарат в 2013 г rus_verbs:ПРИСТЫКОВАТЬСЯ{}, // Роботизированный российский грузовой космический корабль пристыковался к МКС (ПРИСТЫКОВАТЬСЯ) rus_verbs:ПРИМАЗАТЬСЯ{}, // К челябинскому метеориту примазалась таинственная слизь (ПРИМАЗАТЬСЯ) rus_verbs:ПОПРОСИТЬ{}, // Попросите Лизу к телефону (ПОПРОСИТЬ К) rus_verbs:ПРОЕХАТЬ{}, // Порой школьные автобусы просто не имеют возможности проехать к некоторым населенным пунктам из-за бездорожья (ПРОЕХАТЬ К) rus_verbs:ПОДЦЕПЛЯТЬСЯ{}, // Вагоны с пассажирами подцепляются к составу (ПОДЦЕПЛЯТЬСЯ К) rus_verbs:ПРИЗВАТЬ{}, // Президент Афганистана призвал талибов к прямому диалогу (ПРИЗВАТЬ К) rus_verbs:ПРЕОБРАЗИТЬСЯ{}, // Культовый столичный отель преобразился к юбилею (ПРЕОБРАЗИТЬСЯ К) прилагательное:ЧУВСТВИТЕЛЬНЫЙ{}, // нейроны одного комплекса чувствительны к разным веществам (ЧУВСТВИТЕЛЬНЫЙ К) безлич_глагол:нужно{}, // нам нужно к воротам (НУЖНО К) rus_verbs:БРОСИТЬ{}, // огромный клюв бросил это мясо к моим ногам (БРОСИТЬ К) rus_verbs:ЗАКОНЧИТЬ{}, // к пяти утра техники закончили (ЗАКОНЧИТЬ К) rus_verbs:НЕСТИ{}, // к берегу нас несет! (НЕСТИ К) rus_verbs:ПРОДВИГАТЬСЯ{}, // племена медленно продвигались к востоку (ПРОДВИГАТЬСЯ К) rus_verbs:ОПУСКАТЬСЯ{}, // деревья опускались к самой воде (ОПУСКАТЬСЯ К) rus_verbs:СТЕМНЕТЬ{}, // к тому времени стемнело (СТЕМНЕЛО К) rus_verbs:ОТСКОЧИТЬ{}, // после отскочил к окну (ОТСКОЧИТЬ К) rus_verbs:ДЕРЖАТЬСЯ{}, // к солнцу держались спинами (ДЕРЖАТЬСЯ К) rus_verbs:КАЧНУТЬСЯ{}, // толпа качнулась к ступеням (КАЧНУТЬСЯ К) rus_verbs:ВОЙТИ{}, // Андрей вошел к себе (ВОЙТИ К) rus_verbs:ВЫБРАТЬСЯ{}, // мы выбрались к окну (ВЫБРАТЬСЯ К) rus_verbs:ПРОВЕСТИ{}, // провел к стене спальни (ПРОВЕСТИ К) rus_verbs:ВЕРНУТЬСЯ{}, // давай вернемся к делу (ВЕРНУТЬСЯ К) rus_verbs:ВОЗВРАТИТЬСЯ{}, // Среди евреев, живших в диаспоре, всегда было распространено сильное стремление возвратиться к Сиону (ВОЗВРАТИТЬСЯ К) rus_verbs:ПРИЛЕГАТЬ{}, // Задняя поверхность хрусталика прилегает к стекловидному телу (ПРИЛЕГАТЬ К) rus_verbs:ПЕРЕНЕСТИСЬ{}, // мысленно Алёна перенеслась к заливу (ПЕРЕНЕСТИСЬ К) rus_verbs:ПРОБИВАТЬСЯ{}, // сквозь болото к берегу пробивался ручей. (ПРОБИВАТЬСЯ К) rus_verbs:ПЕРЕВЕСТИ{}, // необходимо срочно перевести стадо к воде. (ПЕРЕВЕСТИ К) rus_verbs:ПРИЛЕТЕТЬ{}, // зачем ты прилетел к нам? (ПРИЛЕТЕТЬ К) rus_verbs:ДОБАВИТЬ{}, // добавить ли ее к остальным? (ДОБАВИТЬ К) rus_verbs:ПРИГОТОВИТЬ{}, // Матвей приготовил лук к бою. (ПРИГОТОВИТЬ К) rus_verbs:РВАНУТЬ{}, // человек рванул ее к себе. (РВАНУТЬ К) rus_verbs:ТАЩИТЬ{}, // они тащили меня к двери. (ТАЩИТЬ К) глагол:быть{}, // к тебе есть вопросы. прилагательное:равнодушный{}, // Он равнодушен к музыке. rus_verbs:ПОЖАЛОВАТЬ{}, // скандально известный певец пожаловал к нам на передачу (ПОЖАЛОВАТЬ К) rus_verbs:ПЕРЕСЕСТЬ{}, // Ольга пересела к Антону (ПЕРЕСЕСТЬ К) инфинитив:СБЕГАТЬ{ вид:соверш }, глагол:СБЕГАТЬ{ вид:соверш }, // сбегай к Борису (СБЕГАТЬ К) rus_verbs:ПЕРЕХОДИТЬ{}, // право хода переходит к Адаму (ПЕРЕХОДИТЬ К) rus_verbs:прижаться{}, // она прижалась щекой к его шее. (прижаться+к) rus_verbs:ПОДСКОЧИТЬ{}, // солдат быстро подскочил ко мне. (ПОДСКОЧИТЬ К) rus_verbs:ПРОБРАТЬСЯ{}, // нужно пробраться к реке. (ПРОБРАТЬСЯ К) rus_verbs:ГОТОВИТЬ{}, // нас готовили к этому. (ГОТОВИТЬ К) rus_verbs:ТЕЧЬ{}, // река текла к морю. (ТЕЧЬ К) rus_verbs:ОТШАТНУТЬСЯ{}, // епископ отшатнулся к стене. (ОТШАТНУТЬСЯ К) rus_verbs:БРАТЬ{}, // брали бы к себе. (БРАТЬ К) rus_verbs:СКОЛЬЗНУТЬ{}, // ковер скользнул к пещере. (СКОЛЬЗНУТЬ К) rus_verbs:присохнуть{}, // Грязь присохла к одежде. (присохнуть к) rus_verbs:просить{}, // Директор просит вас к себе. (просить к) rus_verbs:вызывать{}, // шеф вызывал к себе. (вызывать к) rus_verbs:присесть{}, // старик присел к огню. (присесть к) rus_verbs:НАКЛОНИТЬСЯ{}, // Ричард наклонился к брату. (НАКЛОНИТЬСЯ К) rus_verbs:выбираться{}, // будем выбираться к дороге. (выбираться к) rus_verbs:отвернуться{}, // Виктор отвернулся к стене. (отвернуться к) rus_verbs:СТИХНУТЬ{}, // огонь стих к полудню. (СТИХНУТЬ К) rus_verbs:УПАСТЬ{}, // нож упал к ногам. (УПАСТЬ К) rus_verbs:СЕСТЬ{}, // молча сел к огню. (СЕСТЬ К) rus_verbs:ХЛЫНУТЬ{}, // народ хлынул к стенам. (ХЛЫНУТЬ К) rus_verbs:покатиться{}, // они черной волной покатились ко мне. (покатиться к) rus_verbs:ОБРАТИТЬ{}, // она обратила к нему свое бледное лицо. (ОБРАТИТЬ К) rus_verbs:СКЛОНИТЬ{}, // Джон слегка склонил голову к плечу. (СКЛОНИТЬ К) rus_verbs:СВЕРНУТЬ{}, // дорожка резко свернула к южной стене. (СВЕРНУТЬ К) rus_verbs:ЗАВЕРНУТЬ{}, // Он завернул к нам по пути к месту службы. (ЗАВЕРНУТЬ К) rus_verbs:подходить{}, // цвет подходил ей к лицу. rus_verbs:БРЕСТИ{}, // Ричард покорно брел к отцу. (БРЕСТИ К) rus_verbs:ПОПАСТЬ{}, // хочешь попасть к нему? (ПОПАСТЬ К) rus_verbs:ПОДНЯТЬ{}, // Мартин поднял ружье к плечу. (ПОДНЯТЬ К) rus_verbs:ПОТЕРЯТЬ{}, // просто потеряла к нему интерес. (ПОТЕРЯТЬ К) rus_verbs:РАЗВЕРНУТЬСЯ{}, // они сразу развернулись ко мне. (РАЗВЕРНУТЬСЯ К) rus_verbs:ПОВЕРНУТЬ{}, // мальчик повернул к ним голову. (ПОВЕРНУТЬ К) rus_verbs:вызвать{}, // или вызвать к жизни? (вызвать к) rus_verbs:ВЫХОДИТЬ{}, // их земли выходят к морю. (ВЫХОДИТЬ К) rus_verbs:ЕХАТЬ{}, // мы долго ехали к вам. (ЕХАТЬ К) rus_verbs:опуститься{}, // Алиса опустилась к самому дну. (опуститься к) rus_verbs:подняться{}, // они молча поднялись к себе. (подняться к) rus_verbs:ДВИНУТЬСЯ{}, // толстяк тяжело двинулся к ним. (ДВИНУТЬСЯ К) rus_verbs:ПОПЯТИТЬСЯ{}, // ведьмак осторожно попятился к лошади. (ПОПЯТИТЬСЯ К) rus_verbs:РИНУТЬСЯ{}, // мышелов ринулся к черной стене. (РИНУТЬСЯ К) rus_verbs:ТОЛКНУТЬ{}, // к этому толкнул ее ты. (ТОЛКНУТЬ К) rus_verbs:отпрыгнуть{}, // Вадим поспешно отпрыгнул к борту. (отпрыгнуть к) rus_verbs:отступить{}, // мы поспешно отступили к стене. (отступить к) rus_verbs:ЗАБРАТЬ{}, // мы забрали их к себе. (ЗАБРАТЬ к) rus_verbs:ВЗЯТЬ{}, // потом возьму тебя к себе. (ВЗЯТЬ К) rus_verbs:лежать{}, // наш путь лежал к ним. (лежать к) rus_verbs:поползти{}, // ее рука поползла к оружию. (поползти к) rus_verbs:требовать{}, // вас требует к себе император. (требовать к) rus_verbs:поехать{}, // ты должен поехать к нему. (поехать к) rus_verbs:тянуться{}, // мордой животное тянулось к земле. (тянуться к) rus_verbs:ЖДАТЬ{}, // жди их завтра к утру. (ЖДАТЬ К) rus_verbs:ПОЛЕТЕТЬ{}, // они стремительно полетели к земле. (ПОЛЕТЕТЬ К) rus_verbs:подойти{}, // помоги мне подойти к столу. (подойти к) rus_verbs:РАЗВЕРНУТЬ{}, // мужик развернул к нему коня. (РАЗВЕРНУТЬ К) rus_verbs:ПРИВЕЗТИ{}, // нас привезли прямо к королю. (ПРИВЕЗТИ К) rus_verbs:отпрянуть{}, // незнакомец отпрянул к стене. (отпрянуть к) rus_verbs:побежать{}, // Cергей побежал к двери. (побежать к) rus_verbs:отбросить{}, // сильный удар отбросил его к стене. (отбросить к) rus_verbs:ВЫНУДИТЬ{}, // они вынудили меня к сотрудничеству (ВЫНУДИТЬ К) rus_verbs:подтянуть{}, // он подтянул к себе стул и сел на него (подтянуть к) rus_verbs:сойти{}, // по узкой тропинке путники сошли к реке. (сойти к) rus_verbs:являться{}, // по ночам к нему являлись призраки. (являться к) rus_verbs:ГНАТЬ{}, // ледяной ветер гнал их к югу. (ГНАТЬ К) rus_verbs:ВЫВЕСТИ{}, // она вывела нас точно к месту. (ВЫВЕСТИ К) rus_verbs:выехать{}, // почти сразу мы выехали к реке. rus_verbs:пододвигаться{}, // пододвигайся к окну rus_verbs:броситься{}, // большая часть защитников стен бросилась к воротам. rus_verbs:представить{}, // Его представили к ордену. rus_verbs:двигаться{}, // между тем чудище неторопливо двигалось к берегу. rus_verbs:выскочить{}, // тем временем они выскочили к реке. rus_verbs:выйти{}, // тем временем они вышли к лестнице. rus_verbs:потянуть{}, // Мальчик схватил верёвку и потянул её к себе. rus_verbs:приложить{}, // приложить к детали повышенное усилие rus_verbs:пройти{}, // пройти к стойке регистрации (стойка регистрации - проверить проверку) rus_verbs:отнестись{}, // отнестись к животным с сочуствием rus_verbs:привязать{}, // привязать за лапу веревкой к колышку, воткнутому в землю rus_verbs:прыгать{}, // прыгать к хозяину на стол rus_verbs:приглашать{}, // приглашать к доктору rus_verbs:рваться{}, // Чужие люди рвутся к власти rus_verbs:понестись{}, // понестись к обрыву rus_verbs:питать{}, // питать привязанность к алкоголю rus_verbs:заехать{}, // Коля заехал к Оле rus_verbs:переехать{}, // переехать к родителям rus_verbs:ползти{}, // ползти к дороге rus_verbs:сводиться{}, // сводиться к элементарному действию rus_verbs:добавлять{}, // добавлять к общей сумме rus_verbs:подбросить{}, // подбросить к потолку rus_verbs:призывать{}, // призывать к спокойствию rus_verbs:пробираться{}, // пробираться к партизанам rus_verbs:отвезти{}, // отвезти к родителям rus_verbs:применяться{}, // применяться к уравнению rus_verbs:сходиться{}, // сходиться к точному решению rus_verbs:допускать{}, // допускать к сдаче зачета rus_verbs:свести{}, // свести к нулю rus_verbs:придвинуть{}, // придвинуть к мальчику rus_verbs:подготовить{}, // подготовить к печати rus_verbs:подобраться{}, // подобраться к оленю rus_verbs:заторопиться{}, // заторопиться к выходу rus_verbs:пристать{}, // пристать к берегу rus_verbs:поманить{}, // поманить к себе rus_verbs:припасть{}, // припасть к алтарю rus_verbs:притащить{}, // притащить к себе домой rus_verbs:прижимать{}, // прижимать к груди rus_verbs:подсесть{}, // подсесть к симпатичной девочке rus_verbs:придвинуться{}, // придвинуться к окну rus_verbs:отпускать{}, // отпускать к другу rus_verbs:пригнуться{}, // пригнуться к земле rus_verbs:пристроиться{}, // пристроиться к колонне rus_verbs:сгрести{}, // сгрести к себе rus_verbs:удрать{}, // удрать к цыганам rus_verbs:прибавиться{}, // прибавиться к общей сумме rus_verbs:присмотреться{}, // присмотреться к покупке rus_verbs:подкатить{}, // подкатить к трюму rus_verbs:клонить{}, // клонить ко сну rus_verbs:проследовать{}, // проследовать к выходу rus_verbs:пододвинуть{}, // пододвинуть к себе rus_verbs:применять{}, // применять к сотрудникам rus_verbs:прильнуть{}, // прильнуть к экранам rus_verbs:подвинуть{}, // подвинуть к себе rus_verbs:примчаться{}, // примчаться к папе rus_verbs:подкрасться{}, // подкрасться к жертве rus_verbs:привязаться{}, // привязаться к собаке rus_verbs:забирать{}, // забирать к себе rus_verbs:прорваться{}, // прорваться к кассе rus_verbs:прикасаться{}, // прикасаться к коже rus_verbs:уносить{}, // уносить к себе rus_verbs:подтянуться{}, // подтянуться к месту rus_verbs:привозить{}, // привозить к ветеринару rus_verbs:подползти{}, // подползти к зайцу rus_verbs:приблизить{}, // приблизить к глазам rus_verbs:применить{}, // применить к уравнению простое преобразование rus_verbs:приглядеться{}, // приглядеться к изображению rus_verbs:приложиться{}, // приложиться к ручке rus_verbs:приставать{}, // приставать к девчонкам rus_verbs:запрещаться{}, // запрещаться к показу rus_verbs:прибегать{}, // прибегать к насилию rus_verbs:побудить{}, // побудить к действиям rus_verbs:притягивать{}, // притягивать к себе rus_verbs:пристроить{}, // пристроить к полезному делу rus_verbs:приговорить{}, // приговорить к смерти rus_verbs:склоняться{}, // склоняться к прекращению разработки rus_verbs:подъезжать{}, // подъезжать к вокзалу rus_verbs:привалиться{}, // привалиться к забору rus_verbs:наклоняться{}, // наклоняться к щенку rus_verbs:подоспеть{}, // подоспеть к обеду rus_verbs:прилипнуть{}, // прилипнуть к окну rus_verbs:приволочь{}, // приволочь к себе rus_verbs:устремляться{}, // устремляться к вершине rus_verbs:откатиться{}, // откатиться к исходным позициям rus_verbs:побуждать{}, // побуждать к действиям rus_verbs:прискакать{}, // прискакать к кормежке rus_verbs:присматриваться{}, // присматриваться к новичку rus_verbs:прижиматься{}, // прижиматься к борту rus_verbs:жаться{}, // жаться к огню rus_verbs:передвинуть{}, // передвинуть к окну rus_verbs:допускаться{}, // допускаться к экзаменам rus_verbs:прикрепить{}, // прикрепить к корпусу rus_verbs:отправлять{}, // отправлять к специалистам rus_verbs:перебежать{}, // перебежать к врагам rus_verbs:притронуться{}, // притронуться к реликвии rus_verbs:заспешить{}, // заспешить к семье rus_verbs:ревновать{}, // ревновать к сопернице rus_verbs:подступить{}, // подступить к горлу rus_verbs:уводить{}, // уводить к ветеринару rus_verbs:побросать{}, // побросать к ногам rus_verbs:подаваться{}, // подаваться к ужину rus_verbs:приписывать{}, // приписывать к достижениям rus_verbs:относить{}, // относить к растениям rus_verbs:принюхаться{}, // принюхаться к ароматам rus_verbs:подтащить{}, // подтащить к себе rus_verbs:прислонить{}, // прислонить к стене rus_verbs:подплыть{}, // подплыть к бую rus_verbs:опаздывать{}, // опаздывать к стилисту rus_verbs:примкнуть{}, // примкнуть к деомнстрантам rus_verbs:стекаться{}, // стекаются к стенам тюрьмы rus_verbs:подготовиться{}, // подготовиться к марафону rus_verbs:приглядываться{}, // приглядываться к новичку rus_verbs:присоединяться{}, // присоединяться к сообществу rus_verbs:клониться{}, // клониться ко сну rus_verbs:привыкать{}, // привыкать к хорошему rus_verbs:принудить{}, // принудить к миру rus_verbs:уплыть{}, // уплыть к далекому берегу rus_verbs:утащить{}, // утащить к детенышам rus_verbs:приплыть{}, // приплыть к финишу rus_verbs:подбегать{}, // подбегать к хозяину rus_verbs:лишаться{}, // лишаться средств к существованию rus_verbs:приступать{}, // приступать к операции rus_verbs:пробуждать{}, // пробуждать лекцией интерес к математике rus_verbs:подключить{}, // подключить к трубе rus_verbs:подключиться{}, // подключиться к сети rus_verbs:прилить{}, // прилить к лицу rus_verbs:стучаться{}, // стучаться к соседям rus_verbs:пристегнуть{}, // пристегнуть к креслу rus_verbs:присоединить{}, // присоединить к сети rus_verbs:отбежать{}, // отбежать к противоположной стене rus_verbs:подвезти{}, // подвезти к набережной rus_verbs:прибегнуть{}, // прибегнуть к хитрости rus_verbs:приучить{}, // приучить к туалету rus_verbs:подталкивать{}, // подталкивать к выходу rus_verbs:прорываться{}, // прорываться к выходу rus_verbs:увозить{}, // увозить к ветеринару rus_verbs:засеменить{}, // засеменить к выходу rus_verbs:крепиться{}, // крепиться к потолку rus_verbs:прибрать{}, // прибрать к рукам rus_verbs:пристраститься{}, // пристраститься к наркотикам rus_verbs:поспеть{}, // поспеть к обеду rus_verbs:привязывать{}, // привязывать к дереву rus_verbs:прилагать{}, // прилагать к документам rus_verbs:переправить{}, // переправить к дедушке rus_verbs:подогнать{}, // подогнать к воротам rus_verbs:тяготеть{}, // тяготеть к социализму rus_verbs:подбираться{}, // подбираться к оленю rus_verbs:подступать{}, // подступать к горлу rus_verbs:примыкать{}, // примыкать к первому элементу rus_verbs:приладить{}, // приладить к велосипеду rus_verbs:подбрасывать{}, // подбрасывать к потолку rus_verbs:перевозить{}, // перевозить к новому месту дислокации rus_verbs:усаживаться{}, // усаживаться к окну rus_verbs:приближать{}, // приближать к глазам rus_verbs:попроситься{}, // попроситься к бабушке rus_verbs:прибить{}, // прибить к доске rus_verbs:перетащить{}, // перетащить к себе rus_verbs:прицепить{}, // прицепить к паровозу rus_verbs:прикладывать{}, // прикладывать к ране rus_verbs:устареть{}, // устареть к началу войны rus_verbs:причалить{}, // причалить к пристани rus_verbs:приспособиться{}, // приспособиться к опозданиям rus_verbs:принуждать{}, // принуждать к миру rus_verbs:соваться{}, // соваться к директору rus_verbs:протолкаться{}, // протолкаться к прилавку rus_verbs:приковать{}, // приковать к батарее rus_verbs:подкрадываться{}, // подкрадываться к суслику rus_verbs:подсадить{}, // подсадить к арестонту rus_verbs:прикатить{}, // прикатить к финишу rus_verbs:протащить{}, // протащить к владыке rus_verbs:сужаться{}, // сужаться к основанию rus_verbs:присовокупить{}, // присовокупить к пожеланиям rus_verbs:пригвоздить{}, // пригвоздить к доске rus_verbs:отсылать{}, // отсылать к первоисточнику rus_verbs:изготовиться{}, // изготовиться к прыжку rus_verbs:прилагаться{}, // прилагаться к покупке rus_verbs:прицепиться{}, // прицепиться к вагону rus_verbs:примешиваться{}, // примешиваться к вину rus_verbs:переселить{}, // переселить к старшекурсникам rus_verbs:затрусить{}, // затрусить к выходе rus_verbs:приспособить{}, // приспособить к обогреву rus_verbs:примериться{}, // примериться к аппарату rus_verbs:прибавляться{}, // прибавляться к пенсии rus_verbs:подкатиться{}, // подкатиться к воротам rus_verbs:стягивать{}, // стягивать к границе rus_verbs:дописать{}, // дописать к роману rus_verbs:подпустить{}, // подпустить к корове rus_verbs:склонять{}, // склонять к сотрудничеству rus_verbs:припечатать{}, // припечатать к стене rus_verbs:охладеть{}, // охладеть к музыке rus_verbs:пришить{}, // пришить к шинели rus_verbs:принюхиваться{}, // принюхиваться к ветру rus_verbs:подрулить{}, // подрулить к барышне rus_verbs:наведаться{}, // наведаться к оракулу rus_verbs:клеиться{}, // клеиться к конверту rus_verbs:перетянуть{}, // перетянуть к себе rus_verbs:переметнуться{}, // переметнуться к конкурентам rus_verbs:липнуть{}, // липнуть к сокурсницам rus_verbs:поковырять{}, // поковырять к выходу rus_verbs:подпускать{}, // подпускать к пульту управления rus_verbs:присосаться{}, // присосаться к источнику rus_verbs:приклеить{}, // приклеить к стеклу rus_verbs:подтягивать{}, // подтягивать к себе rus_verbs:подкатывать{}, // подкатывать к даме rus_verbs:притрагиваться{}, // притрагиваться к опухоли rus_verbs:слетаться{}, // слетаться к водопою rus_verbs:хаживать{}, // хаживать к батюшке rus_verbs:привлекаться{}, // привлекаться к административной ответственности rus_verbs:подзывать{}, // подзывать к себе rus_verbs:прикладываться{}, // прикладываться к иконе rus_verbs:подтягиваться{}, // подтягиваться к парламенту rus_verbs:прилепить{}, // прилепить к стенке холодильника rus_verbs:пододвинуться{}, // пододвинуться к экрану rus_verbs:приползти{}, // приползти к дереву rus_verbs:запаздывать{}, // запаздывать к обеду rus_verbs:припереть{}, // припереть к стене rus_verbs:нагибаться{}, // нагибаться к цветку инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять к воротам деепричастие:сгоняв{}, rus_verbs:поковылять{}, // поковылять к выходу rus_verbs:привалить{}, // привалить к столбу rus_verbs:отпроситься{}, // отпроситься к родителям rus_verbs:приспосабливаться{}, // приспосабливаться к новым условиям rus_verbs:прилипать{}, // прилипать к рукам rus_verbs:подсоединить{}, // подсоединить к приборам rus_verbs:приливать{}, // приливать к голове rus_verbs:подселить{}, // подселить к другим новичкам rus_verbs:прилепиться{}, // прилепиться к шкуре rus_verbs:подлетать{}, // подлетать к пункту назначения rus_verbs:пристегнуться{}, // пристегнуться к креслу ремнями rus_verbs:прибиться{}, // прибиться к стае, улетающей на юг rus_verbs:льнуть{}, // льнуть к заботливому хозяину rus_verbs:привязываться{}, // привязываться к любящему хозяину rus_verbs:приклеиться{}, // приклеиться к спине rus_verbs:стягиваться{}, // стягиваться к сенату rus_verbs:подготавливать{}, // подготавливать к выходу на арену rus_verbs:приглашаться{}, // приглашаться к доктору rus_verbs:причислять{}, // причислять к отличникам rus_verbs:приколоть{}, // приколоть к лацкану rus_verbs:наклонять{}, // наклонять к горизонту rus_verbs:припадать{}, // припадать к первоисточнику rus_verbs:приобщиться{}, // приобщиться к культурному наследию rus_verbs:придираться{}, // придираться к мелким ошибкам rus_verbs:приучать{}, // приучать к лотку rus_verbs:промотать{}, // промотать к началу rus_verbs:прихлынуть{}, // прихлынуть к голове rus_verbs:пришвартоваться{}, // пришвартоваться к первому пирсу rus_verbs:прикрутить{}, // прикрутить к велосипеду rus_verbs:подплывать{}, // подплывать к лодке rus_verbs:приравниваться{}, // приравниваться к побегу rus_verbs:подстрекать{}, // подстрекать к вооруженной борьбе с оккупантами rus_verbs:изготовляться{}, // изготовляться к прыжку из стратосферы rus_verbs:приткнуться{}, // приткнуться к первой группе туристов rus_verbs:приручить{}, // приручить котика к лотку rus_verbs:приковывать{}, // приковывать к себе все внимание прессы rus_verbs:приготовляться{}, // приготовляться к первому экзамену rus_verbs:остыть{}, // Вода остынет к утру. rus_verbs:приехать{}, // Он приедет к концу будущей недели. rus_verbs:подсаживаться{}, rus_verbs:успевать{}, // успевать к стилисту rus_verbs:привлекать{}, // привлекать к себе внимание прилагательное:устойчивый{}, // переводить в устойчивую к перегреву форму rus_verbs:прийтись{}, // прийтись ко двору инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована к условиям крайнего севера инфинитив:адаптировать{вид:соверш}, глагол:адаптировать{вид:несоверш}, глагол:адаптировать{вид:соверш}, деепричастие:адаптировав{}, деепричастие:адаптируя{}, прилагательное:адаптирующий{}, прилагательное:адаптировавший{ вид:соверш }, //+прилагательное:адаптировавший{ вид:несоверш }, прилагательное:адаптированный{}, инфинитив:адаптироваться{вид:соверш}, // тело адаптировалось к условиям суровой зимы инфинитив:адаптироваться{вид:несоверш}, глагол:адаптироваться{вид:соверш}, глагол:адаптироваться{вид:несоверш}, деепричастие:адаптировавшись{}, деепричастие:адаптируясь{}, прилагательное:адаптировавшийся{вид:соверш}, //+прилагательное:адаптировавшийся{вид:несоверш}, прилагательное:адаптирующийся{}, rus_verbs:апеллировать{}, // оратор апеллировал к патриотизму своих слушателей rus_verbs:близиться{}, // Шторм близится к побережью rus_verbs:доставить{}, // Эскиз ракеты, способной доставить корабль к Луне rus_verbs:буксировать{}, // Буксир буксирует танкер к месту стоянки rus_verbs:причислить{}, // Мы причислили его к числу экспертов rus_verbs:вести{}, // Наша партия ведет народ к процветанию rus_verbs:взывать{}, // Учителя взывают к совести хулигана rus_verbs:воззвать{}, // воззвать соплеменников к оружию rus_verbs:возревновать{}, // возревновать к поклонникам rus_verbs:воспылать{}, // Коля воспылал к Оле страстной любовью rus_verbs:восходить{}, // восходить к вершине rus_verbs:восшествовать{}, // восшествовать к вершине rus_verbs:успеть{}, // успеть к обеду rus_verbs:повернуться{}, // повернуться к кому-то rus_verbs:обратиться{}, // обратиться к охраннику rus_verbs:звать{}, // звать к столу rus_verbs:отправиться{}, // отправиться к парикмахеру rus_verbs:обернуться{}, // обернуться к зовущему rus_verbs:явиться{}, // явиться к следователю rus_verbs:уехать{}, // уехать к родне rus_verbs:прибыть{}, // прибыть к перекличке rus_verbs:привыкнуть{}, // привыкнуть к голоду rus_verbs:уходить{}, // уходить к цыганам rus_verbs:привести{}, // привести к себе rus_verbs:шагнуть{}, // шагнуть к славе rus_verbs:относиться{}, // относиться к прежним периодам rus_verbs:подослать{}, // подослать к врагам rus_verbs:поспешить{}, // поспешить к обеду rus_verbs:зайти{}, // зайти к подруге rus_verbs:позвать{}, // позвать к себе rus_verbs:потянуться{}, // потянуться к рычагам rus_verbs:пускать{}, // пускать к себе rus_verbs:отвести{}, // отвести к врачу rus_verbs:приблизиться{}, // приблизиться к решению задачи rus_verbs:прижать{}, // прижать к стене rus_verbs:отправить{}, // отправить к доктору rus_verbs:падать{}, // падать к многолетним минимумам rus_verbs:полезть{}, // полезть к дерущимся rus_verbs:лезть{}, // Ты сама ко мне лезла! rus_verbs:направить{}, // направить к майору rus_verbs:приводить{}, // приводить к дантисту rus_verbs:кинуться{}, // кинуться к двери rus_verbs:поднести{}, // поднести к глазам rus_verbs:подниматься{}, // подниматься к себе rus_verbs:прибавить{}, // прибавить к результату rus_verbs:зашагать{}, // зашагать к выходу rus_verbs:склониться{}, // склониться к земле rus_verbs:стремиться{}, // стремиться к вершине rus_verbs:лететь{}, // лететь к родственникам rus_verbs:ездить{}, // ездить к любовнице rus_verbs:приближаться{}, // приближаться к финише rus_verbs:помчаться{}, // помчаться к стоматологу rus_verbs:прислушаться{}, // прислушаться к происходящему rus_verbs:изменить{}, // изменить к лучшему собственную жизнь rus_verbs:проявить{}, // проявить к погибшим сострадание rus_verbs:подбежать{}, // подбежать к упавшему rus_verbs:терять{}, // терять к партнерам доверие rus_verbs:пропустить{}, // пропустить к певцу rus_verbs:подвести{}, // подвести к глазам rus_verbs:меняться{}, // меняться к лучшему rus_verbs:заходить{}, // заходить к другу rus_verbs:рвануться{}, // рвануться к воде rus_verbs:привлечь{}, // привлечь к себе внимание rus_verbs:присоединиться{}, // присоединиться к сети rus_verbs:приезжать{}, // приезжать к дедушке rus_verbs:дернуться{}, // дернуться к борту rus_verbs:подъехать{}, // подъехать к воротам rus_verbs:готовиться{}, // готовиться к дождю rus_verbs:убежать{}, // убежать к маме rus_verbs:поднимать{}, // поднимать к источнику сигнала rus_verbs:отослать{}, // отослать к руководителю rus_verbs:приготовиться{}, // приготовиться к худшему rus_verbs:приступить{}, // приступить к выполнению обязанностей rus_verbs:метнуться{}, // метнуться к фонтану rus_verbs:прислушиваться{}, // прислушиваться к голосу разума rus_verbs:побрести{}, // побрести к выходу rus_verbs:мчаться{}, // мчаться к успеху rus_verbs:нестись{}, // нестись к обрыву rus_verbs:попадать{}, // попадать к хорошему костоправу rus_verbs:опоздать{}, // опоздать к психотерапевту rus_verbs:посылать{}, // посылать к доктору rus_verbs:поплыть{}, // поплыть к берегу rus_verbs:подтолкнуть{}, // подтолкнуть к активной работе rus_verbs:отнести{}, // отнести животное к ветеринару rus_verbs:прислониться{}, // прислониться к стволу rus_verbs:наклонить{}, // наклонить к миске с молоком rus_verbs:прикоснуться{}, // прикоснуться к поверхности rus_verbs:увезти{}, // увезти к бабушке rus_verbs:заканчиваться{}, // заканчиваться к концу путешествия rus_verbs:подозвать{}, // подозвать к себе rus_verbs:улететь{}, // улететь к теплым берегам rus_verbs:ложиться{}, // ложиться к мужу rus_verbs:убираться{}, // убираться к чертовой бабушке rus_verbs:класть{}, // класть к другим документам rus_verbs:доставлять{}, // доставлять к подъезду rus_verbs:поворачиваться{}, // поворачиваться к источнику шума rus_verbs:заглядывать{}, // заглядывать к любовнице rus_verbs:занести{}, // занести к заказчикам rus_verbs:прибежать{}, // прибежать к папе rus_verbs:притянуть{}, // притянуть к причалу rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму rus_verbs:подать{}, // он подал лимузин к подъезду rus_verbs:подавать{}, // она подавала соус к мясу rus_verbs:приобщаться{}, // приобщаться к культуре прилагательное:неспособный{}, // Наша дочка неспособна к учению. прилагательное:неприспособленный{}, // Эти устройства неприспособлены к работе в жару прилагательное:предназначенный{}, // Старый дом предназначен к сносу. прилагательное:внимательный{}, // Она всегда внимательна к гостям. прилагательное:назначенный{}, // Дело назначено к докладу. прилагательное:разрешенный{}, // Эта книга разрешена к печати. прилагательное:снисходительный{}, // Этот учитель снисходителен к ученикам. прилагательное:готовый{}, // Я готов к экзаменам. прилагательное:требовательный{}, // Он очень требователен к себе. прилагательное:жадный{}, // Он жаден к деньгам. прилагательное:глухой{}, // Он глух к моей просьбе. прилагательное:добрый{}, // Он добр к детям. rus_verbs:проявлять{}, // Он всегда проявлял живой интерес к нашим делам. rus_verbs:плыть{}, // Пароход плыл к берегу. rus_verbs:пойти{}, // я пошел к доктору rus_verbs:придти{}, // придти к выводу rus_verbs:заглянуть{}, // Я заглянул к вам мимоходом. rus_verbs:принадлежать{}, // Это существо принадлежит к разряду растений. rus_verbs:подготавливаться{}, // Ученики подготавливаются к экзаменам. rus_verbs:спускаться{}, // Улица круто спускается к реке. rus_verbs:спуститься{}, // Мы спустились к реке. rus_verbs:пустить{}, // пускать ко дну rus_verbs:приговаривать{}, // Мы приговариваем тебя к пожизненному веселью! rus_verbs:отойти{}, // Дом отошёл к племяннику. rus_verbs:отходить{}, // Коля отходил ко сну. rus_verbs:приходить{}, // местные жители к нему приходили лечиться rus_verbs:кидаться{}, // не кидайся к столу rus_verbs:ходить{}, // Она простудилась и сегодня ходила к врачу. rus_verbs:закончиться{}, // Собрание закончилось к вечеру. rus_verbs:послать{}, // Они выбрали своих депутатов и послали их к заведующему. rus_verbs:направиться{}, // Мы сошли на берег и направились к городу. rus_verbs:направляться{}, rus_verbs:свестись{}, // Всё свелось к нулю. rus_verbs:прислать{}, // Пришлите кого-нибудь к ней. rus_verbs:присылать{}, // Он присылал к должнику своих головорезов rus_verbs:подлететь{}, // Самолёт подлетел к лесу. rus_verbs:возвращаться{}, // он возвращается к старой работе глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, деепричастие:находясь{}, прилагательное:находившийся{}, прилагательное:находящийся{}, // Япония находится к востоку от Китая. rus_verbs:возвращать{}, // возвращать к жизни rus_verbs:располагать{}, // Атмосфера располагает к работе. rus_verbs:возвратить{}, // Колокольный звон возвратил меня к прошлому. rus_verbs:поступить{}, // К нам поступила жалоба. rus_verbs:поступать{}, // К нам поступают жалобы. rus_verbs:прыгнуть{}, // Белка прыгнула к дереву rus_verbs:торопиться{}, // пассажиры торопятся к выходу rus_verbs:поторопиться{}, // поторопитесь к выходу rus_verbs:вернуть{}, // вернуть к активной жизни rus_verbs:припирать{}, // припирать к стенке rus_verbs:проваливать{}, // Проваливай ко всем чертям! rus_verbs:вбежать{}, // Коля вбежал ко мне rus_verbs:вбегать{}, // Коля вбегал ко мне глагол:забегать{ вид:несоверш }, // Коля забегал ко мне rus_verbs:постучаться{}, // Коля постучался ко мне. rus_verbs:повести{}, // Спросил я озорного Антонио и повел его к дому rus_verbs:понести{}, // Мы понесли кота к ветеринару rus_verbs:принести{}, // Я принес кота к ветеринару rus_verbs:устремиться{}, // Мы устремились к ручью. rus_verbs:подводить{}, // Учитель подводил детей к аквариуму rus_verbs:следовать{}, // Я получил приказ следовать к месту нового назначения. rus_verbs:пригласить{}, // Я пригласил к себе товарищей. rus_verbs:собираться{}, // Я собираюсь к тебе в гости. rus_verbs:собраться{}, // Маша собралась к дантисту rus_verbs:сходить{}, // Я схожу к врачу. rus_verbs:идти{}, // Маша уверенно шла к Пете rus_verbs:измениться{}, // Основные индексы рынка акций РФ почти не изменились к закрытию. rus_verbs:отыграть{}, // Российский рынок акций отыграл падение к закрытию. rus_verbs:заканчивать{}, // Заканчивайте к обеду rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время rus_verbs:окончить{}, // rus_verbs:дозвониться{}, // Я не мог к вам дозвониться. глагол:прийти{}, инфинитив:прийти{}, // Антонио пришел к Элеонор rus_verbs:уйти{}, // Антонио ушел к Элеонор rus_verbs:бежать{}, // Антонио бежит к Элеонор rus_verbs:спешить{}, // Антонио спешит к Элеонор rus_verbs:скакать{}, // Антонио скачет к Элеонор rus_verbs:красться{}, // Антонио крадётся к Элеонор rus_verbs:поскакать{}, // беглецы поскакали к холмам rus_verbs:перейти{} // Антонио перешел к Элеонор } fact гл_предл { if context { Гл_К_Дат предлог:к{} *:*{ падеж:дат } } then return true } fact гл_предл { if context { Гл_К_Дат предлог:к{} @regex("[a-z]+[0-9]*") } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:к{} *:*{} } then return false,-5 } #endregion Предлог_К #region Предлог_ДЛЯ // ------------------- С ПРЕДЛОГОМ 'ДЛЯ' ---------------------- wordentry_set Гл_ДЛЯ_Род={ частица:нет{}, // для меня нет других путей. частица:нету{}, rus_verbs:ЗАДЕРЖАТЬ{}, // полиция может задержать их для выяснения всех обстоятельств и дальнейшего опознания. (ЗАДЕРЖАТЬ) rus_verbs:ДЕЛАТЬСЯ{}, // это делалось для людей (ДЕЛАТЬСЯ) rus_verbs:обернуться{}, // обернулась для греческого рынка труда банкротствами предприятий и масштабными сокращениями (обернуться) rus_verbs:ПРЕДНАЗНАЧАТЬСЯ{}, // Скорее всего тяжелый клинок вообще не предназначался для бросков (ПРЕДНАЗНАЧАТЬСЯ) rus_verbs:ПОЛУЧИТЬ{}, // ты можешь получить его для нас? (ПОЛУЧИТЬ) rus_verbs:ПРИДУМАТЬ{}, // Ваш босс уже придумал для нас веселенькую смерть. (ПРИДУМАТЬ) rus_verbs:оказаться{}, // это оказалось для них тяжелой задачей rus_verbs:ГОВОРИТЬ{}, // теперь она говорила для нас обоих (ГОВОРИТЬ) rus_verbs:ОСВОБОДИТЬ{}, // освободить ее для тебя? (ОСВОБОДИТЬ) rus_verbs:работать{}, // Мы работаем для тех, кто ценит удобство rus_verbs:СТАТЬ{}, // кем она станет для него? (СТАТЬ) rus_verbs:ЯВИТЬСЯ{}, // вы для этого явились сюда? (ЯВИТЬСЯ) rus_verbs:ПОТЕРЯТЬ{}, // жизнь потеряла для меня всякий смысл (ПОТЕРЯТЬ) rus_verbs:УТРАТИТЬ{}, // мой мир утратил для меня всякое подобие смысла (УТРАТИТЬ) rus_verbs:ДОСТАТЬ{}, // ты должен достать ее для меня! (ДОСТАТЬ) rus_verbs:БРАТЬ{}, // некоторые берут для себя (БРАТЬ) rus_verbs:ИМЕТЬ{}, // имею для вас новость (ИМЕТЬ) rus_verbs:ЖДАТЬ{}, // тебя ждут для разговора (ЖДАТЬ) rus_verbs:ПРОПАСТЬ{}, // совсем пропал для мира (ПРОПАСТЬ) rus_verbs:ПОДНЯТЬ{}, // нас подняли для охоты (ПОДНЯТЬ) rus_verbs:ОСТАНОВИТЬСЯ{}, // время остановилось для нее (ОСТАНОВИТЬСЯ) rus_verbs:НАЧИНАТЬСЯ{}, // для него начинается новая жизнь (НАЧИНАТЬСЯ) rus_verbs:КОНЧИТЬСЯ{}, // кончились для него эти игрушки (КОНЧИТЬСЯ) rus_verbs:НАСТАТЬ{}, // для него настало время действовать (НАСТАТЬ) rus_verbs:СТРОИТЬ{}, // для молодых строили новый дом (СТРОИТЬ) rus_verbs:ВЗЯТЬ{}, // возьми для защиты этот меч (ВЗЯТЬ) rus_verbs:ВЫЯСНИТЬ{}, // попытаюсь выяснить для вас всю цепочку (ВЫЯСНИТЬ) rus_verbs:ПРИГОТОВИТЬ{}, // давай попробуем приготовить для них сюрприз (ПРИГОТОВИТЬ) rus_verbs:ПОДХОДИТЬ{}, // берег моря мертвых подходил для этого идеально (ПОДХОДИТЬ) rus_verbs:ОСТАТЬСЯ{}, // внешний вид этих тварей остался для нас загадкой (ОСТАТЬСЯ) rus_verbs:ПРИВЕЗТИ{}, // для меня привезли пиво (ПРИВЕЗТИ) прилагательное:ХАРАКТЕРНЫЙ{}, // Для всей территории края характерен умеренный континентальный климат (ХАРАКТЕРНЫЙ) rus_verbs:ПРИВЕСТИ{}, // для меня белую лошадь привели (ПРИВЕСТИ ДЛЯ) rus_verbs:ДЕРЖАТЬ{}, // их держат для суда (ДЕРЖАТЬ ДЛЯ) rus_verbs:ПРЕДОСТАВИТЬ{}, // вьетнамец предоставил для мигрантов места проживания в ряде вологодских общежитий (ПРЕДОСТАВИТЬ ДЛЯ) rus_verbs:ПРИДУМЫВАТЬ{}, // придумывая для этого разнообразные причины (ПРИДУМЫВАТЬ ДЛЯ) rus_verbs:оставить{}, // или вообще решили оставить планету для себя rus_verbs:оставлять{}, rus_verbs:ВОССТАНОВИТЬ{}, // как ты можешь восстановить это для меня? (ВОССТАНОВИТЬ ДЛЯ) rus_verbs:ТАНЦЕВАТЬ{}, // а вы танцевали для меня танец семи покрывал (ТАНЦЕВАТЬ ДЛЯ) rus_verbs:ДАТЬ{}, // твой принц дал мне это для тебя! (ДАТЬ ДЛЯ) rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // мужчина из лагеря решил воспользоваться для передвижения рекой (ВОСПОЛЬЗОВАТЬСЯ ДЛЯ) rus_verbs:СЛУЖИТЬ{}, // они служили для разговоров (СЛУЖИТЬ ДЛЯ) rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // Для вычисления радиуса поражения ядерных взрывов используется формула (ИСПОЛЬЗОВАТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНЯТЬСЯ{}, // Применяется для изготовления алкогольных коктейлей (ПРИМЕНЯТЬСЯ ДЛЯ) rus_verbs:СОВЕРШАТЬСЯ{}, // Для этого совершался специальный магический обряд (СОВЕРШАТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНИТЬ{}, // а здесь попробуем применить ее для других целей. (ПРИМЕНИТЬ ДЛЯ) rus_verbs:ПОЗВАТЬ{}, // ты позвал меня для настоящей работы. (ПОЗВАТЬ ДЛЯ) rus_verbs:НАЧАТЬСЯ{}, // очередной денек начался для Любки неудачно (НАЧАТЬСЯ ДЛЯ) rus_verbs:ПОСТАВИТЬ{}, // вас здесь для красоты поставили? (ПОСТАВИТЬ ДЛЯ) rus_verbs:умереть{}, // или умерла для всяких чувств? (умереть для) rus_verbs:ВЫБРАТЬ{}, // ты сам выбрал для себя этот путь. (ВЫБРАТЬ ДЛЯ) rus_verbs:ОТМЕТИТЬ{}, // тот же отметил для себя другое. (ОТМЕТИТЬ ДЛЯ) rus_verbs:УСТРОИТЬ{}, // мы хотим устроить для них школу. (УСТРОИТЬ ДЛЯ) rus_verbs:БЫТЬ{}, // у меня есть для тебя работа. (БЫТЬ ДЛЯ) rus_verbs:ВЫЙТИ{}, // для всего нашего поколения так вышло. (ВЫЙТИ ДЛЯ) прилагательное:ВАЖНЫЙ{}, // именно твое мнение для нас крайне важно. (ВАЖНЫЙ ДЛЯ) прилагательное:НУЖНЫЙ{}, // для любого племени нужна прежде всего сила. (НУЖЕН ДЛЯ) прилагательное:ДОРОГОЙ{}, // эти места были дороги для них обоих. (ДОРОГОЙ ДЛЯ) rus_verbs:НАСТУПИТЬ{}, // теперь для больших людей наступило время действий. (НАСТУПИТЬ ДЛЯ) rus_verbs:ДАВАТЬ{}, // старый пень давал для этого хороший огонь. (ДАВАТЬ ДЛЯ) rus_verbs:ГОДИТЬСЯ{}, // доброе старое время годится лишь для воспоминаний. (ГОДИТЬСЯ ДЛЯ) rus_verbs:ТЕРЯТЬ{}, // время просто теряет для вас всякое значение. (ТЕРЯТЬ ДЛЯ) rus_verbs:ЖЕНИТЬСЯ{}, // настало время жениться для пользы твоего клана. (ЖЕНИТЬСЯ ДЛЯ) rus_verbs:СУЩЕСТВОВАТЬ{}, // весь мир перестал существовать для них обоих. (СУЩЕСТВОВАТЬ ДЛЯ) rus_verbs:ЖИТЬ{}, // жить для себя или жить для них. (ЖИТЬ ДЛЯ) rus_verbs:открыть{}, // двери моего дома всегда открыты для вас. (ОТКРЫТЫЙ ДЛЯ) rus_verbs:закрыть{}, // этот мир будет закрыт для них. (ЗАКРЫТЫЙ ДЛЯ) rus_verbs:ТРЕБОВАТЬСЯ{}, // для этого требуется огромное количество энергии. (ТРЕБОВАТЬСЯ ДЛЯ) rus_verbs:РАЗОРВАТЬ{}, // Алексей разорвал для этого свою рубаху. (РАЗОРВАТЬ ДЛЯ) rus_verbs:ПОДОЙТИ{}, // вполне подойдет для начала нашей экспедиции. (ПОДОЙТИ ДЛЯ) прилагательное:опасный{}, // сильный холод опасен для открытой раны. (ОПАСЕН ДЛЯ) rus_verbs:ПРИЙТИ{}, // для вас пришло очень важное сообщение. (ПРИЙТИ ДЛЯ) rus_verbs:вывести{}, // мы специально вывели этих животных для мяса. rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ) rus_verbs:оставаться{}, // механизм этого воздействия остается для меня загадкой. (остается для) rus_verbs:ЯВЛЯТЬСЯ{}, // Чай является для китайцев обычным ежедневным напитком (ЯВЛЯТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНЯТЬ{}, // Для оценок будущих изменений климата применяют модели общей циркуляции атмосферы. (ПРИМЕНЯТЬ ДЛЯ) rus_verbs:ПОВТОРЯТЬ{}, // повторяю для Пети (ПОВТОРЯТЬ ДЛЯ) rus_verbs:УПОТРЕБЛЯТЬ{}, // Краски, употребляемые для живописи (УПОТРЕБЛЯТЬ ДЛЯ) rus_verbs:ВВЕСТИ{}, // Для злостных нарушителей предложили ввести повышенные штрафы (ВВЕСТИ ДЛЯ) rus_verbs:найтись{}, // у вас найдется для него работа? rus_verbs:заниматься{}, // они занимаются этим для развлечения. (заниматься для) rus_verbs:заехать{}, // Коля заехал для обсуждения проекта rus_verbs:созреть{}, // созреть для побега rus_verbs:наметить{}, // наметить для проверки rus_verbs:уяснить{}, // уяснить для себя rus_verbs:нанимать{}, // нанимать для разовой работы rus_verbs:приспособить{}, // приспособить для удовольствия rus_verbs:облюбовать{}, // облюбовать для посиделок rus_verbs:прояснить{}, // прояснить для себя rus_verbs:задействовать{}, // задействовать для патрулирования rus_verbs:приготовлять{}, // приготовлять для проверки инфинитив:использовать{ вид:соверш }, // использовать для достижения цели инфинитив:использовать{ вид:несоверш }, глагол:использовать{ вид:соверш }, глагол:использовать{ вид:несоверш }, прилагательное:использованный{}, деепричастие:используя{}, деепричастие:использовав{}, rus_verbs:напрячься{}, // напрячься для решительного рывка rus_verbs:одобрить{}, // одобрить для использования rus_verbs:одобрять{}, // одобрять для использования rus_verbs:пригодиться{}, // пригодиться для тестирования rus_verbs:готовить{}, // готовить для выхода в свет rus_verbs:отобрать{}, // отобрать для участия в конкурсе rus_verbs:потребоваться{}, // потребоваться для подтверждения rus_verbs:пояснить{}, // пояснить для слушателей rus_verbs:пояснять{}, // пояснить для экзаменаторов rus_verbs:понадобиться{}, // понадобиться для обоснования инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована для условий крайнего севера инфинитив:адаптировать{вид:соверш}, глагол:адаптировать{вид:несоверш}, глагол:адаптировать{вид:соверш}, деепричастие:адаптировав{}, деепричастие:адаптируя{}, прилагательное:адаптирующий{}, прилагательное:адаптировавший{ вид:соверш }, //+прилагательное:адаптировавший{ вид:несоверш }, прилагательное:адаптированный{}, rus_verbs:найти{}, // Папа нашел для детей няню прилагательное:вредный{}, // Это вредно для здоровья. прилагательное:полезный{}, // Прогулки полезны для здоровья. прилагательное:обязательный{}, // Этот пункт обязателен для исполнения прилагательное:бесполезный{}, // Это лекарство бесполезно для него прилагательное:необходимый{}, // Это лекарство необходимо для выздоровления rus_verbs:создать{}, // Он не создан для этого дела. прилагательное:сложный{}, // задача сложна для младших школьников прилагательное:несложный{}, прилагательное:лёгкий{}, прилагательное:сложноватый{}, rus_verbs:становиться{}, rus_verbs:представлять{}, // Это не представляет для меня интереса. rus_verbs:значить{}, // Я рос в деревне и хорошо знал, что для деревенской жизни значат пруд или речка rus_verbs:пройти{}, // День прошёл спокойно для него. rus_verbs:проходить{}, rus_verbs:высадиться{}, // большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ rus_verbs:высаживаться{}, rus_verbs:прибавлять{}, // Он любит прибавлять для красного словца. rus_verbs:прибавить{}, rus_verbs:составить{}, // Ряд тригонометрических таблиц был составлен для астрономических расчётов. rus_verbs:составлять{}, rus_verbs:стараться{}, // Я старался для вас rus_verbs:постараться{}, // Я постарался для вас rus_verbs:сохраниться{}, // Старик хорошо сохранился для своего возраста. rus_verbs:собраться{}, // собраться для обсуждения rus_verbs:собираться{}, // собираться для обсуждения rus_verbs:уполномочивать{}, rus_verbs:уполномочить{}, // его уполномочили для ведения переговоров rus_verbs:принести{}, // Я принёс эту книгу для вас. rus_verbs:делать{}, // Я это делаю для удовольствия. rus_verbs:сделать{}, // Я сделаю это для удовольствия. rus_verbs:подготовить{}, // я подготовил для друзей сюрприз rus_verbs:подготавливать{}, // я подготавливаю для гостей новый сюрприз rus_verbs:закупить{}, // Руководство района обещало закупить новые комбайны для нашего села rus_verbs:купить{}, // Руководство района обещало купить новые комбайны для нашего села rus_verbs:прибыть{} // они прибыли для участия } fact гл_предл { if context { Гл_ДЛЯ_Род предлог:для{} *:*{ падеж:род } } then return true } fact гл_предл { if context { Гл_ДЛЯ_Род предлог:для{} @regex("[a-z]+[0-9]*") } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:для{} *:*{} } then return false,-4 } #endregion Предлог_ДЛЯ #region Предлог_ОТ // попробуем иную стратегию - запретить связывание с ОТ для отдельных глаголов, разрешив для всех остальных. wordentry_set Глаг_ОТ_Род_Запр= { rus_verbs:наслаждаться{}, // свободой от обязательств rus_verbs:насладиться{}, rus_verbs:мочь{}, // Он не мог удержаться от смеха. // rus_verbs:хотеть{}, rus_verbs:желать{}, rus_verbs:чувствовать{}, // все время от времени чувствуют его. rus_verbs:планировать{}, rus_verbs:приняться{} // мы принялись обниматься от радости. } fact гл_предл { if context { Глаг_ОТ_Род_Запр предлог:от{} * } then return false } #endregion Предлог_ОТ #region Предлог_БЕЗ /* // запретить связывание с БЕЗ для отдельных глаголов, разрешив для всех остальных. wordentry_set Глаг_БЕЗ_Род_Запр= { rus_verbs:мочь{}, // Он мог читать часами без отдыха. rus_verbs:хотеть{}, rus_verbs:желать{}, rus_verbs:планировать{}, rus_verbs:приняться{} } fact гл_предл { if context { Глаг_БЕЗ_Род_Запр предлог:без{} * } then return false } */ #endregion Предлог_БЕЗ #region Предлог_КРОМЕ fact гл_предл { if context { * ПредлогДляВсе * } then return false,-5 } #endregion Предлог_КРОМЕ // ------------------------------------ // По умолчанию разрешаем все остальные сочетания. fact гл_предл { if context { * * * } then return true }
протискиваться в аудиторию
rus_verbs:протискиваться{},
5,482,933
[ 1, 145, 128, 146, 227, 145, 127, 146, 229, 145, 121, 146, 228, 145, 123, 145, 121, 145, 115, 145, 113, 146, 229, 146, 239, 146, 228, 146, 242, 225, 145, 115, 225, 145, 113, 146, 230, 145, 117, 145, 121, 146, 229, 145, 127, 146, 227, 145, 121, 146, 241, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 436, 407, 67, 502, 2038, 30, 145, 128, 146, 227, 145, 127, 146, 229, 145, 121, 146, 228, 145, 123, 145, 121, 145, 115, 145, 113, 146, 229, 146, 239, 146, 228, 146, 242, 2916, 16, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x831b33eC64055f93cd01a5a2e1b6e2c8b17b976C/sources/localhost/DMiner/IDMexVendorStorage.sol
power of each shard(Unit is GB)
uint256 power;
16,557,411
[ 1, 12238, 434, 1517, 5820, 12, 2802, 353, 25069, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 377, 7212, 31, 9079, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; contract Charity { enum CharityStatus {UNVERIFIED, VERIFIED, REJECTED} enum CampaignStatus {ONGOING, ENDED} struct charity { address charityOwner; string charityName; string charityAddress; string contactNumber; string description; string pictureURL; string verificationLink; CharityStatus charityStatus; address[] donors; } struct campaign { uint256 charityId; string campaignName; string description; string pictureURL; uint256 targetDonation; uint256 currentDonation; uint256 noOfDonors; uint256 startDate; uint256 endDate; CampaignStatus campaignStatus; } address contractOwner = msg.sender; mapping(uint256 => bool) isVerifiedCharity; mapping(uint256 => charity) charities; mapping(address => uint256) charityAddressIdMap; mapping(address => charity) charityAddressMap; mapping(address => bool) charityOwnerRegistered; address[] donors; uint256 noOfCharities = 0; uint contractMoney = 0; uint256 charityRegFee = 5 * 10**17; // Reg fee is 0.5 ether, 1 ether is 10**18 wei mapping(uint256 => bool) isOngoingCampaign; mapping(uint256 => campaign) campaigns; uint256 noOfCampaigns = 0; uint256 noOfReturns = 0; modifier onlyOwner(address caller) { require(caller == contractOwner, "Caller is not contract owner"); _; } // This will be the modifier that checks whether the function call is done by the Charity itself. modifier onlyVerifiedCharity(address caller) { require( isVerifiedCharity[charityAddressIdMap[caller]], "Caller is not a valid charity" ); _; } // This will be the modifier that checks whether the function call is done by the Charity or contract owner itself. modifier onlyVerifiedCharityOrOwner(address caller) { require( isVerifiedCharity[charityAddressIdMap[caller]] || caller == contractOwner, "Caller is not a valid charity nor contract owner" ); _; } /* * This will be the function that check the address type * Parameters of this function will include address inputAddress * This function assumes all input address are either contract, charity, or donor */ function checkAddressType( address inputAddress ) public view returns (string memory) { if (inputAddress == contractOwner) { return "CONTRACT"; } else if (charityOwnerRegistered[inputAddress] == true) { return "CHARITYOWNER"; } else { return "DONOR"; } } /* * This will be the function that allows contract owner to withdraw money * There will be no parameters for this function */ function withdrawMoney() public onlyOwner(msg.sender) { require(contractMoney >= 3 * charityRegFee, "Current money is less than 3 * charity register fee"); address payable recipient = address(uint160(address(this))); recipient.transfer(contractMoney); contractMoney = 0; } /* * This fallback function is to make contract address able to receive/make payments */ function() external payable { } /* * This will be the payable function to register the charity * Parameters will be string charityName, string charityAddress, string contactNumber, string description and string pictureURL * Need at least 0.5 ether to register */ function registerCharity( string memory charityName, string memory charityAddress, string memory contactNumber, string memory description, string memory pictureURL ) public payable returns (uint256 charityId) { require( charityOwnerRegistered[msg.sender] == false, "This address has registered another charity already" ); require( msg.value >= charityRegFee, "Need at least 0.5 ether to register a charity" ); contractMoney = contractMoney + msg.value; charityId = noOfCharities++; charity memory newCharity = charity( msg.sender, charityName, charityAddress, contactNumber, description, pictureURL, "", CharityStatus.UNVERIFIED, donors ); charities[charityId] = newCharity; charityAddressIdMap[msg.sender] = charityId; isVerifiedCharity[charityId] = false; charityOwnerRegistered[msg.sender] = true; address payable recipient = address(uint160(contractOwner)); recipient.transfer(msg.value); return charityId; } /* * This will be the function for contract owner to verify the charity * Parameters will be uint charityId, string verification */ function verifyCharity( uint256 charityId, string memory verificationLink ) public onlyOwner(msg.sender) { require(msg.sender == contractOwner, "Caller is not contract owner"); require(charityId < noOfCharities, "Invalid charity id"); require( charities[charityId].charityStatus == CharityStatus.UNVERIFIED, "Charity has been verified or rejected" ); require( isVerifiedCharity[charityId] == false, "Charity has been verified" ); charities[charityId].charityStatus = CharityStatus.VERIFIED; charities[charityId].verificationLink = verificationLink; isVerifiedCharity[charityId] = true; } /* * This will be the function for contract owner to reject the charity * Parameters will be uint charityId, string verification */ function rejectCharity( uint256 charityId ) public onlyOwner(msg.sender) { require(msg.sender == contractOwner, "Caller is not contract owner"); require(charityId < noOfCharities, "Invalid charity id"); require( charities[charityId].charityStatus == CharityStatus.UNVERIFIED, "Charity has been verified or rejected" ); require( isVerifiedCharity[charityId] == false, "Charity has been verified" ); charities[charityId].charityStatus = CharityStatus.REJECTED; } /* * This will be the function for contract owner to revoke the charity * Parameters will be uint charityId, string verification */ function revokeCharity( uint256 charityId ) public onlyOwner(msg.sender) { require(charityId < noOfCharities, "Invalid charity id"); require( charities[charityId].charityStatus == CharityStatus.VERIFIED, "Charity is not a verified charity" ); charities[charityId].charityStatus = CharityStatus.REJECTED; } /* * This will be the function that charities call to create a campaign. * Parameters of this function will include string campaignName, string description, string pictureURL, uint targetDonation (of the campaign), uint startDate (of the campaign), uint endDate (of the campaign) */ function createCampaign( string memory campaignName, string memory description, string memory pictureURL, uint256 targetDonation, uint256 startDate, uint256 endDate ) public onlyVerifiedCharity(msg.sender) returns (uint256 campaignId) { campaignId = noOfCampaigns++; uint256 charityId = charityAddressIdMap[msg.sender]; campaign memory newCampaign = campaign( charityId, campaignName, description, pictureURL, targetDonation, 0, 0, startDate, endDate, CampaignStatus.ONGOING ); campaigns[campaignId] = newCampaign; isOngoingCampaign[campaignId] = true; return campaignId; } /* * This will be the function that charities or contract owner call to end an ongoing campaign. * Parameters of this function will include uint campaignId */ function endCampaign( uint256 campaignId ) public onlyVerifiedCharityOrOwner(msg.sender) { require(campaignId < noOfCampaigns, "Invalid campaign id"); require(isOngoingCampaign[campaignId], "Campaign is not ongoing"); require( msg.sender == charities[campaigns[campaignId].charityId].charityOwner || msg.sender == contractOwner, "Caller is not authorized for this operation" ); campaigns[campaignId].campaignStatus = CampaignStatus.ENDED; isOngoingCampaign[campaignId] = false; } /* * This will be the getter function that everyone can call to check the charity address. * Parameters of this function will include uint charityId */ function getCharityOwner( uint256 charityId ) public view returns (address) { require(charityId < noOfCharities, "Invalid charity id"); return charities[charityId].charityOwner; } /* * This will be the getter function that everyone can call to check the charity id. * Parameters of this function will include address inputAddress */ function getCharityIdByAddress( address inputAddress ) public view returns (uint256) { require( charityOwnerRegistered[inputAddress] == true, "Address not owner of any charity" ); uint256 charityIdByAddress = charityAddressIdMap[inputAddress]; return charityIdByAddress; } /* * This will be the getter function that everyone can call to check the charity name. * Parameters of this function will include uint charityId */ function getCharityName( uint256 charityId ) public view returns (string memory) { require(charityId < noOfCharities, "Invalid charity id"); return charities[charityId].charityName; } /* * This will be the getter function that everyone can call to check the charity pictureURL. * Parameters of this function will include uint charityId */ function getCharityPictureURL( uint256 charityId ) public view returns (string memory) { require(charityId < noOfCharities, "Invalid charity id"); return charities[charityId].pictureURL; } /* * This will be the getter function that everyone can call to check the charity pictureURL. * Parameters of this function will include address inputAddress */ function getCharityPictureURLByAddress(address inputAddress) public view returns (string memory) { require( charityOwnerRegistered[inputAddress] == true, "Address not owner of any charity" ); uint256 charityIdByAddress = charityAddressIdMap[inputAddress]; return charities[charityIdByAddress].pictureURL; } /* * This will be the getter function that everyone can call to check the charity description. * Parameters of this function will include uint charityId */ function getCharityDescription( uint256 charityId ) public view returns (string memory) { require(charityId < noOfCharities, "Invalid charity id"); return charities[charityId].description; } /* * This will be the getter function that everyone can call to check the charity status. * Parameters of this function will include uint charityId */ function getCharityStatus( uint256 charityId ) public view returns (CharityStatus) { require(charityId < noOfCharities, "Invalid charity id"); return charities[charityId].charityStatus; } /* * This will be the getter function that everyone can call to check the charity status. * Parameters of this function will include address inputAddress */ function getCharityStatusByAddress( address inputAddress ) public view returns (CharityStatus) { require( charityOwnerRegistered[inputAddress] == true, "Address not owner of any charity" ); uint256 charityIdByAddress = charityAddressIdMap[inputAddress]; return charities[charityIdByAddress].charityStatus; } /* * This will be the getter function that everyone can call to get the charity contact number. * Parameters of this function will include uint charityId */ function getCharityContactNumber( uint256 charityId ) public view returns (string memory) { require(charityId < noOfCharities, "Invalid charity id"); return charities[charityId].contactNumber; } /* * This will be the getter function that everyone can call to get the charity contact address. * Parameters of this function will include uint charityId */ function getCharityContactAddress( uint256 charityId ) public view returns (string memory) { require(charityId < noOfCharities, "Invalid charity id"); return charities[charityId].charityAddress; } /* * This will be the getter function that everyone can call to get the charity verification Link. * Parameters of this function will include uint charityId */ function getCharityVerificationLink( uint256 charityId ) public view returns (string memory) { require(charityId < noOfCharities, "Invalid charity id"); return charities[charityId].verificationLink; } /* * This will be the getter function that everyone can call to get the total amounts of the charities. * There will be no parameters for this function */ function getNoOfCharities() public view returns (uint256) { return noOfCharities; } /* * This will be the getter function that everyone can call to check the campaign's charityId. * Parameters of this function will include uint campaignId */ function getCampaignCharity( uint256 campaignId ) public view returns (uint256) { require(campaignId < noOfCampaigns, "Invalid campaign id"); return campaigns[campaignId].charityId; } /* * This will be the getter function that everyone can call to check the campaign name. * Parameters of this function will include uint campaignId */ function getCampaignName( uint256 campaignId ) public view returns (string memory) { require(campaignId < noOfCampaigns, "Invalid campaign id"); return campaigns[campaignId].campaignName; } /* * This will be the getter function that everyone can call to check the campaign description. * Parameters of this function will include uint campaignId */ function getCampaignDescription( uint256 campaignId ) public view returns (string memory) { require(campaignId < noOfCampaigns, "Invalid campaign id"); return campaigns[campaignId].description; } /* * This will be the getter function that everyone can call to check the campaign pictureURL. * Parameters of this function will include uint campaignId */ function getCampaignPictureURL( uint256 campaignId ) public view returns (string memory) { require(campaignId < noOfCampaigns, "Invalid campaign id"); return campaigns[campaignId].pictureURL; } /* * This will be the getter function that everyone can call to check the campaign targetDonation. * Parameters of this function will include uint campaignId */ function getCampaignTargetDonation( uint256 campaignId ) public view returns (uint256) { require(campaignId < noOfCampaigns, "Invalid campaign id"); return campaigns[campaignId].targetDonation; } /* * This will be the getter function that everyone can call to check the campaign currentDonation. * Parameters of this function will include uint campaignId */ function getCampaignCurrentDonation( uint256 campaignId ) public view returns (uint256) { require(campaignId < noOfCampaigns, "Invalid campaign id"); return campaigns[campaignId].currentDonation; } /* * This will be the getter function that everyone can call to check the campaign noOfDonors. * Parameters of this function will include uint campaignId */ function getCampaignNoOfDonors( uint256 campaignId ) public view returns (uint256) { require(campaignId < noOfCampaigns, "Invalid campaign id"); return campaigns[campaignId].noOfDonors; } /* * This will be the getter function that everyone can call to check the campaign startDate. * Parameters of this function will include uint campaignId */ function getCampaignStartDate( uint256 campaignId ) public view returns (uint256) { require(campaignId < noOfCampaigns, "Invalid campaign id"); return campaigns[campaignId].startDate; } /* * This will be the getter function that everyone can call to check the campaign endDate. * Parameters of this function will include uint campaignId */ function getCampaignEndDate( uint256 campaignId ) public view returns (uint256) { require(campaignId < noOfCampaigns, "Invalid campaign id"); return campaigns[campaignId].endDate; } /* * This will be the getter function that everyone can call to check the campaign status. * Parameters of this function will include uint campaignId */ function getCampaignStatus( uint256 campaignId ) public view returns (CampaignStatus) { require(campaignId < noOfCampaigns, "Invalid campaign id"); return campaigns[campaignId].campaignStatus; } /* * This will be the getter function that everyone can call to get the total amounts of the campaigns. * There will be no parameters fot this function */ function getNoOfCampaigns() public view returns (uint256) { return noOfCampaigns; } /* *This will be the getter function that everyone can call to check the status of the campaign. * Parameters of this function will include uint campaignId */ function isStatusComplete( uint256 campaignId ) public view returns (bool) { require(campaignId < noOfCampaigns, "Invalid campaign id"); if (campaigns[campaignId].campaignStatus == CampaignStatus.ENDED) { return true; } return false; } /* *This will be the getter function that everyone can call to check if the campagin is valid * Parameters of this function will include uint campaignId */ function checkValidCampaign( uint256 campaignId ) public view returns (bool) { if (campaignId < noOfCampaigns) { return true; } return false; } /* * This will be the function that updates the campaign's currentDonation * Parameters of this function will include uint campaignId and uint newDonation */ function updateCampaignCurrentDonation( uint256 campaignId, uint256 newDonation ) public { require(campaignId < noOfCampaigns, "Invalid campaign id"); uint256 newAmount = campaigns[campaignId].currentDonation + newDonation; campaigns[campaignId].currentDonation = newAmount; } /* * This will be the function that updates the campaign's noOfDonors * Parameters of this function will include uint campaignId */ function addCampaignDonor( uint256 campaignId ) public { require(campaignId < noOfCampaigns, "Invalid campaign id"); uint256 newNumber = campaigns[campaignId].noOfDonors + 1; campaigns[campaignId].noOfDonors = newNumber; } /* * This will be the function that returns the charity's donors * Parameters of this function will include uint campaignId */ function getDonors( uint256 charityId ) public view returns(address[] memory) { address[] memory donorList = charities[charityId].donors; return donorList; } /* * This will be the function that get charity register fee * There will be no parameters for this function */ function getRegFee() public view returns(uint256) { return charityRegFee; } /* * This will be the function to get contract's owner * There will be no parameters for this function */ function getContractOwner() public view returns (address) { return contractOwner; } /* * This will be the function to check if donor has donated to charity before * Parameters of this function will include address donor, uint charityId */ function checkCharityDonor( address donor, uint256 charityId ) public view returns (bool) { uint length = charities[charityId].donors.length; for (uint i = 0; i < length; i++) { if(charities[charityId].donors[i] == donor) { return true; } } return false; } /* * This will be the function to add a new donor to charity * Parameters of this function will include address donor, uint charityId */ function addCharityDonor( address donor, uint256 charityId ) public { charities[charityId].donors.push(donor); } }
This will be the getter function that everyone can call to check the status of the campaign. Parameters of this function will include uint campaignId/
function isStatusComplete( uint256 campaignId ) public view returns (bool) { require(campaignId < noOfCampaigns, "Invalid campaign id"); if (campaigns[campaignId].campaignStatus == CampaignStatus.ENDED) { return true; } return false; }
6,449,594
[ 1, 2503, 903, 506, 326, 7060, 445, 716, 3614, 476, 848, 745, 358, 866, 326, 1267, 434, 326, 8965, 18, 7012, 434, 333, 445, 903, 2341, 2254, 8965, 548, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 353, 1482, 6322, 12, 203, 3639, 2254, 5034, 8965, 548, 203, 565, 262, 7010, 3639, 1071, 7010, 3639, 1476, 7010, 3639, 1135, 261, 6430, 13, 7010, 565, 288, 203, 3639, 2583, 12, 14608, 548, 411, 1158, 951, 13432, 87, 16, 315, 1941, 8965, 612, 8863, 203, 3639, 309, 261, 14608, 87, 63, 14608, 548, 8009, 14608, 1482, 422, 17820, 1482, 18, 22088, 13, 288, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 3639, 327, 629, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x94b34CcD6b6E39cF589d5be20B417e991FA86d1D/sources/contracts/CYAN.sol
Get current interval
uint256 currentTime = (block.timestamp / (INTEREST_INTERVAL));
8,339,682
[ 1, 967, 783, 3673, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 6680, 273, 261, 2629, 18, 5508, 342, 261, 9125, 11027, 67, 16435, 10019, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0x7f9634F2F2bBF19A6b22d976A219A780c9F8975e/sources/project_/contracts/poolStorage.sol
Current number of loans. Mapping of loanId to loan information.poolId => loanId => LoanState
abstract contract poolStorage { using EnumerableSet for EnumerableSet.UintSet; uint256 public loanId = 0; mapping(uint256 => Loan) public loans; mapping(uint256 => uint256) public poolLoans; enum LoanState { PENDING, CANCELLED, ACCEPTED, PAID } struct Payment { uint256 principal; uint256 interest; } struct LoanDetails { ERC20 lendingToken; uint256 principal; Payment totalRepaid; uint32 timestamp; uint32 acceptedTimestamp; uint32 lastRepaidTimestamp; uint32 loanDuration; } struct Terms { uint256 paymentCycleAmount; uint256 monthlyCycleInterest; uint32 paymentCycle; uint16 APR; uint32 installments; uint32 installmentsPaid; } struct Loan { address borrower; address receiver; address lender; uint256 poolId; LoanDetails loanDetails; Terms terms; LoanState state; } mapping(uint256 => uint32) public loanDefaultDuration; mapping(uint256 => uint32) public loanExpirationDuration; mapping(address => EnumerableSet.UintSet) internal borrowerActiveLoans; mapping(address => uint256) public totalERC20Amount; mapping(address => uint256[]) public borrowerLoans; mapping(address => mapping(address => uint256)) public lenderLendAmount; }
3,269,762
[ 1, 3935, 1300, 434, 437, 634, 18, 9408, 434, 28183, 548, 358, 28183, 1779, 18, 6011, 548, 516, 28183, 548, 516, 3176, 304, 1119, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 17801, 6835, 2845, 3245, 288, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 5487, 694, 31, 203, 565, 2254, 5034, 1071, 28183, 548, 273, 374, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 3176, 304, 13, 1071, 437, 634, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 2845, 1504, 634, 31, 203, 203, 203, 565, 2792, 3176, 304, 1119, 288, 203, 3639, 28454, 16, 203, 3639, 29641, 6687, 16, 203, 3639, 12048, 1441, 27222, 16, 203, 3639, 15662, 734, 203, 565, 289, 203, 203, 565, 1958, 12022, 288, 203, 3639, 2254, 5034, 8897, 31, 203, 3639, 2254, 5034, 16513, 31, 203, 565, 289, 203, 203, 565, 1958, 3176, 304, 3790, 288, 203, 3639, 4232, 39, 3462, 328, 2846, 1345, 31, 203, 3639, 2254, 5034, 8897, 31, 203, 3639, 12022, 2078, 426, 29434, 31, 203, 3639, 2254, 1578, 2858, 31, 203, 3639, 2254, 1578, 8494, 4921, 31, 203, 3639, 2254, 1578, 1142, 426, 29434, 4921, 31, 203, 3639, 2254, 1578, 28183, 5326, 31, 203, 565, 289, 203, 203, 565, 1958, 26563, 288, 203, 3639, 2254, 5034, 5184, 13279, 6275, 31, 203, 3639, 2254, 5034, 31114, 13279, 29281, 31, 203, 3639, 2254, 1578, 5184, 13279, 31, 203, 3639, 2254, 2313, 432, 8025, 31, 203, 3639, 2254, 1578, 3799, 1346, 31, 203, 3639, 2254, 1578, 3799, 1346, 16507, 350, 31, 203, 565, 289, 203, 203, 565, 1958, 3176, 304, 288, 203, 3639, 1758, 29759, 264, 31, 203, 3639, 1758, 5971, 31, 203, 3639, 1758, 328, 2345, 31, 203, 2 ]
./partial_match/56/0xD4590D2c88fa26004a5cBb67ef3487f082177366/sources/StrategypokeLP.sol
* @dev Core function of the strat, in charge of collecting and re-investing rewards. 1. It claims rewards from the ShareRewardPool. 2. It charges the system fees to simplify the split. 3. It swaps the {poke} token for {lpToken0} & {lpToken1} 4. Adds more liquidity to the pool. 5. It deposits the new LP tokens./
function harvest() external whenNotPaused { if (degen == true) require( flp.balanceOf(msg.sender) > 0, "You need falopa in your life" ); require(!Address.isContract(msg.sender), "!contract"); IShareRewardPool(shareRewardPool).claimReward(poolId); chargeFees(); addLiquidity(); deposit(); emit StratHarvest(msg.sender); }
11,178,945
[ 1, 4670, 445, 434, 326, 609, 270, 16, 316, 13765, 434, 30160, 471, 283, 17, 5768, 10100, 283, 6397, 18, 404, 18, 2597, 11955, 283, 6397, 628, 326, 25805, 17631, 1060, 2864, 18, 576, 18, 2597, 1149, 2852, 326, 2619, 1656, 281, 358, 16499, 326, 1416, 18, 890, 18, 2597, 1352, 6679, 326, 288, 84, 3056, 97, 1147, 364, 288, 9953, 1345, 20, 97, 473, 288, 9953, 1345, 21, 97, 1059, 18, 15605, 1898, 4501, 372, 24237, 358, 326, 2845, 18, 1381, 18, 2597, 443, 917, 1282, 326, 394, 511, 52, 2430, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 17895, 26923, 1435, 3903, 1347, 1248, 28590, 288, 203, 3639, 309, 261, 323, 4507, 422, 638, 13, 203, 5411, 2583, 12, 203, 7734, 1183, 84, 18, 12296, 951, 12, 3576, 18, 15330, 13, 405, 374, 16, 203, 7734, 315, 6225, 1608, 284, 287, 556, 69, 316, 3433, 17140, 6, 203, 5411, 11272, 203, 3639, 2583, 12, 5, 1887, 18, 291, 8924, 12, 3576, 18, 15330, 3631, 17528, 16351, 8863, 203, 3639, 467, 9535, 17631, 1060, 2864, 12, 14419, 17631, 1060, 2864, 2934, 14784, 17631, 1060, 12, 6011, 548, 1769, 203, 3639, 13765, 2954, 281, 5621, 203, 3639, 527, 48, 18988, 24237, 5621, 203, 3639, 443, 1724, 5621, 203, 203, 3639, 3626, 3978, 270, 44, 297, 26923, 12, 3576, 18, 15330, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x8Ff4b4c84940092eee58BC3583dF417489B64F27/sources/browser/ERC1363PayableCrowdsale.sol
* @return the address where funds are collected./
function wallet() public view returns (address) { return _wallet; }
12,367,984
[ 1, 2463, 326, 1758, 1625, 284, 19156, 854, 12230, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9230, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 19177, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x7ab609160F6D0f1D1d367635692E5a7CEA6cB136/sources/TKN.sol
public variables of the token reachable if max amount raised
contract TKN is StandardToken { string public constant name = "Tanveer Khan"; string public constant symbol = "TKN"; uint256 public constant decimals = 18; address mainWallet; modifier onlyMainWallet{ require(msg.sender == mainWallet); _; } function TKN() public { totalSupply = 100000000e18; mainWallet = msg.sender; balances[mainWallet] = totalSupply; } modifier onlyOwner() { require(msg.sender == mainWallet); _; } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(mainWallet, newOwner); balances[newOwner]=balances[mainWallet]; balances[mainWallet] = 0; mainWallet = newOwner; } function sendBatchCS(address[] _recipients, uint[] _values) external returns (bool) { require(_recipients.length == _values.length); uint senderBalance = balances[msg.sender]; for (uint i = 0; i < _values.length; i++) { uint value = _values[i]; address to = _recipients[i]; require(senderBalance >= value); if(msg.sender != _recipients[i]){ senderBalance = senderBalance - value; balances[to] += value; } Transfer(msg.sender, to, value); } balances[msg.sender] = senderBalance; return true; } function sendBatchCS(address[] _recipients, uint[] _values) external returns (bool) { require(_recipients.length == _values.length); uint senderBalance = balances[msg.sender]; for (uint i = 0; i < _values.length; i++) { uint value = _values[i]; address to = _recipients[i]; require(senderBalance >= value); if(msg.sender != _recipients[i]){ senderBalance = senderBalance - value; balances[to] += value; } Transfer(msg.sender, to, value); } balances[msg.sender] = senderBalance; return true; } function sendBatchCS(address[] _recipients, uint[] _values) external returns (bool) { require(_recipients.length == _values.length); uint senderBalance = balances[msg.sender]; for (uint i = 0; i < _values.length; i++) { uint value = _values[i]; address to = _recipients[i]; require(senderBalance >= value); if(msg.sender != _recipients[i]){ senderBalance = senderBalance - value; balances[to] += value; } Transfer(msg.sender, to, value); } balances[msg.sender] = senderBalance; return true; } }
5,274,230
[ 1, 482, 3152, 434, 326, 1147, 19234, 309, 943, 3844, 11531, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 399, 47, 50, 353, 8263, 1345, 288, 203, 377, 203, 203, 203, 565, 533, 1071, 5381, 508, 273, 315, 56, 304, 537, 264, 1475, 25842, 14432, 203, 565, 533, 1071, 5381, 3273, 273, 315, 56, 47, 50, 14432, 203, 565, 2254, 5034, 1071, 5381, 15105, 273, 6549, 31, 203, 377, 203, 27699, 203, 203, 565, 1758, 2774, 16936, 31, 203, 203, 203, 565, 9606, 1338, 6376, 16936, 95, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 2774, 16936, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 399, 47, 50, 1435, 1071, 288, 203, 3639, 2078, 3088, 1283, 273, 2130, 9449, 73, 2643, 31, 203, 3639, 2774, 16936, 273, 1234, 18, 15330, 31, 203, 3639, 324, 26488, 63, 5254, 16936, 65, 273, 2078, 3088, 1283, 31, 203, 540, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 2774, 16936, 1769, 203, 565, 389, 31, 203, 225, 289, 203, 203, 282, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 225, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1338, 5541, 1071, 288, 203, 565, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 10019, 203, 565, 14223, 9646, 5310, 1429, 4193, 12, 5254, 16936, 16, 394, 5541, 1769, 203, 565, 324, 26488, 63, 2704, 5541, 65, 33, 70, 26488, 63, 5254, 16936, 15533, 203, 565, 324, 26488, 63, 5254, 16936, 65, 273, 374, 31, 203, 565, 2774, 16936, 273, 394, 5541, 2 ]
// File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); 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 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 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 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: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.2; /** * @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. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice 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 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: set-protocol-contracts/contracts/lib/TimeLockUpgrade.sol /* 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.5.7; /** * @title TimeLockUpgrade * @author Set Protocol * * The TimeLockUpgrade contract contains a modifier for handling minimum time period updates */ contract TimeLockUpgrade is Ownable { using SafeMath for uint256; /* ============ State Variables ============ */ // Timelock Upgrade Period in seconds uint256 public timeLockPeriod; // Mapping of upgradable units and initialized timelock mapping(bytes32 => uint256) public timeLockedUpgrades; /* ============ Events ============ */ event UpgradeRegistered( bytes32 _upgradeHash, uint256 _timestamp ); /* ============ Modifiers ============ */ modifier timeLockUpgrade() { // If the time lock period is 0, then allow non-timebound upgrades. // This is useful for initialization of the protocol and for testing. if (timeLockPeriod == 0) { _; return; } // The upgrade hash is defined by the hash of the transaction call data, // which uniquely identifies the function as well as the passed in arguments. bytes32 upgradeHash = keccak256( abi.encodePacked( msg.data ) ); uint256 registrationTime = timeLockedUpgrades[upgradeHash]; // If the upgrade hasn't been registered, register with the current time. if (registrationTime == 0) { timeLockedUpgrades[upgradeHash] = block.timestamp; emit UpgradeRegistered( upgradeHash, block.timestamp ); return; } require( block.timestamp >= registrationTime.add(timeLockPeriod), "TimeLockUpgrade: Time lock period must have elapsed." ); // Reset the timestamp to 0 timeLockedUpgrades[upgradeHash] = 0; // Run the rest of the upgrades _; } /* ============ Function ============ */ /** * Change timeLockPeriod period. Generally called after initially settings have been set up. * * @param _timeLockPeriod Time in seconds that upgrades need to be evaluated before execution */ function setTimeLockPeriod( uint256 _timeLockPeriod ) external onlyOwner { // Only allow setting of the timeLockPeriod if the period is greater than the existing require( _timeLockPeriod > timeLockPeriod, "TimeLockUpgrade: New period must be greater than existing" ); timeLockPeriod = _timeLockPeriod; } } // File: contracts/meta-oracles/lib/DataSourceLinearInterpolationLibrary.sol /* Copyright 2019 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.5.7; /** * @title LinearInterpolationLibrary * @author Set Protocol * * Library used to determine linearly interpolated value for DataSource contracts when TimeSeriesFeed * is updated after interpolationThreshold has passed. */ library DataSourceLinearInterpolationLibrary { using SafeMath for uint256; /* ============ External ============ */ /* * When the update time has surpassed the currentTime + interpolationThreshold, linearly interpolate the * price between the current time and price and the last updated time and price to reduce potential error. This * is done with the following series of equations, modified in this instance to deal unsigned integers: * * price = (currentPrice * updateInterval + previousLoggedPrice * timeFromExpectedUpdate) / timeFromLastUpdate * * Where updateTimeFraction represents the fraction of time passed between the last update and now spent in * the previous update window. It's worth noting that because we consider updates to occur on their update * timestamp we can make the assumption that the amount of time spent in the previous update window is equal * to the update frequency. * * By way of example, assume updateInterval of 24 hours and a interpolationThreshold of 1 hour. At time 1 the * update is missed by one day and when the oracle is finally called the price is 150, the price feed * then interpolates this price to imply a price at t1 equal to 125. Time 2 the update is 10 minutes late but * since it's within the interpolationThreshold the value isn't interpolated. At time 3 everything * falls back in line. * * +----------------------+------+-------+-------+-------+ * | | 0 | 1 | 2 | 3 | * +----------------------+------+-------+-------+-------+ * | Expected Update Time | 0:00 | 24:00 | 48:00 | 72:00 | * +----------------------+------+-------+-------+-------+ * | Actual Update Time | 0:00 | 48:00 | 48:10 | 72:00 | * +----------------------+------+-------+-------+-------+ * | Logged Px | 100 | 125 | 151 | 130 | * +----------------------+------+-------+-------+-------+ * | Received Oracle Px | 100 | 150 | 151 | 130 | * +----------------------+------+-------+-------+-------+ * | Actual Price | 100 | 110 | 151 | 130 | * +------------------------------------------------------ * * @param _currentPrice Current price returned by oracle * @param _updateInterval Update interval of TimeSeriesFeed * @param _timeFromExpectedUpdate Time passed from expected update * @param _previousLoggedDataPoint Previously logged price from TimeSeriesFeed * @returns Interpolated price value */ function interpolateDelayedPriceUpdate( uint256 _currentPrice, uint256 _updateInterval, uint256 _timeFromExpectedUpdate, uint256 _previousLoggedDataPoint ) internal pure returns (uint256) { // Calculate how much time has passed from timestamp corresponding to last update uint256 timeFromLastUpdate = _timeFromExpectedUpdate.add(_updateInterval); // Linearly interpolate between last updated price (with corresponding timestamp) and current price (with // current timestamp) to imply price at the timestamp we are updating return _currentPrice.mul(_updateInterval) .add(_previousLoggedDataPoint.mul(_timeFromExpectedUpdate)) .div(timeFromLastUpdate); } } // File: contracts/meta-oracles/lib/EMALibrary.sol /* Copyright 2019 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.5.7; /** * @title EMALibrary * @author Set Protocol * * Library for calculate the Exponential Moving Average * */ library EMALibrary{ using SafeMath for uint256; /* * Calculates the new exponential moving average value using the previous value, * EMA time period, and the current asset price. * * Weighted Multiplier = 2 / (timePeriod + 1) * * EMA = Price(Today) x Weighted Multiplier + * EMA(Yesterday) - * EMA(Yesterday) x Weighted Multiplier * * Our implementation is simplified to the following for efficiency: * * EMA = (Price(Today) * 2 + EMA(Yesterday) * (timePeriod - 1)) / (timePeriod + 1) * * * @param _previousEMAValue The previous Exponential Moving average value * @param _timePeriod The number of days the calculate the EMA with * @param _currentAssetPrice The current asset price * @returns The exponential moving average */ function calculate( uint256 _previousEMAValue, uint256 _timePeriod, uint256 _currentAssetPrice ) internal pure returns (uint256) { uint256 a = _currentAssetPrice.mul(2); uint256 b = _previousEMAValue.mul(_timePeriod.sub(1)); uint256 c = _timePeriod.add(1); return a.add(b).div(c); } } // File: contracts/meta-oracles/interfaces/IOracle.sol /* Copyright 2019 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.5.7; /** * @title IOracle * @author Set Protocol * * Interface for operating with any external Oracle that returns uint256 or * an adapting contract that converts oracle output to uint256 */ interface IOracle { /** * Returns the queried data from an oracle returning uint256 * * @return Current price of asset represented in uint256 */ function read() external view returns (uint256); } // File: contracts/meta-oracles/lib/LinkedListLibraryV3.sol /* Copyright 2019 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.5.7; /** * @title LinkedListLibraryV3 * @author Set Protocol * * Library for creating and altering uni-directional circularly linked lists, optimized for sequential updating * Version two of this contract is a library vs. a contract. * * * CHANGELOG * - LinkedListLibraryV3's readList function does not load LinkedList into memory * - readListMemory is removed */ library LinkedListLibraryV3 { using SafeMath for uint256; /* ============ Structs ============ */ struct LinkedList{ uint256 dataSizeLimit; uint256 lastUpdatedIndex; uint256[] dataArray; } /* * Initialize LinkedList by setting limit on amount of nodes and initial value of node 0 * * @param _self LinkedList to operate on * @param _dataSizeLimit Max amount of nodes allowed in LinkedList * @param _initialValue Initial value of node 0 in LinkedList */ function initialize( LinkedList storage _self, uint256 _dataSizeLimit, uint256 _initialValue ) internal { // Check dataArray is empty require( _self.dataArray.length == 0, "LinkedListLibrary.initialize: Initialized LinkedList must be empty" ); // Check that LinkedList is intialized to be greater than 0 size require( _dataSizeLimit > 0, "LinkedListLibrary.initialize: dataSizeLimit must be greater than 0." ); // Initialize Linked list by defining upper limit of data points in the list and setting // initial value _self.dataSizeLimit = _dataSizeLimit; _self.dataArray.push(_initialValue); _self.lastUpdatedIndex = 0; } /* * Add new value to list by either creating new node if node limit not reached or updating * existing node value * * @param _self LinkedList to operate on * @param _addedValue Value to add to list */ function editList( LinkedList storage _self, uint256 _addedValue ) internal { // Add node if data hasn't reached size limit, otherwise update next node _self.dataArray.length < _self.dataSizeLimit ? addNode(_self, _addedValue) : updateNode(_self, _addedValue); } /* * Add new value to list by either creating new node. Node limit must not be reached. * * @param _self LinkedList to operate on * @param _addedValue Value to add to list */ function addNode( LinkedList storage _self, uint256 _addedValue ) internal { uint256 newNodeIndex = _self.lastUpdatedIndex.add(1); require( newNodeIndex == _self.dataArray.length, "LinkedListLibrary: Node must be added at next expected index in list" ); require( newNodeIndex < _self.dataSizeLimit, "LinkedListLibrary: Attempting to add node that exceeds data size limit" ); // Add node value _self.dataArray.push(_addedValue); // Update lastUpdatedIndex value _self.lastUpdatedIndex = newNodeIndex; } /* * Add new value to list by updating existing node. Updates only happen if node limit has been * reached. * * @param _self LinkedList to operate on * @param _addedValue Value to add to list */ function updateNode( LinkedList storage _self, uint256 _addedValue ) internal { // Determine the next node in list to be updated uint256 updateNodeIndex = _self.lastUpdatedIndex.add(1) % _self.dataSizeLimit; // Require that updated node has been previously added require( updateNodeIndex < _self.dataArray.length, "LinkedListLibrary: Attempting to update non-existent node" ); // Update node value and last updated index _self.dataArray[updateNodeIndex] = _addedValue; _self.lastUpdatedIndex = updateNodeIndex; } /* * Read list from the lastUpdatedIndex back the passed amount of data points. * * @param _self LinkedList to operate on * @param _dataPoints Number of data points to return * @return Array of length dataPoints containing most recent values */ function readList( LinkedList storage _self, uint256 _dataPoints ) internal view returns (uint256[] memory) { // Make sure query isn't for more data than collected require( _dataPoints <= _self.dataArray.length, "LinkedListLibrary: Querying more data than available" ); // Instantiate output array in memory uint256[] memory outputArray = new uint256[](_dataPoints); // Find head of list uint256 linkedListIndex = _self.lastUpdatedIndex; for (uint256 i = 0; i < _dataPoints; i++) { // Get value at index in linkedList outputArray[i] = _self.dataArray[linkedListIndex]; // Find next linked index linkedListIndex = linkedListIndex == 0 ? _self.dataSizeLimit.sub(1) : linkedListIndex.sub(1); } return outputArray; } /* * Get latest value from LinkedList. * * @param _self LinkedList to operate on * @return Latest logged value in LinkedList */ function getLatestValue( LinkedList storage _self ) internal view returns (uint256) { return _self.dataArray[_self.lastUpdatedIndex]; } } // File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.5.2; /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } // File: contracts/meta-oracles/lib/TimeSeriesFeedV2.sol /* Copyright 2019 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.5.7; /** * @title TimeSeriesFeedV2 * @author Set Protocol * * Contract used to track time-series data. This is meant to be inherited, as the calculateNextValue * function is unimplemented. New data is appended by calling the poke function, which retrieves the * latest value using the calculateNextValue function. * * CHANGELOG * - Built to be inherited by contract that implements new calculateNextValue function * - Uses LinkedListLibraryV3 * - nextEarliestUpdate is passed into constructor */ contract TimeSeriesFeedV2 is ReentrancyGuard { using SafeMath for uint256; using LinkedListLibraryV3 for LinkedListLibraryV3.LinkedList; /* ============ State Variables ============ */ uint256 public updateInterval; uint256 public maxDataPoints; // Unix Timestamp in seconds of next earliest update time uint256 public nextEarliestUpdate; LinkedListLibraryV3.LinkedList internal timeSeriesData; /* ============ Constructor ============ */ /* * Stores time-series values in a LinkedList and updated using data from a specific data source. * Updates must be triggered off chain to be stored in this smart contract. * * @param _updateInterval Cadence at which data is optimally logged. Optimal schedule is based off deployment timestamp. A certain data point can't be logged before it's expected timestamp but can be logged after * @param _nextEarliestUpdate Time the first on-chain price update becomes available * @param _maxDataPoints The maximum amount of data points the linkedList will hold * @param _seededValues Array of previous timeseries values to seed initial values in list. * The last value should contain the most current piece of data */ constructor( uint256 _updateInterval, uint256 _nextEarliestUpdate, uint256 _maxDataPoints, uint256[] memory _seededValues ) public { // Check that nextEarliestUpdate is greater than current block timestamp require( _nextEarliestUpdate > block.timestamp, "TimeSeriesFeed.constructor: nextEarliestUpdate must be greater than current timestamp." ); // Check that at least one seeded value is passed in require( _seededValues.length > 0, "TimeSeriesFeed.constructor: Must include at least one seeded value." ); // Check that maxDataPoints greater than 0 require( _maxDataPoints > 0, "TimeSeriesFeed.constructor: Max data points must be greater than 0." ); // Check that updateInterval greater than 0 require( _updateInterval > 0, "TimeSeriesFeed.constructor: Update interval must be greater than 0." ); // Set updateInterval and maxDataPoints updateInterval = _updateInterval; maxDataPoints = _maxDataPoints; // Define upper data size limit for linked list and input initial value timeSeriesData.initialize(_maxDataPoints, _seededValues[0]); // Cycle through input values array (skipping first value used to initialize LinkedList) // and add to timeSeriesData for (uint256 i = 1; i < _seededValues.length; i++) { timeSeriesData.editList(_seededValues[i]); } // Set nextEarliestUpdate nextEarliestUpdate = _nextEarliestUpdate; } /* ============ External ============ */ /* * Updates linked list with newest data point by calling the implemented calculateNextValue function */ function poke() external nonReentrant { // Make sure block timestamp exceeds nextEarliestUpdate require( block.timestamp >= nextEarliestUpdate, "TimeSeriesFeed.poke: Not enough time elapsed since last update" ); // Get the most current data point uint256 newValue = calculateNextValue(); // Update the nextEarliestUpdate to previous nextEarliestUpdate plus updateInterval nextEarliestUpdate = nextEarliestUpdate.add(updateInterval); // Update linkedList with new price timeSeriesData.editList(newValue); } /* * Query linked list for specified days of data. Will revert if number of days * passed exceeds amount of days collected. Will revert if not enough days of * data logged. * * @param _numDataPoints Number of datapoints to query * @returns Array of datapoints of length _numDataPoints from most recent to oldest */ function read( uint256 _numDataPoints ) external view returns (uint256[] memory) { return timeSeriesData.readList(_numDataPoints); } /* ============ Internal ============ */ function calculateNextValue() internal returns (uint256); } // File: contracts/meta-oracles/feeds/LinearizedEMATimeSeriesFeed.sol /* Copyright 2019 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.5.7; pragma experimental "ABIEncoderV2"; /** * @title LinearizedEMATimeSeriesFeed * @author Set Protocol * * This TimeSeriesFeed calculates the current EMA price and stores it using the * inherited TimeSeriesFeedV2 contract. On calculation, if the interpolationThreshold * is reached, then it returns a linearly interpolated value. */ contract LinearizedEMATimeSeriesFeed is TimeSeriesFeedV2, TimeLockUpgrade { using SafeMath for uint256; using LinkedListLibraryV3 for LinkedListLibraryV3.LinkedList; /* ============ State Variables ============ */ // Number of EMA Days uint256 public emaTimePeriod; // Amount of time after which read interpolates price result, in seconds uint256 public interpolationThreshold; string public dataDescription; IOracle public oracleInstance; /* ============ Events ============ */ event LogOracleUpdated( address indexed newOracleAddress ); /* ============ Constructor ============ */ /* * Set interpolationThreshold, data description, emaTimePeriod, and instantiate oracle * * @param _updateInterval Cadence at which data is optimally logged. Optimal schedule is based off deployment timestamp. A certain data point can't be logged before it's expected timestamp but can be logged after (for TimeSeriesFeed) * @param _nextEarliestUpdate Time the first on-chain price update becomes available (for TimeSeriesFeed) * @param _maxDataPoints The maximum amount of data points the linkedList will hold (for TimeSeriesFeed) * @param _seededValues Array of previous timeseries values to seed initial values in list. * The last value should contain the most current piece of data (for TimeSeriesFeed) * @param _emaTimePeriod The time period the exponential moving average is based off of * @param _interpolationThreshold The minimum time in seconds where interpolation is enabled * @param _oracleAddress The address to read current data from * @param _dataDescription Description of contract for Etherscan / other applications */ constructor( uint256 _updateInterval, uint256 _nextEarliestUpdate, uint256 _maxDataPoints, uint256[] memory _seededValues, uint256 _emaTimePeriod, uint256 _interpolationThreshold, IOracle _oracleAddress, string memory _dataDescription ) public TimeSeriesFeedV2( _updateInterval, _nextEarliestUpdate, _maxDataPoints, _seededValues ) { require( _emaTimePeriod > 0, "LinearizedEMADataSource.constructor: Time Period must be greater than 0." ); interpolationThreshold = _interpolationThreshold; emaTimePeriod = _emaTimePeriod; oracleInstance = _oracleAddress; dataDescription = _dataDescription; } /* ============ External ============ */ /* * Change oracle in case current one fails or is deprecated. Only contract * owner is allowed to change. * * @param _newOracleAddress Address of new oracle to pull data from */ function changeOracle( IOracle _newOracleAddress ) external onlyOwner timeLockUpgrade // Must be placed after onlyOwner { // Check to make sure new oracle address is passed require( address(_newOracleAddress) != address(oracleInstance), "LinearizedEMADataSource.changeOracle: Must give new oracle address." ); oracleInstance = _newOracleAddress; emit LogOracleUpdated(address(_newOracleAddress)); } /* ============ Internal ============ */ /* * Returns the data from the oracle contract. If the current timestamp has surpassed * the interpolationThreshold, then the current price is retrieved and interpolated based on * the previous value and the time that has elapsed since the intended update value. * * Returns with newest data point by querying oracle. Is eligible to be * called after nextAvailableUpdate timestamp has passed. Because the nextAvailableUpdate occurs * on a predetermined cadence based on the time of deployment, delays in calling poke do not propogate * throughout the whole dataset and the drift caused by previous poke transactions not being mined * exactly on nextAvailableUpdate do not compound as they would if it was required that poke is called * an updateInterval amount of time after the last poke. * * @param _timeSeriesState Struct of TimeSeriesFeed state * @returns Returns the datapoint from the oracle contract */ function calculateNextValue() internal returns (uint256) { // Get current oracle value uint256 oracleValue = oracleInstance.read(); // Get the previous EMA Value uint256 previousEMAValue = timeSeriesData.getLatestValue(); // Calculate the current EMA uint256 currentEMAValue = EMALibrary.calculate( previousEMAValue, emaTimePeriod, oracleValue ); // Calculate how much time has passed from last expected update uint256 timeFromExpectedUpdate = block.timestamp.sub(nextEarliestUpdate); // If block timeFromExpectedUpdate is greater than interpolationThreshold we linearize // the current price to try to reduce error if (timeFromExpectedUpdate < interpolationThreshold) { return currentEMAValue; } else { return DataSourceLinearInterpolationLibrary.interpolateDelayedPriceUpdate( currentEMAValue, updateInterval, timeFromExpectedUpdate, previousEMAValue ); } } }
Returns the data from the oracle contract. If the current timestamp has surpassed the interpolationThreshold, then the current price is retrieved and interpolated based on the previous value and the time that has elapsed since the intended update value. Returns with newest data point by querying oracle. Is eligible to be called after nextAvailableUpdate timestamp has passed. Because the nextAvailableUpdate occurs on a predetermined cadence based on the time of deployment, delays in calling poke do not propogate throughout the whole dataset and the drift caused by previous poke transactions not being mined exactly on nextAvailableUpdate do not compound as they would if it was required that poke is called an updateInterval amount of time after the last poke. @param _timeSeriesState Struct of TimeSeriesFeed state @returns Returns the datapoint from the oracle contract/ Get current oracle value Get the previous EMA Value Calculate the current EMA Calculate how much time has passed from last expected update If block timeFromExpectedUpdate is greater than interpolationThreshold we linearize the current price to try to reduce error
function calculateNextValue() internal returns (uint256) { uint256 oracleValue = oracleInstance.read(); uint256 previousEMAValue = timeSeriesData.getLatestValue(); uint256 currentEMAValue = EMALibrary.calculate( previousEMAValue, emaTimePeriod, oracleValue ); uint256 timeFromExpectedUpdate = block.timestamp.sub(nextEarliestUpdate); if (timeFromExpectedUpdate < interpolationThreshold) { return currentEMAValue; return DataSourceLinearInterpolationLibrary.interpolateDelayedPriceUpdate( currentEMAValue, updateInterval, timeFromExpectedUpdate, previousEMAValue ); } }
12,971,745
[ 1, 1356, 326, 501, 628, 326, 20865, 6835, 18, 971, 326, 783, 2858, 711, 5056, 23603, 326, 12851, 7614, 16, 1508, 326, 783, 6205, 353, 10295, 471, 24985, 2511, 603, 326, 2416, 460, 471, 326, 813, 716, 711, 9613, 3241, 326, 12613, 1089, 460, 18, 2860, 598, 19824, 501, 1634, 635, 23936, 20865, 18, 2585, 21351, 358, 506, 2566, 1839, 1024, 5268, 1891, 2858, 711, 2275, 18, 15191, 326, 1024, 5268, 1891, 9938, 603, 279, 3479, 4443, 329, 28451, 802, 2511, 603, 326, 813, 434, 6314, 16, 4624, 87, 316, 4440, 293, 3056, 741, 486, 2270, 717, 340, 3059, 659, 326, 7339, 3709, 471, 326, 25217, 15848, 635, 2416, 293, 3056, 8938, 486, 3832, 1131, 329, 8950, 603, 1024, 5268, 1891, 741, 486, 11360, 487, 2898, 4102, 309, 518, 1703, 1931, 716, 293, 3056, 353, 2566, 392, 1089, 4006, 3844, 434, 813, 1839, 326, 1142, 293, 3056, 18, 282, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 4604, 2134, 620, 1435, 203, 3639, 2713, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2254, 5034, 20865, 620, 273, 20865, 1442, 18, 896, 5621, 203, 203, 3639, 2254, 5034, 2416, 3375, 37, 620, 273, 813, 6485, 751, 18, 588, 18650, 620, 5621, 203, 203, 3639, 2254, 5034, 783, 3375, 37, 620, 273, 7141, 1013, 495, 3345, 18, 11162, 12, 203, 5411, 2416, 3375, 37, 620, 16, 203, 5411, 801, 69, 26540, 16, 203, 5411, 20865, 620, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 813, 1265, 6861, 1891, 273, 1203, 18, 5508, 18, 1717, 12, 4285, 41, 297, 17452, 1891, 1769, 203, 203, 3639, 309, 261, 957, 1265, 6861, 1891, 411, 12851, 7614, 13, 288, 203, 5411, 327, 783, 3375, 37, 620, 31, 203, 5411, 327, 12806, 15982, 31516, 9313, 18, 18676, 340, 29527, 5147, 1891, 12, 203, 7734, 783, 3375, 37, 620, 16, 203, 7734, 1089, 4006, 16, 203, 7734, 813, 1265, 6861, 1891, 16, 203, 7734, 2416, 3375, 37, 620, 203, 5411, 11272, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/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}. * @dev Please notice that this contract is a very lightly modified version of the openzeppelin ERC-721 contract. * Variations are noted in detailed comments throughout the contract. Here is a summary of changes. * * 1. Change private contract variables (_name, _symbol, _owners, _balances, _tokenApprovals, _operatorApprovals) to internal so inheriting contracts have access. * 2. Removed _mint/_safeMint functions. This contract is going to be used as the basis of a Fixed Cost Mint contract. * 3. Removed _beforeTokenTransfer and _afterTokenTransfer calls - the are not needed for this example. * 4. Added _clearApproval, _clearOwnership, and _setOwnership functions. * 5. Modified transferFrom implementation. See detailed comments below. * 6. Modified safeTransferFrom implementation. See detailed comments below. * 7. Modified _burn implementation. See detailed comments below. * 8. Modified _isApprovedOrOwner implementation. See detailed comments below. * 9. Modified _transfer implementation. See detailed comments below. */ contract ERC721 is Context, ERC165, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string internal _name; // Token symbol string internal _symbol; // Mapping from token ID to owner address mapping(uint256 => address) internal _owners; // Mapping owner address to token count mapping(address => uint256) internal _balances; // Mapping from token ID to approved address mapping(uint256 => address) internal _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) internal _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = 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(owner, to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. * @dev Please notice that transferFrom is slightly modified from the openzeppelin implementation. * The contract has been modified such that _isApprovedOrOwner returns the owner address. * The owner is now passed in to the _transfer functionso that we don't have to read the owner twice. * This optimization conserves a little bit of gas. * The openzeppelin version is shown commented out below fo comparison. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { (address owner, bool isApprovedOrOwner) = _isApprovedOrOwner(_msgSender(), tokenId); require(isApprovedOrOwner, "ERC721: transfer caller is not owner nor approved"); _transfer(owner, from, to, tokenId); } //function transferFrom(address from, address to, uint256 tokenId) public virtual override { // 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}. @dev Please notice that safeTransferFrom is slightly modified from the openzeppelin implementation. In this version it calls through the same logic as transferFrom, followed by the ERC721 Receiver Check. The openzeppelin version is shown commented out below fo comparison. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual override { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer"); } //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 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`. * @dev Please notice that _isApprovedOrOwner is slightly modified from the openzeppelin implementation. * The contract has been modified such that _isApprovedOrOwner returns the owner address so that * code downstream does not have to read the owner twice. This optimization conserves a little bit of gas. * The openzeppelin version is shown commented out below fo comparison. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (address owner, bool isApprovedOrOwner) { owner = _owners[tokenId]; require(owner != address(0), "ERC721: operator query for nonexistent token"); isApprovedOrOwner = (spender == owner || _tokenApprovals[tokenId] == spender || isApprovedForAll(owner, spender)); } //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 Destroys `tokenId`. * The approval is cleared when the token is burned. * @dev Please notice that _burn is slightly modified from the openzeppelin implementation. * The contract has been modified such that _beforeTokenTransfer and _afterTokenTransfer are no longer called. * Calls ownerOf in a way that an inheriting contract could override the ownerOf behavior. * Checks approval so that either the owner or an approved address can burn. * Calls _clearApproval(owner, tokenId) instead of _approve(address(0), tokenId). This just deletes the approval entry, saving gas. * Calls _clearOwnership(tokenId) so that inheriting contract can override the basic delete of the _owners mapping. * The openzeppelin version is shown commented out below fo comparison. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); bool isApprovedOrOwner = (_msgSender() == owner || _tokenApprovals[tokenId] == _msgSender() || isApprovedForAll(owner, _msgSender())); require(isApprovedOrOwner, "ERC721: burn caller is not owner nor approved"); // Clear approvals _clearApproval(owner, tokenId); _balances[owner] -= 1; _clearOwnership(tokenId); emit Transfer(owner, address(0), tokenId); } //function _burn(uint256 tokenId) internal virtual { // address owner = ERC721.ownerOf(tokenId); // // _beforeTokenTransfer(owner, address(0), tokenId); // // // Clear approvals // _approve(address(0), tokenId); // // _balances[owner] -= 1; // delete _owners[tokenId]; // // emit Transfer(owner, address(0), tokenId); // // _afterTokenTransfer(owner, address(0), tokenId); //} /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @dev Please notice that _transfer is slightly modified from the openzeppelin implementation. * The contract has been modified such that _beforeTokenTransfer and _afterTokenTransfer are no longer called. * 'owner' is passed in to save gas looking it up twice. * Calls _clearApproval(owner, tokenId) instead of _approve(address(0), tokenId). This just deletes the approval entry, saving gas. * Calls _setOwnership(to, tokenId) so that inheriting contract can override the implementation of re-assigning owner address. * The openzeppelin version is shown commented out below fo comparison. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address owner, address from, address to, uint256 tokenId) internal virtual { require(owner == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); // Clear approvals from the previous owner _clearApproval(owner, tokenId); _balances[from] -= 1; _balances[to] += 1; _setOwnership(to, tokenId); emit Transfer(from, to, tokenId); } //function _transfer(address from, address to, uint256 tokenId) internal virtual { // require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); // require(to != address(0), "ERC721: transfer to the zero address"); // // _beforeTokenTransfer(from, to, tokenId); // // // Clear approvals from the previous owner // _approve(address(0), tokenId); // // _balances[from] -= 1; // _balances[to] += 1; // _owners[tokenId] = to; // // emit Transfer(from, to, tokenId); // // _afterTokenTransfer(from, to, tokenId); //} /** * @dev Equivalent to approving address(0), but more gas efficient * @dev Please notice that _clearApproval is a function that was added that does not exist in the openzeppelin implementation. * It gives you a gas refund when resetting approval to address(0). * * Emits a {Approval} event. */ function _clearApproval(address owner, uint256 tokenId) internal virtual { delete _tokenApprovals[tokenId]; emit Approval(owner, address(0), tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address owner, address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Please notice that _clearOwnership is a function that was added that does not exist in the openzeppelin implementation. * It will be overridden in our fixed cost minting contract. */ function _clearOwnership(uint256 tokenId) internal virtual { delete _owners[tokenId]; } /** * @dev Please notice that _setOwnership is a function that was added that does not exist in the openzeppelin implementation. * It will be overridden in our fixed cost minting contract. */ function _setOwnership(address to, uint256 tokenId) internal virtual { _owners[tokenId] = to; } /** * @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 * * @dev Slither identifies an issue with unused return value. * Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#unused-return * This should be a non-issue. It is the standard OpenZeppelin implementation which has been heavily used and audited. */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } }
* @dev Equivalent to approving address(0), but more gas efficient @dev Please notice that _clearApproval is a function that was added that does not exist in the openzeppelin implementation. It gives you a gas refund when resetting approval to address(0). Emits a {Approval} event./
function _clearApproval(address owner, uint256 tokenId) internal virtual { delete _tokenApprovals[tokenId]; emit Approval(owner, address(0), tokenId); }
15,881,832
[ 1, 22606, 358, 6617, 6282, 1758, 12, 20, 3631, 1496, 1898, 16189, 14382, 225, 7801, 11690, 716, 389, 8507, 23461, 353, 279, 445, 716, 1703, 3096, 716, 1552, 486, 1005, 316, 326, 1696, 94, 881, 84, 292, 267, 4471, 18, 1377, 2597, 14758, 1846, 279, 16189, 16255, 1347, 30691, 23556, 358, 1758, 12, 20, 2934, 7377, 1282, 279, 288, 23461, 97, 871, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 8507, 23461, 12, 2867, 3410, 16, 2254, 5034, 1147, 548, 13, 2713, 5024, 288, 203, 3639, 1430, 389, 2316, 12053, 4524, 63, 2316, 548, 15533, 203, 3639, 3626, 1716, 685, 1125, 12, 8443, 16, 1758, 12, 20, 3631, 1147, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/56/0xfC652Ea2E8A373C16f3d8c5BD25E9898b9699ECB/sources/contracts/IFAllocationMaster.sol
adds a new track add track
function addTrack( string calldata name, ERC20 stakeToken, uint24 _weightAccrualRate, uint64 _passiveRolloverRate, uint64 _activeRolloverRate, uint104 _maxTotalStake ) external onlyOwner { require(_weightAccrualRate != 0, 'accrual rate is 0'); tracks.push( TrackInfo({ }) ); ); }
3,247,459
[ 1, 25428, 279, 394, 3298, 527, 3298, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 527, 4402, 12, 203, 3639, 533, 745, 892, 508, 16, 203, 3639, 4232, 39, 3462, 384, 911, 1345, 16, 203, 3639, 2254, 3247, 389, 4865, 8973, 86, 1462, 4727, 16, 203, 3639, 2254, 1105, 389, 5466, 688, 4984, 21896, 4727, 16, 203, 3639, 2254, 1105, 389, 3535, 4984, 21896, 4727, 16, 203, 3639, 2254, 21869, 389, 1896, 5269, 510, 911, 203, 565, 262, 3903, 1338, 5541, 288, 203, 3639, 2583, 24899, 4865, 8973, 86, 1462, 4727, 480, 374, 16, 296, 8981, 86, 1462, 4993, 353, 374, 8284, 203, 203, 3639, 13933, 18, 6206, 12, 203, 5411, 11065, 966, 12590, 203, 5411, 289, 13, 203, 3639, 11272, 203, 203, 3639, 11272, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x1E4558Fe59149Bb3FD8bA08E3fB6ed9B023e09aC/sources/contracts/pools/MSPoolNFTBasic.sol
@notice ERC-721 Receiver implementation
function onERC721Received(address, address, uint256 id, bytes calldata) public override returns (bytes4) { if( NFT == msg.sender ) _TOKEN_IDS.push(id); emit NFTDeposit( msg.sender, id ); return IERC721Receiver.onERC721Received.selector; }
16,404,055
[ 1, 654, 39, 17, 27, 5340, 31020, 4471, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 603, 654, 39, 27, 5340, 8872, 12, 2867, 16, 1758, 16, 2254, 5034, 612, 16, 1731, 745, 892, 13, 1071, 3849, 1135, 261, 3890, 24, 13, 288, 203, 540, 203, 3639, 309, 12, 423, 4464, 422, 1234, 18, 15330, 262, 389, 8412, 67, 19516, 18, 6206, 12, 350, 1769, 203, 203, 3639, 3626, 423, 4464, 758, 1724, 12, 1234, 18, 15330, 16, 612, 11272, 203, 203, 3639, 327, 467, 654, 39, 27, 5340, 12952, 18, 265, 654, 39, 27, 5340, 8872, 18, 9663, 31, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
library OwnershipTypes{ using Serializer for Serializer.DataComponent; struct Ownership { address m_Owner; // 0 uint32 m_OwnerInventoryIndex; // 20 } function SerializeOwnership(Ownership ownership) internal pure returns (bytes32) { Serializer.DataComponent memory data; data.WriteAddress(0, ownership.m_Owner); data.WriteUint32(20, ownership.m_OwnerInventoryIndex); return data.m_Raw; } function DeserializeOwnership(bytes32 raw) internal pure returns (Ownership) { Ownership memory ownership; Serializer.DataComponent memory data; data.m_Raw = raw; ownership.m_Owner = data.ReadAddress(0); ownership.m_OwnerInventoryIndex = data.ReadUint32(20); return ownership; } } library LibStructs{ using Serializer for Serializer.DataComponent; // HEROES struct Hero { uint16 stockID; uint8 rarity; uint16 hp; uint16 atk; uint16 def; uint16 agi; uint16 intel; uint16 cHp; //uint8 cenas; // uint8 critic; // uint8 healbonus; // uint8 atackbonus; // uint8 defensebonus; uint8 isForSale; uint8 lvl; uint16 xp; } struct StockHero {uint16 price;uint8 stars;uint8 mainOnePosition;uint8 mainTwoPosition;uint16 stock;uint8 class;} function SerializeHero(Hero hero) internal pure returns (bytes32){ Serializer.DataComponent memory data; data.WriteUint16(0, hero.stockID); data.WriteUint8(2, hero.rarity); //data.WriteUint8(2, hero.m_IsForSale); //data.WriteUint8(3, rocket.m_Unused3); data.WriteUint16(4, hero.hp); data.WriteUint16(6, hero.atk); data.WriteUint16(8, hero.def); data.WriteUint16(10, hero.agi); data.WriteUint16(12, hero.intel); data.WriteUint16(14, hero.cHp); // data.WriteUint8(16, hero.class); // data.WriteUint8(17, hero.healbonus); // data.WriteUint8(18, hero.atackbonus); // data.WriteUint8(19, hero.defensebonus); data.WriteUint8(20, hero.isForSale); data.WriteUint8(21, hero.lvl); data.WriteUint16(23, hero.xp); return data.m_Raw; } function DeserializeHero(bytes32 raw) internal pure returns (Hero){ Hero memory hero; Serializer.DataComponent memory data; data.m_Raw = raw; hero.stockID = data.ReadUint16(0); //hero.rarity = data.ReadUint8(1); hero.rarity = data.ReadUint8(2); //rocket.m_Unused3 = data.ReadUint8(3); hero.hp = data.ReadUint16(4); hero.atk = data.ReadUint16(6); hero.def = data.ReadUint16(8); hero.agi = data.ReadUint16(10); hero.intel = data.ReadUint16(12); hero.cHp = data.ReadUint16(14); // hero.class = data.ReadUint8(16); // hero.healbonus = data.ReadUint8(17); // hero.atackbonus = data.ReadUint8(18); // hero.defensebonus = data.ReadUint8(19); hero.isForSale = data.ReadUint8(20); hero.lvl = data.ReadUint8(21); hero.xp = data.ReadUint16(23); return hero; } function SerializeStockHero(StockHero stockhero) internal pure returns (bytes32){ // string name;uint64 price;uint8 stars;uint8 mainOnePosition;uint8 mainTwoPosition; Serializer.DataComponent memory data; data.WriteUint16(0, stockhero.price); data.WriteUint8(2, stockhero.stars); data.WriteUint8(3, stockhero.mainOnePosition); data.WriteUint8(4, stockhero.mainTwoPosition); data.WriteUint16(5, stockhero.stock); data.WriteUint8(7, stockhero.class); return data.m_Raw; } function DeserializeStockHero(bytes32 raw) internal pure returns (StockHero){ StockHero memory stockhero; Serializer.DataComponent memory data; data.m_Raw = raw; stockhero.price = data.ReadUint16(0); stockhero.stars = data.ReadUint8(2); stockhero.mainOnePosition = data.ReadUint8(3); stockhero.mainTwoPosition = data.ReadUint8(4); stockhero.stock = data.ReadUint16(5); stockhero.class = data.ReadUint8(7); return stockhero; } // ITEMS struct Item { uint16 stockID; uint8 lvl; uint8 rarity; uint16 hp; uint16 atk; uint16 def; uint16 agi; uint16 intel; uint8 critic; uint8 healbonus; uint8 atackbonus; uint8 defensebonus; uint8 isForSale; uint8 grade; } struct StockItem {uint16 price;uint8 stars;uint8 lvl;uint8 mainOnePosition;uint8 mainTwoPosition;uint16[5] stats;uint8[4] secstats;uint8 cat;uint8 subcat;} // 1 finney = 0.0001 ether function SerializeItem(Item item) internal pure returns (bytes32){ Serializer.DataComponent memory data; data.WriteUint16(0, item.stockID); data.WriteUint8(4, item.lvl); data.WriteUint8(5, item.rarity); data.WriteUint16(6, item.hp); data.WriteUint16(8, item.atk); data.WriteUint16(10, item.def); data.WriteUint16(12, item.agi); data.WriteUint16(14, item.intel); // data.WriteUint32(14, item.cHp); data.WriteUint8(16, item.critic); data.WriteUint8(17, item.healbonus); data.WriteUint8(18, item.atackbonus); data.WriteUint8(19, item.defensebonus); data.WriteUint8(20, item.isForSale); data.WriteUint8(21, item.grade); return data.m_Raw; } function DeserializeItem(bytes32 raw) internal pure returns (Item){ Item memory item; Serializer.DataComponent memory data; data.m_Raw = raw; item.stockID = data.ReadUint16(0); item.lvl = data.ReadUint8(4); item.rarity = data.ReadUint8(5); item.hp = data.ReadUint16(6); item.atk = data.ReadUint16(8); item.def = data.ReadUint16(10); item.agi = data.ReadUint16(12); item.intel = data.ReadUint16(14); item.critic = data.ReadUint8(16); item.healbonus = data.ReadUint8(17); item.atackbonus = data.ReadUint8(18); item.defensebonus = data.ReadUint8(19); item.isForSale = data.ReadUint8(20); item.grade = data.ReadUint8(21); return item; } function SerializeStockItem(StockItem stockitem) internal pure returns (bytes32){ // string name;uint64 price;uint8 stars;uint8 mainOnePosition;uint8 mainTwoPosition;uint8 mainThreePosition; // uint16[] stats;uint8[] secstats; Serializer.DataComponent memory data; data.WriteUint16(0, stockitem.price); data.WriteUint8(2, stockitem.stars); data.WriteUint8(3, stockitem.lvl); data.WriteUint8(4, stockitem.mainOnePosition); data.WriteUint8(5, stockitem.mainTwoPosition); //data.WriteUint8(12, stockitem.mainThreePosition); //stats data.WriteUint16(6, stockitem.stats[0]); data.WriteUint16(8, stockitem.stats[1]); data.WriteUint16(10, stockitem.stats[2]); data.WriteUint16(12, stockitem.stats[3]); data.WriteUint16(14, stockitem.stats[4]); //secstats data.WriteUint8(16, stockitem.secstats[0]); data.WriteUint8(17, stockitem.secstats[1]); data.WriteUint8(18, stockitem.secstats[2]); data.WriteUint8(19, stockitem.secstats[3]); data.WriteUint8(20, stockitem.cat); data.WriteUint8(21, stockitem.subcat); return data.m_Raw; } function DeserializeStockItem(bytes32 raw) internal pure returns (StockItem){ StockItem memory stockitem; Serializer.DataComponent memory data; data.m_Raw = raw; stockitem.price = data.ReadUint16(0); stockitem.stars = data.ReadUint8(2); stockitem.lvl = data.ReadUint8(3); stockitem.mainOnePosition = data.ReadUint8(4); stockitem.mainTwoPosition = data.ReadUint8(5); //stockitem.mainThreePosition = data.ReadUint8(12); stockitem.stats[0] = data.ReadUint16(6); stockitem.stats[1] = data.ReadUint16(8); stockitem.stats[2] = data.ReadUint16(10); stockitem.stats[3] = data.ReadUint16(12); stockitem.stats[4] = data.ReadUint16(14); stockitem.secstats[0] = data.ReadUint8(16); stockitem.secstats[1] = data.ReadUint8(17); stockitem.secstats[2] = data.ReadUint8(18); stockitem.secstats[3] = data.ReadUint8(19); stockitem.cat = data.ReadUint8(20); stockitem.subcat = data.ReadUint8(21); return stockitem; } struct Action {uint16 actionID;uint8 actionType;uint16 finneyCost;uint32 cooldown;uint8 lvl;uint8 looted;uint8 isDaily;} function SerializeAction(Action action) internal pure returns (bytes32){ Serializer.DataComponent memory data; data.WriteUint16(0, action.actionID); data.WriteUint8(2, action.actionType); data.WriteUint16(3, action.finneyCost); data.WriteUint32(5, action.cooldown); data.WriteUint8(9, action.lvl); data.WriteUint8(10, action.looted); data.WriteUint8(11, action.isDaily); return data.m_Raw; } function DeserializeAction(bytes32 raw) internal pure returns (Action){ Action memory action; Serializer.DataComponent memory data; data.m_Raw = raw; action.actionID = data.ReadUint16(0); action.actionType = data.ReadUint8(2); action.finneyCost = data.ReadUint16(3); action.cooldown = data.ReadUint32(5); action.lvl = data.ReadUint8(9); action.looted = data.ReadUint8(10); action.isDaily = data.ReadUint8(11); return action; } struct Mission {uint8 dificulty;uint16[4] stockitemId_drops;uint16[5] statsrequired;uint16 count;} function SerializeMission(Mission mission) internal pure returns (bytes32){ Serializer.DataComponent memory data; data.WriteUint8(0, mission.dificulty); data.WriteUint16(1, mission.stockitemId_drops[0]); data.WriteUint16(5, mission.stockitemId_drops[1]); data.WriteUint16(9, mission.stockitemId_drops[2]); data.WriteUint16(13, mission.stockitemId_drops[3]); data.WriteUint16(15, mission.statsrequired[0]); data.WriteUint16(17, mission.statsrequired[1]); data.WriteUint16(19, mission.statsrequired[2]); data.WriteUint16(21, mission.statsrequired[3]); data.WriteUint16(23, mission.statsrequired[4]); data.WriteUint16(25, mission.count); return data.m_Raw; } function DeserializeMission(bytes32 raw) internal pure returns (Mission){ Mission memory mission; Serializer.DataComponent memory data; data.m_Raw = raw; mission.dificulty = data.ReadUint8(0); mission.stockitemId_drops[0] = data.ReadUint16(1); mission.stockitemId_drops[1] = data.ReadUint16(5); mission.stockitemId_drops[2] = data.ReadUint16(9); mission.stockitemId_drops[3] = data.ReadUint16(13); mission.statsrequired[0] = data.ReadUint16(15); mission.statsrequired[1] = data.ReadUint16(17); mission.statsrequired[2] = data.ReadUint16(19); mission.statsrequired[3] = data.ReadUint16(21); mission.statsrequired[4] = data.ReadUint16(23); mission.count = data.ReadUint16(25); return mission; } function toWei(uint80 price) public returns(uint256 value){ value = price; value = value * 1 finney; } } library GlobalTypes{ using Serializer for Serializer.DataComponent; struct Global { uint32 m_LastHeroId; // 0 uint32 m_LastItem; // 4 uint8 m_Unused8; // 8 uint8 m_Unused9; // 9 uint8 m_Unused10; // 10 uint8 m_Unused11; // 11 } function SerializeGlobal(Global global) internal pure returns (bytes32) { Serializer.DataComponent memory data; data.WriteUint32(0, global.m_LastHeroId); data.WriteUint32(4, global.m_LastItem); data.WriteUint8(8, global.m_Unused8); data.WriteUint8(9, global.m_Unused9); data.WriteUint8(10, global.m_Unused10); data.WriteUint8(11, global.m_Unused11); return data.m_Raw; } function DeserializeGlobal(bytes32 raw) internal pure returns (Global) { Global memory global; Serializer.DataComponent memory data; data.m_Raw = raw; global.m_LastHeroId = data.ReadUint32(0); global.m_LastItem = data.ReadUint32(4); global.m_Unused8 = data.ReadUint8(8); global.m_Unused9 = data.ReadUint8(9); global.m_Unused10 = data.ReadUint8(10); global.m_Unused11 = data.ReadUint8(11); return global; } } library MarketTypes{ using Serializer for Serializer.DataComponent; struct MarketListing { uint128 m_Price; // 0 } function SerializeMarketListing(MarketListing listing) internal pure returns (bytes32) { Serializer.DataComponent memory data; data.WriteUint128(0, listing.m_Price); return data.m_Raw; } function DeserializeMarketListing(bytes32 raw) internal pure returns (MarketListing) { MarketListing memory listing; Serializer.DataComponent memory data; data.m_Raw = raw; listing.m_Price = data.ReadUint128(0); return listing; } } library Serializer{ struct DataComponent { bytes32 m_Raw; } function ReadUint8(DataComponent memory self, uint32 offset) internal pure returns (uint8) { return uint8((self.m_Raw >> (offset * 8)) & 0xFF); } function WriteUint8(DataComponent memory self, uint32 offset, uint8 value) internal pure { self.m_Raw |= (bytes32(value) << (offset * 8)); } function ReadUint16(DataComponent memory self, uint32 offset) internal pure returns (uint16) { return uint16((self.m_Raw >> (offset * 8)) & 0xFFFF); } function WriteUint16(DataComponent memory self, uint32 offset, uint16 value) internal pure { self.m_Raw |= (bytes32(value) << (offset * 8)); } function ReadUint32(DataComponent memory self, uint32 offset) internal pure returns (uint32) { return uint32((self.m_Raw >> (offset * 8)) & 0xFFFFFFFF); } function WriteUint32(DataComponent memory self, uint32 offset, uint32 value) internal pure { self.m_Raw |= (bytes32(value) << (offset * 8)); } function ReadUint64(DataComponent memory self, uint32 offset) internal pure returns (uint64) { return uint64((self.m_Raw >> (offset * 8)) & 0xFFFFFFFFFFFFFFFF); } function WriteUint64(DataComponent memory self, uint32 offset, uint64 value) internal pure { self.m_Raw |= (bytes32(value) << (offset * 8)); } function ReadUint80(DataComponent memory self, uint32 offset) internal pure returns (uint80) { return uint80((self.m_Raw >> (offset * 8)) & 0xFFFFFFFFFFFFFFFFFFFF); } function WriteUint80(DataComponent memory self, uint32 offset, uint80 value) internal pure { self.m_Raw |= (bytes32(value) << (offset * 8)); } function ReadUint128(DataComponent memory self, uint128 offset) internal pure returns (uint128) { return uint128((self.m_Raw >> (offset * 8)) & 0xFFFFFFFFFFFFFFFFFFFF); } function WriteUint128(DataComponent memory self, uint32 offset, uint128 value) internal pure { self.m_Raw |= (bytes32(value) << (offset * 8)); } function ReadAddress(DataComponent memory self, uint32 offset) internal pure returns (address) { return address((self.m_Raw >> (offset * 8)) & ( (0xFFFFFFFF << 0) | (0xFFFFFFFF << 32) | (0xFFFFFFFF << 64) | (0xFFFFFFFF << 96) | (0xFFFFFFFF << 128) )); } function WriteAddress(DataComponent memory self, uint32 offset, address value) internal pure { self.m_Raw |= (bytes32(value) << (offset * 8)); } } 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; } } library SafeMath32 { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint32 a, uint32 b) internal pure returns (uint32) { if (a == 0) { return 0; } uint32 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint32 a, uint32 b) internal pure returns (uint32) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 c = a + b; assert(c >= a); return c; } } library SafeMath16 { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint16 a, uint16 b) internal pure returns (uint16) { if (a == 0) { return 0; } uint16 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint16 a, uint16 b) internal pure returns (uint16) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint16 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(uint16 a, uint16 b) internal pure returns (uint16) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint16 a, uint16 b) internal pure returns (uint16) { uint16 c = a + b; assert(c >= a); return c; } } library SafeMath8 { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint8 a, uint8 b) internal pure returns (uint8) { if (a == 0) { return 0; } uint8 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint8 a, uint8 b) internal pure returns (uint8) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint8 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(uint8 a, uint8 b) internal pure returns (uint8) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint8 a, uint8 b) internal pure returns (uint8) { uint8 c = a + b; assert(c >= a); return c; } } contract ProfitManager { address public m_Owner; bool public m_Paused; AbstractDatabase m_Database= AbstractDatabase(0x095cbb73c75d4e1c62c94e0b1d4d88f8194b1941); modifier NotWhilePaused() { require(m_Paused == false); _; } modifier OnlyOwner(){ require(msg.sender == m_Owner); _; } address constant NullAddress = 0; //Market uint256 constant ProfitFundsCategory = 14; uint256 constant WithdrawalFundsCategory = 15; uint256 constant HeroMarketCategory = 16; //ReferalCategory uint256 constant ReferalCategory = 237; function ProfitManager() public { m_Owner = msg.sender; m_Paused = true; } function Unpause() public OnlyOwner() { m_Paused = false; } function Pause() public OnlyOwner() { require(m_Paused == false); m_Paused = true; } // 1 write function WithdrawProfitFunds(uint256 withdraw_amount, address beneficiary) public NotWhilePaused() OnlyOwner() { uint256 profit_funds = uint256(m_Database.Load(NullAddress, ProfitFundsCategory, 0)); require(withdraw_amount > 0); require(withdraw_amount <= profit_funds); require(beneficiary != address(0)); require(beneficiary != address(this)); require(beneficiary != address(m_Database)); profit_funds -= withdraw_amount; m_Database.Store(NullAddress, ProfitFundsCategory, 0, bytes32(profit_funds)); m_Database.TransferFunds(beneficiary, withdraw_amount); } // 1 write function WithdrawWinnings(uint256 withdraw_amount) public NotWhilePaused() { require(withdraw_amount > 0); uint256 withdrawal_funds = uint256(m_Database.Load(msg.sender, WithdrawalFundsCategory, 0)); require(withdraw_amount <= withdrawal_funds); withdrawal_funds -= withdraw_amount; m_Database.Store(msg.sender, WithdrawalFundsCategory, 0, bytes32(withdrawal_funds)); m_Database.TransferFunds(msg.sender, withdraw_amount); } function GetProfitFunds() view public OnlyOwner() returns (uint256 funds) { uint256 profit_funds = uint256(m_Database.Load(NullAddress, ProfitFundsCategory, 0)); return profit_funds; } function GetWithdrawalFunds(address target) view public NotWhilePaused() returns (uint256 funds) { funds = uint256(m_Database.Load(target, WithdrawalFundsCategory, 0)); } } contract AbstractDatabase { function() public payable; function ChangeOwner(address new_owner) public; function ChangeOwner2(address new_owner) public; function Store(address user, uint256 category, uint256 slot, bytes32 data) public; function Load(address user, uint256 category, uint256 index) public view returns (bytes32); function TransferFunds(address target, uint256 transfer_amount) public; function getRandom(uint256 upper, uint8 seed) public returns (uint256 number); }
* @dev Multiplies two numbers, throws on overflow./
function mul(uint8 a, uint8 b) internal pure returns (uint8) { if (a == 0) { return 0; } uint8 c = a * b; assert(c / a == b); return c; }
5,352,711
[ 1, 5002, 5259, 2795, 5600, 16, 1216, 603, 9391, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 14064, 12, 11890, 28, 279, 16, 2254, 28, 324, 13, 2713, 16618, 1135, 261, 11890, 28, 13, 288, 203, 3639, 309, 261, 69, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 3639, 2254, 28, 276, 273, 279, 380, 324, 31, 203, 3639, 1815, 12, 71, 342, 279, 422, 324, 1769, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /* Author: Philipp Schindler Source code and documentation available on Github: https://github.com/PhilippSchindler/ethdkg Copyright 2018 Philipp Schindler 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. */ contract DKG { struct Node { uint256 id; // the node's one based id, if id=0 the node has not registered or a dispute was successful uint256 deposit; uint256[2] pk; // the node's public key from group G1 (i.e. g1 * sk) uint256[4] bls_pk; // the node's public key from group G2 (i.e. g2 * sk) bytes32 key_distribution_hash; } event Registration(address node_adr, uint256 id, uint256 deposit, uint256[2] pk, uint256[4] bls_pk); event KeySharing(uint256 issuer, uint256[] encrypted_shares, uint256[] public_coefficients); event DisputeSuccessful(address bad_issuer_addr); uint256 constant g1x = 1; uint256 constant g1y = 2; uint256 constant g2xx = 11559732032986387107991004021392285783925812861821192530917403151452391805634; uint256 constant g2xy = 10857046999023057135944570762232829481370756359578518086990519993285655852781; uint256 constant g2yx = 4082367875863433681332203403145435568316851327593401208105741076214120093531; uint256 constant g2yy = 8495653923123431417604973247489272438418190587263600148770280649306958101930; uint256 constant GROUP_ORDER = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint256 constant FIELD_MODULUS = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint256[4] bls_group_pk; address[] registered_addresses; mapping (address => Node) nodes; bool public aborted; uint256 public constant DELTA_INCLUDE = 20; // needs to be appropriately set for the production system uint256 public constant DELTA_CONFIRM = 2; // needs to be appropriately set for the production system uint256 public constant PARTICIPATION_THRESHOLD = 3; // minimum number of nodes which need to register (inclusive) // uint256 public constant PARTICIPATION_LIMIT = 256; // maximum number of nodes allowed to register (inclusive) uint256 public T_CONTRACT_CREATION; // block number in which the contract instance was created uint256 public T_REGISTRATION_END; // block number of the last block where registration is possible uint256 public T_SHARING_END; // block number of the last block where key sharing is possible uint256 public T_DISPUTE_END; // block number of the last block where dispute is possible. uint256 public T_GROUP_KEY_UPLOAD; // block number of the block in which the group key is uploaded (dynamic) constructor() public { // potential optimization: could set all this values as constants during compile time // to save gas during deployment and for checking the guard conditions T_CONTRACT_CREATION = block.number; T_REGISTRATION_END = T_CONTRACT_CREATION + DELTA_CONFIRM + DELTA_INCLUDE; T_SHARING_END = T_REGISTRATION_END + DELTA_CONFIRM + DELTA_INCLUDE; T_DISPUTE_END = T_SHARING_END + DELTA_CONFIRM + DELTA_INCLUDE; } function in_registration_phase() public view returns(bool) { return block.number <= T_REGISTRATION_END; } function in_sharing_phase() public view returns(bool) { return (T_REGISTRATION_END < block.number) && (block.number <= T_SHARING_END); } function in_dispute_phase() public view returns(bool) { return (T_SHARING_END < block.number) && (block.number <= T_DISPUTE_END); } function in_finalization_phase() public view returns(bool) { return (T_DISPUTE_END < block.number) && (T_GROUP_KEY_UPLOAD == 0); } function registrations_confirmed() public view returns(bool) { return T_REGISTRATION_END + DELTA_CONFIRM <= block.number; } function sharing_confirmed() public view returns(bool) { return T_SHARING_END + DELTA_CONFIRM <= block.number; } function dispute_confirmed() public view returns(bool) { return T_DISPUTE_END + DELTA_CONFIRM <= block.number; } function group_key_confirmed() public view returns(bool) { return (T_GROUP_KEY_UPLOAD != 0) && (T_GROUP_KEY_UPLOAD + DELTA_CONFIRM <= block.number); } function register(uint256[2] pk, uint256[4] bls_pk, uint256[2] sk_knowledge_proof) public payable { require(in_registration_phase(), "registration failed (contract is not in registration phase)"); require(nodes[msg.sender].id == 0, "registration failed (account already registered a public key)"); require( bn128_check_pairing( // ensures that the given pk and bls_pk correspond to each other [ // i.e. that pk and bls_pk are of the form pk[0], pk[1], // pk = g1 * sk g2xx, g2xy, g2yx, g2yy, // bls_pk = -g2 * sk g1x, g1y, // for some secret key sk bls_pk[0], bls_pk[1], bls_pk[2], bls_pk[3] ]), "registration failed (bls public key is invalid)" ); require( verify_sk_knowledge(pk, sk_knowledge_proof), "registration failed (invalid proof of secret key knowlegde)" ); // add appropriate registration condition(s) here // e.g. require a minimum deposit amount or whitelist specific Ethereum accounts registered_addresses.push(msg.sender); uint256 id = registered_addresses.length; nodes[msg.sender].id = id; nodes[msg.sender].deposit = msg.value; nodes[msg.sender].pk[0] = pk[0]; nodes[msg.sender].pk[1] = pk[1]; nodes[msg.sender].bls_pk[0] = bls_pk[0]; nodes[msg.sender].bls_pk[1] = bls_pk[1]; nodes[msg.sender].bls_pk[2] = bls_pk[2]; nodes[msg.sender].bls_pk[3] = bls_pk[3]; emit Registration(msg.sender, id, msg.value, pk, bls_pk); } function share_key( uint256[] encrypted_shares, // Enc_kAB(s_i), each 256 bit uint256[] public_coefficients) // Cj, each 512 bit public { uint256 n = registered_addresses.length; uint256 t = (n / 2) + 1; uint256 issuer_id = nodes[msg.sender].id; require(in_sharing_phase(), "key sharing failed (contract is not in sharing phase)"); require(issuer_id > 0, "key sharing failed (ethereum account has not registered)"); require(encrypted_shares.length == n - 1, "key sharing failed (invalid number of encrypted shares provided)"); require(public_coefficients.length == t * 2 - 2, "key sharing failed (invalid number of commitments provided)"); // for optimization we only store the hash of the submitted data // and emit an event with the actual data nodes[msg.sender].key_distribution_hash = keccak256(abi.encodePacked(encrypted_shares, public_coefficients)); emit KeySharing(issuer_id, encrypted_shares, public_coefficients); } function dispute_public_coefficient( address issuer_addr, // the node which is accussed to have distributed (at least one) invalid coefficient uint256[] encrypted_shares, // the data from previous KeySharing event uint256[] public_coefficients, // the data from previous KeySharing event uint256 invalid_coefficient_idx // specifies any coefficient which is invalid (used for efficiency) ) public { Node storage issuer = nodes[issuer_addr]; Node storage verifier = nodes[msg.sender]; require(in_dispute_phase(), "dispute failed (contract is not in sharing phase)"); require(issuer.id > 0, "dispute failed/aborted (issuer not registered or slashed)"); require(verifier.id > 0, "dispute failed/aborted (verifier not registered or slashed)"); require(issuer.id != verifier.id, "dispute failed (self dispute is not allowed)"); require( issuer.key_distribution_hash == keccak256(abi.encodePacked(encrypted_shares, public_coefficients)), "dispute failed (encrypted shares and/or public coefficients not matching)" ); uint256 i = invalid_coefficient_idx * 2; require( !bn128_is_on_curve([public_coefficients[i], public_coefficients[i + 1]]), "dispute failed (coefficient is actually valid)" ); __slash__(issuer_addr); } function dispute_share( address issuer_addr, // the node which is accussed to have distributed an invalid share uint256[] encrypted_shares, // the data from previous KeyDistribution event uint256[] public_coefficients, // the data from previous KeyDistribution event uint256[2] decryption_key, // shared key between issuer and calling node uint256[2] decryption_key_proof) // NIZK proof, showing that decryption key is valid public { Node storage issuer = nodes[issuer_addr]; Node storage verifier = nodes[msg.sender]; require(in_dispute_phase(), "dispute failed (contract is not in sharing phase)"); require(issuer.id > 0, "dispute failed/aborted (issuer not registered or slashed)"); require(verifier.id > 0, "dispute failed/aborted (verifier not registered or slashed)"); require(issuer.id != verifier.id, "dispute failed (self dispute is not allowed)"); require( issuer.key_distribution_hash == keccak256(abi.encodePacked(encrypted_shares, public_coefficients)), "dispute failed (encrypted shares and/or public coefficients not matching)" ); require( verify_decryption_key(decryption_key, decryption_key_proof, verifier.pk, issuer.pk), "dispute failed (invalid decryption key or decryption key proof)" ); // compute share index i: // the index i is one-based (which is required!) (indepent of the correction below) // as the issuer does not provide a share for itself the index has to be corrected uint256 i = verifier.id; if (i > issuer.id) { i--; } // decryption of the share, (correct for one-based index i to make it zero-based) // We currently use a encryption/decryption by xoring the share with the hash of shared key and id as there are // currently no symmetric key encryption primitives available as EVM instructions. // This approach can be replaced once such a primitive or an alternative cheap implementation becomes available. uint256 share = encrypted_shares[i - 1] ^ uint256(keccak256(abi.encodePacked(decryption_key[0], verifier.id))); // verify that share is actually invalid // evaluate the polynom F(x) for x = i uint256 x = i; uint256[2] memory Fx = [issuer.pk[0], issuer.pk[1]]; uint256[2] memory tmp = bn128_multiply([public_coefficients[0], public_coefficients[1], x]); Fx = bn128_add([Fx[0], Fx[1], tmp[0], tmp[1]]); for (uint256 j = 2; j < public_coefficients.length; j += 2) { x = mulmod(x, i, GROUP_ORDER); tmp = bn128_multiply([public_coefficients[j], public_coefficients[j + 1], x]); Fx = bn128_add([Fx[0], Fx[1], tmp[0], tmp[1]]); } // and compare the result (stored in Fx) with g1*si uint256[2] memory Fi = bn128_multiply([g1x, g1y, share]); // require that share is actually invalid require(Fx[0] != Fi[0] || Fx[1] != Fi[1], "dispute failed (the provided share was valid)"); __slash__(issuer_addr); } // compute the group key in the elliptic curve group G1 // and verify the uploaded bls_group_pk from G2 with the pairing // only non-successfully-disputed keys form the group keys // calls abort if insufficient valid keys have been registered function upload_group_key(uint[4] _bls_group_pk) public returns(bool success) { require( in_finalization_phase(), "group key upload failed (key sharing / disputes not finsished, or group key already uploaded)" ); uint256 n = registered_addresses.length; uint256 t = (n / 2) + 1; Node memory node; uint256[2] memory group_pk; // find first (i.e. lowest index) valid registered node uint256 i = 0; do { node = nodes[registered_addresses[i]]; i += 1; } while((node.id == 0 || node.key_distribution_hash == 0) && i < n); if (i == n) { // in this case at most one nodes actually shared a valid key __abort__(); return false; } uint256 p = 1; // number of nodes which provided valid keys group_pk = node.pk; for ( ; i < registered_addresses.length; i++) { // sum up all valid pubic keys node = nodes[registered_addresses[i]]; if (node.id != 0 && node.key_distribution_hash != 0) { p++; group_pk = bn128_add([group_pk[0], group_pk[1], node.pk[0], node.pk[1]]); } } if (p < t) { __abort__(); return false; } // ensures that the given group_pk and bls_group_pk correspond to each other require( bn128_check_pairing( [ group_pk[0], group_pk[1], g2xx, g2xy, g2yx, g2yy, g1x, g1y, _bls_group_pk[0], _bls_group_pk[1], _bls_group_pk[2], _bls_group_pk[3] ]), "upload of group key failed (the submitted bls_group_pk does not correspond to group_pk)" ); bls_group_pk = _bls_group_pk; T_GROUP_KEY_UPLOAD = block.number; } function __slash__(address addr) private { emit DisputeSuccessful(addr); nodes[addr].id = 0; } // checks abort condition and aborts the contract if at least one abort condition is fulfilled function abort() public { // never abort during registration phase require(!in_registration_phase(), "abort failed (cannot abort during registration phase)"); uint256 n = registered_addresses.length; uint256 t = (n / 2) + 1; // abort is possible if not enough nodes joined the DKG protocol if (n < PARTICIPATION_THRESHOLD) { __abort__(); } // abort is possible if less then t nodes actually shared their keys without disputes else { require( T_SHARING_END < block.number, "abort failed (abort is only possible after key sharing phase ended)" ); uint256 p = 0; // number of nodes with shared their key without disputes for (uint256 i = 0; i < n; i++) { Node memory node = nodes[registered_addresses[i]]; // id != 0 ensures not was not slashed // hashkey_distribution_hash != 0 ensures that node has shared its key if ((node.id != 0) && node.key_distribution_hash != 0) { p++; } } require( p < t, "abort failed (abort is only possible if less than t nodes shared their key successfully)" ); __abort__(); } } // move the contract to the aborted state: // can e.g. be used to releases all the deposits to be withdrawn from the contract and evenly distribute // slashed deposists are evenly distributed to all other nodes function __abort__() private { aborted = true; } // verifies that the sender account knows the private key corresponding to the given public key function verify_sk_knowledge(uint[2] public_key, uint[2] proof) public returns (bool) { uint256[2] memory a = bn128_multiply([g1x, g1y, proof[1]]); uint256[2] memory b = bn128_multiply([public_key[0], public_key[1], proof[0]]); uint256[2] memory t = bn128_add([a[0], a[1], b[0], b[1]]); uint256 c = uint256( keccak256(abi.encodePacked(g1x, g1y, public_key[0], public_key[1], t[0], t[1], msg.sender))); return proof[0] == c; } // implement the verification procedure for the NIZK DLEQ (discrete logarithm equalty) proof function verify_decryption_key( uint256[2] decryption_key, uint256[2] correctness_proof, // DLEQ challenge and response uint256[2] verifier_pk, uint256[2] issuer_pk) public returns (bool key_valid) { // equivalent to DLEQ_verify(G1, issuer_pk, verifier_pk, decryption_key, correctness_proof) in python uint256[2] memory tmp1; // two temporary variables uint256[2] memory tmp2; tmp1 = bn128_multiply([g1x, g1y, correctness_proof[1]]); tmp2 = bn128_multiply([verifier_pk[0], verifier_pk[1], correctness_proof[0]]); uint256[2] memory a1 = bn128_add([tmp1[0], tmp1[1], tmp2[0], tmp2[1]]); tmp1 = bn128_multiply([issuer_pk[0], issuer_pk[1], correctness_proof[1]]); tmp2 = bn128_multiply([decryption_key[0], decryption_key[1], correctness_proof[0]]); uint256[2] memory a2 = bn128_add([tmp1[0], tmp1[1], tmp2[0], tmp2[1]]); uint256 challenge_computed = uint256( keccak256(abi.encodePacked(a1, a2, g1x, g1y, verifier_pk, issuer_pk, decryption_key))); key_valid = correctness_proof[0] == challenge_computed; } function verify_signature(uint256[4] bls_pk, bytes32 message, uint256[2] signature) public returns (bool signature_valid) { uint[2] memory h = bn128_map_to_G1(message); signature_valid = bn128_check_pairing( [ signature[0], signature[1], g2xx, g2xy, g2yx, g2yy, h[0], h[1], bls_pk[0], bls_pk[1], bls_pk[2], bls_pk[3] ]); } function bn128_add(uint256[4] input) public returns (uint256[2] result) { // computes P + Q // input: 4 values of 256 bit each // *) x-coordinate of point P // *) y-coordinate of point P // *) x-coordinate of point Q // *) y-coordinate of point Q bool success; assembly { // 0x06 id of precompiled bn256Add contract // 0 number of ether to transfer // 128 size of call parameters, i.e. 128 bytes total // 64 size of call return value, i.e. 64 bytes / 512 bit for a BN256 curve point success := call(not(0), 0x06, 0, input, 128, result, 64) } require(success, "elliptic curve addition failed"); } function bn128_multiply(uint256[3] input) public returns (uint256[2] result) { // computes P*x // input: 3 values of 256 bit each // *) x-coordinate of point P // *) y-coordinate of point P // *) scalar x bool success; assembly { // 0x07 id of precompiled bn256ScalarMul contract // 0 number of ether to transfer // 96 size of call parameters, i.e. 96 bytes total (256 bit for x, 256 bit for y, 256 bit for scalar) // 64 size of call return value, i.e. 64 bytes / 512 bit for a BN256 curve point success := call(not(0), 0x07, 0, input, 96, result, 64) } require(success, "elliptic curve multiplication failed"); } function bn128_is_on_curve(uint[2] point) public returns(bool valid) { // checks if the given point is a valid point from the first elliptic curve group // by trying an addition with the generator point g1 uint256[4] memory input = [point[0], point[1], g1x, g1y]; assembly { // 0x06 id of precompiled bn256Add contract // 0 number of ether to transfer // 128 size of call parameters, i.e. 128 bytes total // 64 size of call return value, i.e. 64 bytes / 512 bit for a BN256 curve point valid := call(not(0), 0x06, 0, input, 128, input, 64) } } function bn128_check_pairing(uint256[12] input) public returns (bool) { uint256[1] memory result; bool success; assembly { // 0x08 id of precompiled bn256Pairing contract (checking the elliptic curve pairings) // 0 number of ether to transfer // 384 size of call parameters, i.e. 12*256 bits == 384 bytes // 32 size of result (one 32 byte boolean!) success := call(sub(gas, 2000), 0x08, 0, input, 384, result, 32) } require(success, "elliptic curve pairing failed"); return result[0] == 1; } function bn128_map_to_G1(bytes32 data) public returns (uint[2] point) { uint256 ctr = 0; while (true) { uint256 x = uint256(keccak256(abi.encodePacked(ctr, data))); bool b = x & 1 == 1; // extract last bit of the hash x >>= 2; // drop last 2 bits of the hash, a coordinate is a 254 bit number if (x < FIELD_MODULUS) { // p... FIELD_MODULUS // z = x**3 + 3 (mod p) uint256 z = (bigModExp([32, 32, 32, x, 3, FIELD_MODULUS]) + 3) % FIELD_MODULUS; // y = sqrt(z) = z**((p + 1) / 4) mod p uint256 y = bigModExp([32, 32, 32, z, (FIELD_MODULUS + 1) >> 2, FIELD_MODULUS]); // checks if y is indeed a square root of z mod p if (bigModExp([32, 32, 32, y, 2, FIELD_MODULUS]) == z) { if (b) { y = (FIELD_MODULUS - y); } return [x, y]; } } ctr++; } } function bigModExp(uint256[6] input) public returns (uint256) { // call the precompiled contract to compute the b^e mod m // used the following arguments in the given order // - length of the base b // - length of the exponent e // - length of the modulus m // - the base b itself // - the exponent e itself // - the modulus m itself // we use 256 bit integers for all of the above values bool success; uint256[1] memory result; assembly { // 0x05 id of precompiled bigModExp contract // 0 number of ether to transfer // 192 size of call parameters, i.e. 192 bytes total (6x 256 bit) // 32 size of call return value, i.e. 32 bytes / 256 bit success := call(not(0), 0x05, 0, input, 192, result, 32) } require(success, "bigModExp operation failed"); return result[0]; } }
0x06 id of precompiled bn256Add contract 0 number of ether to transfer 128 size of call parameters, i.e. 128 bytes total 64 size of call return value, i.e. 64 bytes / 512 bit for a BN256 curve point
function bn128_is_on_curve(uint[2] point) assembly { valid := call(not(0), 0x06, 0, input, 128, input, 64) }
2,538,307
[ 1, 20, 92, 7677, 377, 612, 434, 675, 19397, 18254, 5034, 986, 6835, 374, 3639, 1300, 434, 225, 2437, 358, 7412, 8038, 1377, 963, 434, 745, 1472, 16, 277, 18, 73, 18, 8038, 1731, 2078, 5178, 4202, 963, 434, 745, 327, 460, 16, 277, 18, 73, 18, 5178, 1731, 342, 13908, 2831, 364, 279, 605, 50, 5034, 8882, 1634, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18254, 10392, 67, 291, 67, 265, 67, 16683, 12, 11890, 63, 22, 65, 1634, 13, 203, 3639, 19931, 288, 203, 5411, 923, 519, 745, 12, 902, 12, 20, 3631, 374, 92, 7677, 16, 374, 16, 810, 16, 8038, 16, 810, 16, 5178, 13, 203, 3639, 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 ]
./full_match/3/0x5ddeD6b7328924cebbc8063744CB73F4EE5F19A5/sources/browser/FairSwap.sol
* "view" allowing each party to review the terms of the swap prior to accepting/
function reviewTerms() public view returns ( address party1, address contract1, uint256 party1_Tokens, address party2, address contract2, uint256 party2_Tokens ) { PartyTerms memory ptA = partyTerms[a]; PartyTerms memory ptB = partyTerms[b]; return ( a, ptA.sourceContract, ptA.tokensToSwap, b, ptB.sourceContract, ptB.tokensToSwap ); }
14,156,371
[ 1, 6, 1945, 6, 15632, 1517, 18285, 358, 10725, 326, 6548, 434, 326, 7720, 6432, 358, 25806, 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, 10725, 11673, 1435, 1071, 1476, 1135, 261, 203, 3639, 1758, 18285, 21, 16, 1758, 6835, 21, 16, 2254, 5034, 18285, 21, 67, 5157, 16, 7010, 3639, 1758, 18285, 22, 16, 1758, 6835, 22, 16, 2254, 5034, 18285, 22, 67, 5157, 203, 565, 262, 288, 203, 3639, 6393, 93, 11673, 3778, 5818, 37, 273, 18285, 11673, 63, 69, 15533, 203, 3639, 6393, 93, 11673, 3778, 5818, 38, 273, 18285, 11673, 63, 70, 15533, 203, 3639, 327, 261, 203, 5411, 279, 16, 5818, 37, 18, 3168, 8924, 16, 5818, 37, 18, 7860, 774, 12521, 16, 203, 5411, 324, 16, 5818, 38, 18, 3168, 8924, 16, 5818, 38, 18, 7860, 774, 12521, 203, 3639, 11272, 203, 565, 289, 203, 377, 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 ]
./partial_match/1/0x99937d00F549e222fe8f144C12A161707a766F4c/sources/TnmtToken.sol
* Sets the contract default royalties. @dev Only callable by the owner/
function setDefaultRoyalty(uint96 value) external onlyOwner returns(bool) { _setDefaultRoyalty(owner(), value); return true; }
2,661,676
[ 1, 2785, 326, 6835, 805, 721, 93, 2390, 606, 18, 225, 5098, 4140, 635, 326, 3410, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9277, 54, 13372, 15006, 12, 11890, 10525, 460, 13, 3903, 1338, 5541, 1135, 12, 6430, 13, 288, 203, 3639, 389, 542, 1868, 54, 13372, 15006, 12, 8443, 9334, 460, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 21281, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-03 */ /** Contract is by captain ike and frens ,--. ,--. ,--.,--. ,---. ,--,--. ,---. ,-' '-. ,--,--.`--',--,--, `--'| |,-. ,---. | .--'' ,-. || .-. |'-. .-'' ,-. |,--.| \ ,--.| /| .-. : \ `--.\ '-' || '-' ' | | \ '-' || || || | | || \ \\ --. `---' `--`--'| |-' `--' `--`--'`--'`--''--' `--'`--'`--'`----' `--' */ // SPDX-License-Identifier: GPL-3.0 // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { 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.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() { 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/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/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/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/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: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // 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/utils/Strings.sol 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); } } // File: @openzeppelin/contracts/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/ERC721.sol pragma solidity ^0.8.0; /** * @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 {} } // File: contracts/CaptainIke.sol pragma solidity ^0.8.4; contract CaptainIke is Ownable, ERC721 { event Mint(uint256 indexed _tokenId); uint256 public maxSupply = 6942; // Maximum tokens that can be minted uint256 public limitPerAccount = 69; // Maximum mints per wallet uint256 public mintFee = 0.069420 ether; // Price per mint uint256 public totalSupply = 0; // This is our mint counter as well mapping(uint256 => string) public tokenURIs; // Metadata location, updatable by owner mapping(address => uint256) public mintCounts; // Amount minted per user string public _baseTokenURI = "https://gateway.pinata.cloud/ipfs/QmQ5GQR8k8mBwGvWeAfeW2uYE4wHLPzRBAhnCPUZpRgSBX?preview=1"; // Same for all tokens mapping(address => bool) public canWithdraw; bool public paused = true; constructor() payable ERC721("CaptainIke", "Icarus") {} function mint(address to, uint256 quantity) external payable { require( totalSupply + quantity <= maxSupply, "maxSupply of mints already reached" ); if (msg.sender != owner()) { require(!paused, "Paused"); require( mintCounts[to] + quantity <= limitPerAccount, "max 69 mints per account" ); require( quantity * mintFee == msg.value, "Pay 0.069420 eth per mint" ); } mintCounts[to] += quantity; for (uint256 i = 0; i < quantity; i++) { totalSupply += 1; // 1-indexed instead of 0 _mint(to, totalSupply); emit Mint(totalSupply); } } /** * @dev Returns a URI for a given token ID's metadata */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { return string(abi.encodePacked(_baseTokenURI, Strings.toString(_tokenId))); } // ADMIN FUNCTIONALITY /** * @dev Withdraw ETH */ function withdraw() public { require(msg.sender == owner() || canWithdraw[msg.sender], "Nice try!"); uint256 amount = address(this).balance; (bool success, ) = msg.sender.call{value: amount}(""); require(success, "Failed to send ether"); } /** * @dev Pauses or unpauses the contract */ function setPaused(bool _paused) public onlyOwner { paused = _paused; } /** * @dev Adds an address to the withdraw whitelist */ function setWhitelist(address addr, bool val) public onlyOwner { canWithdraw[addr] = val; } /** * @dev Updates the base token URI for the metadata */ function setBaseTokenURI(string memory __baseTokenURI) public onlyOwner { _baseTokenURI = __baseTokenURI; } }
* @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; }
2,311,572
[ 1, 1429, 18881, 23178, 434, 326, 6835, 358, 279, 394, 2236, 21863, 2704, 5541, 68, 2934, 4480, 1338, 506, 2566, 635, 326, 783, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 5024, 1338, 5541, 288, 203, 2583, 12, 203, 394, 5541, 480, 1758, 12, 20, 3631, 203, 315, 5460, 429, 30, 394, 3410, 353, 326, 3634, 1758, 6, 203, 11272, 203, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 394, 5541, 1769, 203, 389, 8443, 273, 394, 5541, 31, 203, 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 ]
pragma solidity ^0.4.16; /** * @title SafeMath * @dev Math operations with safety checks that throw on error * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ library SafeMath { function mul(uint256 a, uint256 b) pure internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) pure internal returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) pure internal returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) pure internal 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; /** * @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() { if (msg.sender != owner) { revert(); } _; } /** * @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 ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { uint256 public tokenTotalSupply; function balanceOf(address who) public view returns(uint256); function allowance(address owner, address spender) public view returns(uint256); function transfer(address to, uint256 value) public returns (bool success); event Transfer(address indexed from, address indexed to, uint256 value); function transferFrom(address from, address to, uint256 value) public returns (bool success); function approve(address spender, uint256 value) public returns (bool success); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() public view returns (uint256 availableSupply); } /** * @title Standard ERC20 token * * @dev Implemantation of the basic standart 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 SaveToken is ERC20, Ownable { using SafeMath for uint; string public name = "SaveToken"; string public symbol = "SAVE"; uint public decimals = 18; mapping(address => uint256) affiliate; function getAffiliate(address who) public view returns(uint256) { return affiliate[who]; } struct AffSender { bytes32 aff_code; uint256 amount; } uint public no_aff = 0; mapping(uint => AffSender) affiliate_senders; function getAffiliateSender(bytes32 who) public view returns(uint256) { for (uint i = 0; i < no_aff; i++) { if(affiliate_senders[i].aff_code == who) { return affiliate_senders[i].amount; } } return 1; } function getAffiliateSenderPosCode(uint pos) public view returns(bytes32) { if(pos >= no_aff) { return 1; } return affiliate_senders[pos].aff_code; } function getAffiliateSenderPosAmount(uint pos) public view returns(uint256) { if(pos >= no_aff) { return 2; } return affiliate_senders[pos].amount; } uint256 public tokenTotalSupply = 0; uint256 public trashedTokens = 0; uint256 public hardcap = 350 * 1000000 * (10 ** decimals); // 350 million tokens uint public ethToToken = 6000; // 1 eth buys 6 thousands tokens uint public noContributors = 0; //-----------------------------bonus periods uint public tokenBonusForFirst = 10; // multiplyer in % uint256 public soldForFirst = 0; uint256 public maximumTokensForFirst = 55 * 1000000 * (10 ** decimals); // 55 million uint public tokenBonusForSecond = 5; // multiplyer in % uint256 public soldForSecond = 0; uint256 public maximumTokensForSecond = 52.5 * 1000000 * (10 ** decimals); // 52 million 500 thousands uint public tokenBonusForThird = 4; // multiplyer in % uint256 public soldForThird = 0; uint256 public maximumTokensForThird = 52 * 1000000 * (10 ** decimals); // 52 million uint public tokenBonusForForth = 3; // multiplyer in % uint256 public soldForForth = 0; uint256 public maximumTokensForForth = 51.5 * 1000000 * (10 ** decimals); // 51 million 500 thousands uint public tokenBonusForFifth = 0; // multiplyer in % uint256 public soldForFifth = 0; uint256 public maximumTokensForFifth = 50 * 1000000 * (10 ** decimals); // 50 million uint public presaleStart = 1519344000; //2018-02-23T00:00:00+00:00 uint public presaleEnd = 1521849600; //2018-03-24T00:00:00+00:00 uint public weekOneStart = 1524355200; //2018-04-22T00:00:00+00:00 uint public weekTwoStart = 1525132800; //2018-05-01T00:00:00+00:00 uint public weekThreeStart = 1525824000; //2018-05-09T00:00:00+00:00 uint public weekFourStart = 1526601600; //2018-05-18T00:00:00+00:00 uint public tokenSaleEnd = 1527292800; //2018-05-26T00:00:00+00:00 uint public saleOn = 1; uint public disown = 0; //uint256 public maximumTokensForReserve = 89 * 1000000 * (10 ** decimals); // 89 million address public ownerVault; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { if (msg.data.length < size + 4) { revert(); } _; } /** * @dev modifier to allow token creation only when the hardcap has not been reached */ modifier isUnderHardCap() { require(tokenTotalSupply <= hardcap); _; } /** * @dev Constructor */ function SaveToken() public { ownerVault = msg.sender; } /** * @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 onlyPayloadSize(2 * 32) returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3 * 32) returns (bool success) { uint256 _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Transfer tokens from one address to another according to off exchange agreements * @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 masterTransferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public onlyOwner returns (bool success) { if(disown == 1) revert(); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); Transfer(_from, _to, _value); return true; } function totalSupply() public view returns (uint256 availableSupply) { return tokenTotalSupply; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns(uint256 balance) { return balances[_owner]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @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 success) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) { revert(); } allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens than 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 remaining) { return allowed[_owner][_spender]; } /** * @dev Allows the owner to change the token exchange rate. * @param _ratio the new eth to token ration */ function changeEthToTokenRation(uint8 _ratio) public onlyOwner { if (_ratio != 0) { ethToToken = _ratio; } } /** * @dev convenience show balance */ function showEthBalance() view public returns(uint256 remaining) { return this.balance; } /** * @dev burn tokens if need to * @param value token with decimals * @param from burn address */ function decreaseSupply(uint256 value, address from) public onlyOwner returns (bool) { if(disown == 1) revert(); balances[from] = balances[from].sub(value); trashedTokens = trashedTokens.add(value); tokenTotalSupply = tokenTotalSupply.sub(value); Transfer(from, 0, value); return true; } /** * Send ETH with affilate code. */ function BuyTokensWithAffiliate(address _affiliate) public isUnderHardCap payable { affiliate[_affiliate] += msg.value; if (_affiliate == msg.sender){ revert(); } BuyTokens(); } /** * Allows owner to create tokens without ETH */ function mintTokens(address _address, uint256 amount) public onlyOwner isUnderHardCap { if(disown == 1) revert(); if (amount + tokenTotalSupply > hardcap) revert(); if (amount < 1) revert(); //add tokens to balance balances[_address] = balances[_address] + amount; //increase total tokens tokenTotalSupply = tokenTotalSupply.add(amount); Transfer(this, _address, amount); noContributors++; } /** * @dev Change owner vault. */ function changeOwnerVault(address new_vault) public onlyOwner { ownerVault = new_vault; } /** * @dev Change periods. */ function changePeriod(uint period_no, uint new_value) public onlyOwner { if(period_no == 1) { presaleStart = new_value; } else if(period_no == 2) { presaleEnd = new_value; } else if(period_no == 3) { weekOneStart = new_value; } else if(period_no == 4) { weekTwoStart = new_value; } else if(period_no == 5) { weekThreeStart = new_value; } else if(period_no == 6) { weekFourStart = new_value; } else if(period_no == 7) { tokenSaleEnd = new_value; } } /** * @dev Change saleOn. */ function changeSaleOn(uint new_value) public onlyOwner { if(disown == 1) revert(); saleOn = new_value; } /** * @dev No more god like. */ function changeDisown(uint new_value) public onlyOwner { if(new_value == 1) { disown = 1; } } /** * @dev Allows anyone to create tokens by depositing ether. */ function BuyTokens() public isUnderHardCap payable { uint256 tokens; uint256 bonus; if(saleOn == 0) revert(); if (now < presaleStart) revert(); //this is pause period if (now >= presaleEnd && now <= weekOneStart) revert(); //sale has ended if (now >= tokenSaleEnd) revert(); //pre-sale if (now >= presaleStart && now <= presaleEnd) { bonus = ethToToken.mul(msg.value).mul(tokenBonusForFirst).div(100); tokens = ethToToken.mul(msg.value).add(bonus); soldForFirst = soldForFirst.add(tokens); if (soldForFirst > maximumTokensForFirst) revert(); } //public first week if (now >= weekOneStart && now <= weekTwoStart) { bonus = ethToToken.mul(msg.value).mul(tokenBonusForSecond).div(100); tokens = ethToToken.mul(msg.value).add(bonus); soldForSecond = soldForSecond.add(tokens); if (soldForSecond > maximumTokensForSecond.add(maximumTokensForFirst).sub(soldForFirst)) revert(); } //public second week if (now >= weekTwoStart && now <= weekThreeStart) { bonus = ethToToken.mul(msg.value).mul(tokenBonusForThird).div(100); tokens = ethToToken.mul(msg.value).add(bonus); soldForThird = soldForThird.add(tokens); if (soldForThird > maximumTokensForThird.add(maximumTokensForFirst).sub(soldForFirst).add(maximumTokensForSecond).sub(soldForSecond)) revert(); } //public third week if (now >= weekThreeStart && now <= weekFourStart) { bonus = ethToToken.mul(msg.value).mul(tokenBonusForForth).div(100); tokens = ethToToken.mul(msg.value).add(bonus); soldForForth = soldForForth.add(tokens); if (soldForForth > maximumTokensForForth.add(maximumTokensForFirst).sub(soldForFirst).add(maximumTokensForSecond).sub(soldForSecond).add(maximumTokensForThird).sub(soldForThird)) revert(); } //public forth week if (now >= weekFourStart && now <= tokenSaleEnd) { bonus = ethToToken.mul(msg.value).mul(tokenBonusForFifth).div(100); tokens = ethToToken.mul(msg.value).add(bonus); soldForFifth = soldForFifth.add(tokens); if (soldForFifth > maximumTokensForFifth.add(maximumTokensForFirst).sub(soldForFirst).add(maximumTokensForSecond).sub(soldForSecond).add(maximumTokensForThird).sub(soldForThird).add(maximumTokensForForth).sub(soldForForth)) revert(); } if (tokens == 0) { revert(); } if (tokens + tokenTotalSupply > hardcap) revert(); //add tokens to balance balances[msg.sender] = balances[msg.sender] + tokens; //increase total tokens tokenTotalSupply = tokenTotalSupply.add(tokens); Transfer(this, msg.sender, tokens); noContributors++; } /** * @dev Allows the owner to send the funds to the vault. * @param _amount the amount in wei to send */ function withdrawEthereum(uint256 _amount) public onlyOwner { require(_amount <= this.balance); // wei if (!ownerVault.send(_amount)) { revert(); } Transfer(this, ownerVault, _amount); } // function getReservedTokens() public view returns (uint256) // { // if (checkIsPublicTime() == false) return 0; // return hardcap - maximumTokensForPublic + maximumTokensForPrivate - tokenTotalSupply; // } function transferReservedTokens(uint256 _amount) public onlyOwner { if(disown == 1) revert(); if (now <= tokenSaleEnd) revert(); assert(_amount <= (hardcap - tokenTotalSupply) ); balances[ownerVault] = balances[ownerVault] + _amount; tokenTotalSupply = tokenTotalSupply + _amount; Transfer(this, ownerVault, _amount); } function() external payable { BuyTokens(); } }
2018-04-22T00:00:00+00:00
uint public weekOneStart = 1524355200;
11,736,633
[ 1, 21849, 17, 3028, 17, 3787, 56, 713, 30, 713, 30, 713, 15, 713, 30, 713, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 1071, 4860, 3335, 1685, 273, 4711, 3247, 23, 2539, 6976, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.0; import "@c-layer/common/contracts/call/DelegateCall.sol"; import "@c-layer/common/contracts/call/DelegateCallView.sol"; import "../interface/IVotingSessionManager.sol"; import "./VotingSessionStorage.sol"; /** * @title VotingSessionManager * @dev VotingSessionManager contract * @author Cyril Lapinte - <[email protected]> * SPDX-License-Identifier: MIT * * Error messages * VM01: Session doesn't exist * VM02: Token is invalid * VM03: Delegate is invalid * VM04: Token has no valid core * VM05: Only contract owner may define its sponsor */ contract VotingSessionManager is IVotingSessionManager, DelegateCallView, VotingSessionStorage { using DelegateCall for address; modifier onlyOperator() { require(core_.hasProxyPrivilege( msg.sender, address(this), msg.sig), "VM01"); _; } /** * @dev constructor */ constructor(ITokenProxy _token, IVotingSessionDelegate _delegate) { defineContractsInternal(_token, _delegate); resolutionRequirements[ANY_TARGET][ANY_METHOD] = ResolutionRequirement(DEFAULT_MAJORITY, DEFAULT_QUORUM, DEFAULT_EXECUTION_THRESHOLD); } /** * @dev token */ function contracts() public override view returns ( IVotingSessionDelegate delegate, ITokenProxy token, ITokenCore core) { return (delegate_, token_, core_); } /** * @dev sessionRule */ function sessionRule() public override view returns ( uint64 campaignPeriod, uint64 votingPeriod, uint64 executionPeriod, uint64 gracePeriod, uint64 periodOffset, uint8 openProposals, uint8 maxProposals, uint8 maxProposalsOperator, uint256 newProposalThreshold, address[] memory nonVotingAddresses) { return ( sessionRule_.campaignPeriod, sessionRule_.votingPeriod, sessionRule_.executionPeriod, sessionRule_.gracePeriod, sessionRule_.periodOffset, sessionRule_.openProposals, sessionRule_.maxProposals, sessionRule_.maxProposalsOperator, sessionRule_.newProposalThreshold, sessionRule_.nonVotingAddresses); } /** * @dev resolutionRequirement */ function resolutionRequirement(address _target, bytes4 _method) public override view returns ( uint128 majority, uint128 quorum, uint256 executionThreshold) { ResolutionRequirement storage requirement = resolutionRequirements[_target][_method]; return ( requirement.majority, requirement.quorum, requirement.executionThreshold); } /** * @dev oldestSessionId */ function oldestSessionId() public override view returns (uint256) { return oldestSessionId_; } /** * @dev currentSessionId */ function currentSessionId() public override view returns (uint256) { return currentSessionId_; } /** * @dev session */ function session(uint256 _sessionId) public override view returns ( uint64 campaignAt, uint64 voteAt, uint64 executionAt, uint64 graceAt, uint64 closedAt, uint256 proposalsCount, uint256 participation, uint256 totalSupply, uint256 votingSupply) { Session storage session_ = sessions[_sessionId]; return ( session_.campaignAt, session_.voteAt, session_.executionAt, session_.graceAt, session_.closedAt, session_.proposalsCount, session_.participation, session_.totalSupply, session_.votingSupply); } /** * @dev sponsorOf */ function sponsorOf(address _voter) public override view returns (address address_, uint64 until) { Sponsor storage sponsor_ = sponsors[_voter]; address_ = sponsor_.address_; until = sponsor_.until; } /** * @dev lastVoteOf */ function lastVoteOf(address _voter) public override view returns (uint64 at) { return lastVotes[_voter]; } /** * @dev proposal */ function proposal(uint256 _sessionId, uint8 _proposalId) public override view returns ( string memory name, string memory url, bytes32 proposalHash, address resolutionTarget, bytes memory resolutionAction) { Proposal storage proposal_ = sessions[_sessionId].proposals[_proposalId]; return ( proposal_.name, proposal_.url, proposal_.proposalHash, proposal_.resolutionTarget, proposal_.resolutionAction); } /** * @dev proposalData */ function proposalData(uint256 _sessionId, uint8 _proposalId) public override view returns ( address proposedBy, uint128 requirementMajority, uint128 requirementQuorum, uint256 executionThreshold, uint8 dependsOn, uint8 alternativeOf, uint256 alternativesMask, uint256 approvals) { Proposal storage proposal_ = sessions[_sessionId].proposals[_proposalId]; return ( proposal_.proposedBy, proposal_.requirement.majority, proposal_.requirement.quorum, proposal_.requirement.executionThreshold, proposal_.dependsOn, proposal_.alternativeOf, proposal_.alternativesMask, proposal_.approvals); } /** * @dev nextSessionAt */ function nextSessionAt(uint256) public override view returns (uint256) { return _delegateCallUint256(address(delegate_)); } /** * @dev sessionStateAt */ function sessionStateAt(uint256, uint256) public override view returns (SessionState) { return SessionState(_delegateCallUint256(address(delegate_))); } /** * @dev newProposalThresholdAt */ function newProposalThresholdAt(uint256, uint256) public override view returns (uint256) { return _delegateCallUint256(address(delegate_)); } /** * @dev proposalApproval */ function proposalApproval(uint256, uint8) public override view returns (bool) { return _delegateCallBool(address(delegate_)); } /** * @dev proposalStateAt */ function proposalStateAt(uint256, uint8, uint256) public override view returns (ProposalState) { return ProposalState(_delegateCallUint256(address(delegate_))); } /** * @dev define contracts */ function defineContracts(ITokenProxy _token, IVotingSessionDelegate _delegate) public override onlyOperator() returns (bool) { return defineContractsInternal(_token, _delegate); } /** * @dev updateSessionRule */ function updateSessionRule( uint64, uint64, uint64, uint64, uint64, uint8, uint8, uint8, uint256, address[] memory) public override onlyOperator() returns (bool) { return address(delegate_)._delegateCall(); } /** * @dev updateResolutionRequirements */ function updateResolutionRequirements( address[] memory, bytes4[] memory, uint128[] memory, uint128[] memory, uint256[] memory) public override onlyOperator() returns (bool) { return address(delegate_)._delegateCall(); } /** * @dev defineSponsor */ function defineSponsor(address _sponsor, uint64 _until) public override returns (bool) { sponsors[msg.sender] = Sponsor(_sponsor, _until); emit SponsorDefined(msg.sender, _sponsor, _until); return true; } /** * @dev defineSponsorOf */ function defineSponsorOf(Ownable _contract, address _sponsor, uint64 _until) public override returns (bool) { require(_contract.owner() == msg.sender, "VM05"); sponsors[address(_contract)] = Sponsor(_sponsor, _until); emit SponsorDefined(address(_contract), _sponsor, _until); return true; } /** * @dev defineProposal */ function defineProposal(string memory, string memory, bytes32, address, bytes memory, uint8, uint8) public override returns (bool) { return address(delegate_)._delegateCall(); } /** * @dev updateProposal */ function updateProposal( uint8, string memory, string memory, bytes32, address, bytes memory, uint8, uint8) public override returns (bool) { return address(delegate_)._delegateCall(); } /** * @dev cancelProposal */ function cancelProposal(uint8) public override returns (bool) { return address(delegate_)._delegateCall(); } /** * @dev submitVote */ function submitVote(uint256) public override returns (bool) { return address(delegate_)._delegateCall(); } /** * @dev submitVotesOnBehalf */ function submitVotesOnBehalf(address[] memory, uint256) public override returns (bool) { return address(delegate_)._delegateCall(); } /** * @dev execute resolutions */ function executeResolutions(uint8[] memory) public override returns (bool) { return address(delegate_)._delegateCall(); } /** * @dev archiveSession **/ function archiveSession() public override returns (bool) { return address(delegate_)._delegateCall(); } /** * @dev define contracts internal */ function defineContractsInternal(ITokenProxy _token, IVotingSessionDelegate _delegate) internal returns (bool) { require(address(_token) != address(0), "VM02"); require(address(_delegate) != address(0), "VM03"); ITokenCore core = ITokenCore(_token.core()); require(address(core) != address(0), "VM04"); if (token_ != _token || core_ != core) { token_ = _token; core_ = core; emit TokenDefined(address(token_), address(core_)); } if (delegate_ != _delegate) { delegate_ = _delegate; emit DelegateDefined(address(delegate_)); } return true; } }
* @dev submitVotesOnBehalf/
function submitVotesOnBehalf(address[] memory, uint256) public override returns (bool) { return address(delegate_)._delegateCall(); }
2,475,453
[ 1, 9297, 29637, 1398, 1919, 20222, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 4879, 29637, 1398, 1919, 20222, 12, 2867, 8526, 3778, 16, 2254, 5034, 13, 1071, 3849, 1135, 261, 6430, 13, 203, 225, 288, 203, 565, 327, 1758, 12, 22216, 67, 2934, 67, 22216, 1477, 5621, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0x2148a45E33050A799b3fEb906da7644466F2F2aC/sources/contracts/Lottery.sol
every ticket purchased adds this much to the timer
uint256 public newTicketStep = 30 seconds;
13,181,841
[ 1, 20434, 9322, 5405, 343, 8905, 4831, 333, 9816, 358, 326, 5441, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 11890, 5034, 1071, 394, 13614, 4160, 273, 5196, 3974, 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 ]
./partial_match/5/0x89D9f11e962f2Eb5a4c8c3c057199b6e7Eafb63B/sources/Factory.sol
status of the request.
Status status;
16,834,079
[ 1, 2327, 434, 326, 590, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2685, 225, 1267, 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 ]
automat sg { #region MODIF_TYPE:ADV // ------------------------------------------------------ // наречия, которые могут модифицировать другие наречия, // выступая в роли предшествующих модификаторов. // ------------------------------------------------------ tag eng_adverb:straight{ MODIF_TYPE:ADV } // Go straight back tag eng_adverb:impressively{ MODIF_TYPE:ADV } // The students progressed impressively fast. tag eng_adverb:only{ MODIF_TYPE:ADV } // We perceived the change only dimly. tag eng_adverb:almost{ MODIF_TYPE:ADV } tag eng_adverb:at least{ MODIF_TYPE:ADV } tag eng_adverb:a little{ MODIF_TYPE:ADV } tag eng_adverb:a bit{ MODIF_TYPE:ADV } tag eng_adverb:a little bit{ MODIF_TYPE:ADV } tag eng_adverb:a little while{ MODIF_TYPE:ADV } tag eng_adverb:pretty{ MODIF_TYPE:ADV } tag eng_adverb:always{ MODIF_TYPE:ADV } tag eng_adverb:extremely{ MODIF_TYPE:ADV } tag eng_adverb:exceptionally{ MODIF_TYPE:ADV } tag eng_adverb:unbelievably{ MODIF_TYPE:ADV } tag eng_adverb:incurably{ MODIF_TYPE:ADV } tag eng_adverb:extraordinarily{ MODIF_TYPE:ADV } tag eng_adverb:jolly{ MODIF_TYPE:ADV } tag eng_adverb:mighty{ MODIF_TYPE:ADV } tag eng_adverb:damn{ MODIF_TYPE:ADV } tag eng_adverb:so{ MODIF_TYPE:ADV } tag eng_adverb:exceedingly{ MODIF_TYPE:ADV } tag eng_adverb:overly{ MODIF_TYPE:ADV } tag eng_adverb:downright{ MODIF_TYPE:ADV } tag eng_adverb:plumb{ MODIF_TYPE:ADV } tag eng_adverb:vitally{ MODIF_TYPE:ADV } tag eng_adverb:abundantly{ MODIF_TYPE:ADV } tag eng_adverb:chronically{ MODIF_TYPE:ADV } tag eng_adverb:frightfully{ MODIF_TYPE:ADV } tag eng_adverb:genuinely{ MODIF_TYPE:ADV } tag eng_adverb:humanly{ MODIF_TYPE:ADV } tag eng_adverb:patently{ MODIF_TYPE:ADV } tag eng_adverb:singularly{ MODIF_TYPE:ADV } tag eng_adverb:supremely{ MODIF_TYPE:ADV } tag eng_adverb:unbearably{ MODIF_TYPE:ADV } tag eng_adverb:unmistakably{ MODIF_TYPE:ADV } tag eng_adverb:unspeakably{ MODIF_TYPE:ADV } tag eng_adverb:awfully{ MODIF_TYPE:ADV } tag eng_adverb:decidedly{ MODIF_TYPE:ADV } tag eng_adverb:demonstrably{ MODIF_TYPE:ADV } tag eng_adverb:fashionably{ MODIF_TYPE:ADV } tag eng_adverb:frighteningly{ MODIF_TYPE:ADV } tag eng_adverb:horrifyingly{ MODIF_TYPE:ADV } tag eng_adverb:indescribably{ MODIF_TYPE:ADV } tag eng_adverb:intolerably{ MODIF_TYPE:ADV } tag eng_adverb:laughably{ MODIF_TYPE:ADV } tag eng_adverb:predominantly { MODIF_TYPE:ADV } tag eng_adverb:unalterably{ MODIF_TYPE:ADV } tag eng_adverb:undisputedly{ MODIF_TYPE:ADV } tag eng_adverb:unpardonably{ MODIF_TYPE:ADV } tag eng_adverb:unreasonably{ MODIF_TYPE:ADV } tag eng_adverb:unusually{ MODIF_TYPE:ADV } tag eng_adverb:hugely{ MODIF_TYPE:ADV } tag eng_adverb:infernally{ MODIF_TYPE:ADV } tag eng_adverb:notoriously{ MODIF_TYPE:ADV } tag eng_adverb:fabulously{ MODIF_TYPE:ADV } tag eng_adverb:incomparably{ MODIF_TYPE:ADV } tag eng_adverb:inherently{ MODIF_TYPE:ADV } tag eng_adverb:marginally{ MODIF_TYPE:ADV } tag eng_adverb:moderately { MODIF_TYPE:ADV } tag eng_adverb:relatively{ MODIF_TYPE:ADV } tag eng_adverb:ridiculously { MODIF_TYPE:ADV } tag eng_adverb:unacceptably{ MODIF_TYPE:ADV } tag eng_adverb:unarguably{ MODIF_TYPE:ADV } tag eng_adverb:undeniably{ MODIF_TYPE:ADV } tag eng_adverb:unimaginably{ MODIF_TYPE:ADV } tag eng_adverb:wide{ MODIF_TYPE:ADV } tag eng_adverb:very{ MODIF_TYPE:ADV } tag eng_adverb:way{ MODIF_TYPE:ADV } tag eng_adverb:real{ MODIF_TYPE:ADV } tag eng_adverb:quite{ MODIF_TYPE:ADV } tag eng_adverb:amazingly{ MODIF_TYPE:ADV } tag eng_adverb:strangely{ MODIF_TYPE:ADV } tag eng_adverb:incredibly{ MODIF_TYPE:ADV } tag eng_adverb:rather{ MODIF_TYPE:ADV } tag eng_adverb:particularly{ MODIF_TYPE:ADV } tag eng_adverb:notably{ MODIF_TYPE:ADV } tag eng_adverb:almost nearly{ MODIF_TYPE:ADV } tag eng_adverb:entirely{ MODIF_TYPE:ADV } tag eng_adverb:reasonably{ MODIF_TYPE:ADV } tag eng_adverb:highly{ MODIF_TYPE:ADV } tag eng_adverb:fairly{ MODIF_TYPE:ADV } tag eng_adverb:totally{ MODIF_TYPE:ADV } tag eng_adverb:completely{ MODIF_TYPE:ADV } tag eng_adverb:terribly{ MODIF_TYPE:ADV } tag eng_adverb:absolutely{ MODIF_TYPE:ADV } tag eng_adverb:altogether{ MODIF_TYPE:ADV } tag eng_adverb:equally{ MODIF_TYPE:ADV } tag eng_adverb:really{ MODIF_TYPE:ADV } tag eng_adverb:surprisingly{ MODIF_TYPE:ADV } tag eng_adverb:especially{ MODIF_TYPE:ADV } tag eng_adverb:virtually{ MODIF_TYPE:ADV } tag eng_adverb:too{ MODIF_TYPE:ADV } #endregion MODIF_TYPE:ADV #region MODIF_TYPE:COMPAR_ADV // --------------------------------------------------- // Модификаторы для наречий в сравнительной степени // --------------------------------------------------- tag eng_adverb:significantly{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:much{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:slightly{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:marginally{ MODIF_TYPE:COMPAR_ADV } // That one is marginally better tag eng_adverb:inherently{ MODIF_TYPE:COMPAR_ADV } // It's an inherently better method tag eng_adverb:fabulously{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:incomparably{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:moderately{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:relatively{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:ridiculously{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:unacceptably{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:unarguably{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:undeniably{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:unimaginably{ MODIF_TYPE:COMPAR_ADV } #endregion MODIF_TYPE:COMPAR_ADV #region MODIF_TYPE:ADJ // Наречия, которые могут модифицировать прилагательные в позиции слева. tag eng_adverb:generally{ MODIF_TYPE:ADJ } // Such hybrids are generally infertile. tag eng_adverb:overall{ MODIF_TYPE:ADJ } // The prognosis is overall poor. tag eng_adverb:whole{ MODIF_TYPE:ADJ } // I ate a fish whole! tag eng_adverb:also{ MODIF_TYPE:ADJ } // Dappled eyes are also possible. tag eng_adverb:increasingly{ MODIF_TYPE:ADJ } // It also became increasingly violent. tag eng_adverb:apparently{ MODIF_TYPE:ADJ } // An apparently arbitrary and reasonless change tag eng_adverb:Melodically{ MODIF_TYPE:ADJ } // Melodically interesting themes tag eng_adverb:Denominationally{ MODIF_TYPE:ADJ } // Denominationally diverse audiences tag eng_adverb:absurdly{ MODIF_TYPE:ADJ } // An absurdly rich young woman tag eng_adverb:Uncannily{ MODIF_TYPE:ADJ } // Uncannily human robots tag eng_adverb:vapidly{ MODIF_TYPE:ADJ } // A vapidly smiling salesman tag eng_adverb:unswervingly{ MODIF_TYPE:ADJ } // An unswervingly loyal man tag eng_adverb:Floridly{ MODIF_TYPE:ADJ } // Floridly figurative prose tag eng_adverb:Boringly{ MODIF_TYPE:ADJ } // Boringly slow work tag eng_adverb:Nocturnally{ MODIF_TYPE:ADJ } // Nocturnally active bird tag eng_adverb:actually{ MODIF_TYPE:ADJ } // The specimens are actually different from each other tag eng_adverb:simply{ MODIF_TYPE:ADJ } // We are simply broke. tag eng_adverb:obviously{ MODIF_TYPE:ADJ } // The answer is obviously wrong. tag eng_adverb:enviably{ MODIF_TYPE:ADJ } // She was enviably fluent in French. tag eng_adverb:crucially{ MODIF_TYPE:ADJ } // crucially important tag eng_adverb:dauntingly{ MODIF_TYPE:ADJ } // dauntingly difficult tag eng_adverb:cerebrally{ MODIF_TYPE:ADJ } // cerebrally active tag eng_adverb:territorially{ MODIF_TYPE:ADJ } // territorially important tag eng_adverb:scholastically{ MODIF_TYPE:ADJ } // scholastically apt tag eng_adverb:repellently{ MODIF_TYPE:ADJ } // repellently fat tag eng_adverb:screamingly{ MODIF_TYPE:ADJ } // screamingly funny tag eng_adverb:deucedly{ MODIF_TYPE:ADJ } // deucedly clever tag eng_adverb:deadly{ MODIF_TYPE:ADJ } // deadly dull tag eng_adverb:hellishly{ MODIF_TYPE:ADJ } // hellishly dangerous tag eng_adverb:chromatically{ MODIF_TYPE:ADJ } // chromatically pure tag eng_adverb:biradially{ MODIF_TYPE:ADJ } // biradially symmetrical tag eng_adverb:typically{ MODIF_TYPE:ADJ } // Tom was typically hostile. tag eng_adverb:relativistically{ MODIF_TYPE:ADJ } // This is relativistically impossible. tag eng_adverb:exultingly{ MODIF_TYPE:ADJ } // It was exultingly easy. tag eng_adverb:rollickingly{ MODIF_TYPE:ADJ } // She was rollickingly happy. tag eng_adverb:bewilderingly{ MODIF_TYPE:ADJ } // Her situation was bewilderingly unclear. tag eng_adverb:gratifyingly{ MODIF_TYPE:ADJ } // The performance was at a gratifyingly high level. tag eng_adverb:healthily{ MODIF_TYPE:ADJ } // The answers were healthily individual. tag eng_adverb:sufficiently{ MODIF_TYPE:ADJ } // She was sufficiently fluent in Mandarin. tag eng_adverb:surely{ MODIF_TYPE:ADJ } // The results are surely encouraging. tag eng_adverb:glaringly{ MODIF_TYPE:ADJ } // It was glaringly obvious. tag eng_adverb:uncharacteristically{ MODIF_TYPE:ADJ } // He was uncharacteristically cool. tag eng_adverb:discouragingly{ MODIF_TYPE:ADJ } // The failure rate on the bar exam is discouragingly high. tag eng_adverb:basically{ MODIF_TYPE:ADJ } // He is basically dishonest. tag eng_adverb:deliciously{ MODIF_TYPE:ADJ } // I bought some more of these deliciously sweet peaches. tag eng_adverb:bewitchingly{ MODIF_TYPE:ADJ } // She was bewitchingly beautiful. tag eng_adverb:captiously{ MODIF_TYPE:ADJ } // He was captiously pedantic. tag eng_adverb:potentially{ MODIF_TYPE:ADJ } // He is potentially dangerous. tag eng_adverb:contagiously{ MODIF_TYPE:ADJ } // She was contagiously bubbly. tag eng_adverb:goddamn{ MODIF_TYPE:ADJ } // You are goddamn right! tag eng_adverb:impracticably{ MODIF_TYPE:ADJ } // This is still impracticably high. tag eng_adverb:ravishingly{ MODIF_TYPE:ADJ } // She was ravishingly beautiful. tag eng_adverb:preternaturally{ MODIF_TYPE:ADJ } // She was preternaturally beautiful. tag eng_adverb:pleasingly{ MODIF_TYPE:ADJ } // The room was pleasingly large. tag eng_adverb:nowise{ MODIF_TYPE:ADJ } // They are nowise different. tag eng_adverb:mistily{ MODIF_TYPE:ADJ } // The summits of the mountains were mistily purple. tag eng_adverb:identifiably{ MODIF_TYPE:ADJ } // They were identifiably different. tag eng_adverb:so{ MODIF_TYPE:ADJ } // Are you so foolish? tag eng_adverb:unattainably{ MODIF_TYPE:ADJ } tag eng_adverb:tropically{ MODIF_TYPE:ADJ } // It was tropically hot in the greenhouse. tag eng_adverb:unwantedly{ MODIF_TYPE:ADJ } // He was unwantedly friendly. tag eng_adverb:demandingly{ MODIF_TYPE:ADJ } // He became demandingly dominant over the years. tag eng_adverb:greasily{ MODIF_TYPE:ADJ } // The food was greasily unappetizing. tag eng_adverb:often{ MODIF_TYPE:ADJ } // He was often friendly tag eng_adverb:vanishingly{ MODIF_TYPE:ADJ } // a vanishingly small dog tag eng_adverb:unbreathably{ MODIF_TYPE:ADJ } // It was unbreathably hot tag eng_adverb:unaccountably{ MODIF_TYPE:ADJ } // The jury was unaccountably slow tag eng_adverb:infinitely{ MODIF_TYPE:ADJ } // God is infinitely and unchangeably good tag eng_adverb:unexplainably{ MODIF_TYPE:ADJ } // His salary is unexplainably high tag eng_adverb:unnervingly{ MODIF_TYPE:ADJ } // Her companion was unnervingly quiet tag eng_adverb:unseasonally{ MODIF_TYPE:ADJ } // They had an unseasonally warm winter tag eng_adverb:a little{ MODIF_TYPE:ADJ } tag eng_adverb:slightly{ MODIF_TYPE:ADJ } tag eng_adverb:somewhat{ MODIF_TYPE:ADJ } tag eng_adverb:pretty{ MODIF_TYPE:ADJ } tag eng_adverb:extremely{ MODIF_TYPE:ADJ } tag eng_adverb:exceptionally{ MODIF_TYPE:ADJ } tag eng_adverb:unbelievably{ MODIF_TYPE:ADJ } tag eng_adverb:incurably{ MODIF_TYPE:ADJ } tag eng_adverb:extraordinarily{ MODIF_TYPE:ADJ } tag eng_adverb:jolly{ MODIF_TYPE:ADJ } tag eng_adverb:mighty{ MODIF_TYPE:ADJ } tag eng_adverb:damn{ MODIF_TYPE:ADJ } tag eng_adverb:exceedingly{ MODIF_TYPE:ADJ } tag eng_adverb:overly{ MODIF_TYPE:ADJ } tag eng_adverb:downright{ MODIF_TYPE:ADJ } tag eng_adverb:plumb{ MODIF_TYPE:ADJ } tag eng_adverb:vitally{ MODIF_TYPE:ADJ } tag eng_adverb:abundantly{ MODIF_TYPE:ADJ } tag eng_adverb:chronically{ MODIF_TYPE:ADJ } tag eng_adverb:frightfully{ MODIF_TYPE:ADJ } tag eng_adverb:genuinely{ MODIF_TYPE:ADJ } tag eng_adverb:humanly{ MODIF_TYPE:ADJ } tag eng_adverb:patently{ MODIF_TYPE:ADJ } tag eng_adverb:singularly{ MODIF_TYPE:ADJ } tag eng_adverb:supremely{ MODIF_TYPE:ADJ } tag eng_adverb:unbearably{ MODIF_TYPE:ADJ } tag eng_adverb:unmistakably{ MODIF_TYPE:ADJ } tag eng_adverb:unspeakably{ MODIF_TYPE:ADJ } tag eng_adverb:awfully{ MODIF_TYPE:ADJ } tag eng_adverb:decidedly{ MODIF_TYPE:ADJ } tag eng_adverb:demonstrably{ MODIF_TYPE:ADJ } tag eng_adverb:fashionably{ MODIF_TYPE:ADJ } tag eng_adverb:frighteningly{ MODIF_TYPE:ADJ } tag eng_adverb:horrifyingly{ MODIF_TYPE:ADJ } tag eng_adverb:indescribably{ MODIF_TYPE:ADJ } tag eng_adverb:intolerably{ MODIF_TYPE:ADJ } tag eng_adverb:laughably{ MODIF_TYPE:ADJ } tag eng_adverb:predominantly { MODIF_TYPE:ADJ } tag eng_adverb:unalterably{ MODIF_TYPE:ADJ } tag eng_adverb:undisputedly{ MODIF_TYPE:ADJ } tag eng_adverb:unpardonably{ MODIF_TYPE:ADJ } tag eng_adverb:unreasonably{ MODIF_TYPE:ADJ } tag eng_adverb:unusually{ MODIF_TYPE:ADJ } tag eng_adverb:usually{ MODIF_TYPE:ADJ } tag eng_adverb:hugely{ MODIF_TYPE:ADJ } tag eng_adverb:infernally{ MODIF_TYPE:ADJ } tag eng_adverb:notoriously{ MODIF_TYPE:ADJ } tag eng_adverb:fabulously{ MODIF_TYPE:ADJ } tag eng_adverb:incomparably{ MODIF_TYPE:ADJ } tag eng_adverb:inherently{ MODIF_TYPE:ADJ } tag eng_adverb:marginally{ MODIF_TYPE:ADJ } tag eng_adverb:moderately { MODIF_TYPE:ADJ } tag eng_adverb:relatively{ MODIF_TYPE:ADJ } tag eng_adverb:ridiculously { MODIF_TYPE:ADJ } tag eng_adverb:unacceptably{ MODIF_TYPE:ADJ } tag eng_adverb:unarguably{ MODIF_TYPE:ADJ } tag eng_adverb:undeniably{ MODIF_TYPE:ADJ } tag eng_adverb:unimaginably{ MODIF_TYPE:ADJ } tag eng_adverb:very{ MODIF_TYPE:ADJ } tag eng_adverb:way{ MODIF_TYPE:ADJ } tag eng_adverb:real{ MODIF_TYPE:ADJ } tag eng_adverb:quite{ MODIF_TYPE:ADJ } tag eng_adverb:amazingly{ MODIF_TYPE:ADJ } tag eng_adverb:strangely{ MODIF_TYPE:ADJ } tag eng_adverb:incredibly{ MODIF_TYPE:ADJ } tag eng_adverb:rather{ MODIF_TYPE:ADJ } tag eng_adverb:particularly{ MODIF_TYPE:ADJ } tag eng_adverb:notably{ MODIF_TYPE:ADJ } tag eng_adverb:almost nearly{ MODIF_TYPE:ADJ } tag eng_adverb:entirely{ MODIF_TYPE:ADJ } tag eng_adverb:reasonably{ MODIF_TYPE:ADJ } tag eng_adverb:highly{ MODIF_TYPE:ADJ } tag eng_adverb:fairly{ MODIF_TYPE:ADJ } tag eng_adverb:totally{ MODIF_TYPE:ADJ } // The car was totally destroyed in the crash tag eng_adverb:completely{ MODIF_TYPE:ADJ } tag eng_adverb:terribly{ MODIF_TYPE:ADJ } tag eng_adverb:absolutely{ MODIF_TYPE:ADJ } tag eng_adverb:altogether{ MODIF_TYPE:ADJ } tag eng_adverb:equally{ MODIF_TYPE:ADJ } tag eng_adverb:really{ MODIF_TYPE:ADJ } tag eng_adverb:surprisingly{ MODIF_TYPE:ADJ } tag eng_adverb:especially{ MODIF_TYPE:ADJ } tag eng_adverb:virtually{ MODIF_TYPE:ADJ } tag eng_adverb:wholly{ MODIF_TYPE:ADJ } // Bismuthides are not even wholly ionic; tag eng_adverb:fully{ MODIF_TYPE:ADJ } tag eng_adverb:critically{ MODIF_TYPE:ADJ } tag eng_adverb:greatly{ MODIF_TYPE:ADJ } tag eng_adverb:grossly{ MODIF_TYPE:ADJ } tag eng_adverb:duly{ MODIF_TYPE:ADJ } tag eng_adverb:unduly{ MODIF_TYPE:ADJ } tag eng_adverb:seemingly{ MODIF_TYPE:ADJ } tag eng_adverb:utterly{ MODIF_TYPE:ADJ } tag eng_adverb:barely{ MODIF_TYPE:ADJ } tag eng_adverb:scarcely{ MODIF_TYPE:ADJ } tag eng_adverb:hardly{ MODIF_TYPE:ADJ } tag eng_adverb:merely{ MODIF_TYPE:ADJ } tag eng_adverb:truly{ MODIF_TYPE:ADJ } tag eng_adverb:practically{ MODIF_TYPE:ADJ } tag eng_adverb:partly{ MODIF_TYPE:ADJ } tag eng_adverb:largely{ MODIF_TYPE:ADJ } tag eng_adverb:mostly{ MODIF_TYPE:ADJ } tag eng_adverb:chiefly{ MODIF_TYPE:ADJ } tag eng_adverb:purely{ MODIF_TYPE:ADJ } tag eng_adverb:solely{ MODIF_TYPE:ADJ } tag eng_adverb:academically{ MODIF_TYPE:ADJ } tag eng_adverb:actuarially{ MODIF_TYPE:ADJ } tag eng_adverb:administratively{ MODIF_TYPE:ADJ } tag eng_adverb:aesthetically{ MODIF_TYPE:ADJ } tag eng_adverb:agriculturally{ MODIF_TYPE:ADJ } tag eng_adverb:algebraically{ MODIF_TYPE:ADJ } tag eng_adverb:allegorically{ MODIF_TYPE:ADJ } tag eng_adverb:anatomically{ MODIF_TYPE:ADJ } tag eng_adverb:archeologically{ MODIF_TYPE:ADJ } tag eng_adverb:architecturally{ MODIF_TYPE:ADJ } tag eng_adverb:arithmetically{ MODIF_TYPE:ADJ } tag eng_adverb:artistically{ MODIF_TYPE:ADJ } tag eng_adverb:assumedly{ MODIF_TYPE:ADJ } tag eng_adverb:astronomically{ MODIF_TYPE:ADJ } tag eng_adverb:athletically{ MODIF_TYPE:ADJ } tag eng_adverb:atypically{ MODIF_TYPE:ADJ } tag eng_adverb:behaviorally{ MODIF_TYPE:ADJ } tag eng_adverb:biblically{ MODIF_TYPE:ADJ } tag eng_adverb:biochemically{ MODIF_TYPE:ADJ } tag eng_adverb:biologically{ MODIF_TYPE:ADJ } tag eng_adverb:biotically{ MODIF_TYPE:ADJ } tag eng_adverb:bipedally{ MODIF_TYPE:ADJ } tag eng_adverb:carnally{ MODIF_TYPE:ADJ } tag eng_adverb:chemically{ MODIF_TYPE:ADJ } tag eng_adverb:clandestinely{ MODIF_TYPE:ADJ } tag eng_adverb:climatically{ MODIF_TYPE:ADJ } tag eng_adverb:cognitively{ MODIF_TYPE:ADJ } tag eng_adverb:collegiately{ MODIF_TYPE:ADJ } tag eng_adverb:colonially{ MODIF_TYPE:ADJ } tag eng_adverb:computationally{ MODIF_TYPE:ADJ } tag eng_adverb:conceptually{ MODIF_TYPE:ADJ } tag eng_adverb:contractually{ MODIF_TYPE:ADJ } tag eng_adverb:cryogenically{ MODIF_TYPE:ADJ } tag eng_adverb:cryptographically{ MODIF_TYPE:ADJ } tag eng_adverb:ecclesiastically{ MODIF_TYPE:ADJ } tag eng_adverb:ecologically{ MODIF_TYPE:ADJ } tag eng_adverb:economically{ MODIF_TYPE:ADJ } tag eng_adverb:educationally{ MODIF_TYPE:ADJ } tag eng_adverb:electorally{ MODIF_TYPE:ADJ } tag eng_adverb:empirically{ MODIF_TYPE:ADJ } tag eng_adverb:environmentally{ MODIF_TYPE:ADJ } tag eng_adverb:equidistantly{ MODIF_TYPE:ADJ } tag eng_adverb:ethically{ MODIF_TYPE:ADJ } tag eng_adverb:ethnically{ MODIF_TYPE:ADJ } tag eng_adverb:factually{ MODIF_TYPE:ADJ } tag eng_adverb:federally{ MODIF_TYPE:ADJ } tag eng_adverb:financially{ MODIF_TYPE:ADJ } tag eng_adverb:finitely{ MODIF_TYPE:ADJ } tag eng_adverb:genealogically{ MODIF_TYPE:ADJ } tag eng_adverb:generically{ MODIF_TYPE:ADJ } tag eng_adverb:genetically{ MODIF_TYPE:ADJ } tag eng_adverb:geographically{ MODIF_TYPE:ADJ } tag eng_adverb:geologically{ MODIF_TYPE:ADJ } tag eng_adverb:geometrically{ MODIF_TYPE:ADJ } tag eng_adverb:governmentally{ MODIF_TYPE:ADJ } tag eng_adverb:grammatically{ MODIF_TYPE:ADJ } tag eng_adverb:gynaecologically{ MODIF_TYPE:ADJ } tag eng_adverb:harmonically{ MODIF_TYPE:ADJ } tag eng_adverb:heretofore{ MODIF_TYPE:ADJ } tag eng_adverb:histochemically{ MODIF_TYPE:ADJ } tag eng_adverb:historically{ MODIF_TYPE:ADJ } tag eng_adverb:hydraulically{ MODIF_TYPE:ADJ } tag eng_adverb:immunophenotypically{ MODIF_TYPE:ADJ } tag eng_adverb:infinitesimally{ MODIF_TYPE:ADJ } tag eng_adverb:institutionally{ MODIF_TYPE:ADJ } tag eng_adverb:journalistically{ MODIF_TYPE:ADJ } tag eng_adverb:judicially{ MODIF_TYPE:ADJ } tag eng_adverb:lastingly{ MODIF_TYPE:ADJ } tag eng_adverb:legendarily{ MODIF_TYPE:ADJ } tag eng_adverb:linguistically{ MODIF_TYPE:ADJ } tag eng_adverb:logically{ MODIF_TYPE:ADJ } tag eng_adverb:logistically{ MODIF_TYPE:ADJ } tag eng_adverb:maddeningly{ MODIF_TYPE:ADJ } tag eng_adverb:materially{ MODIF_TYPE:ADJ } tag eng_adverb:mathematically{ MODIF_TYPE:ADJ } tag eng_adverb:medically{ MODIF_TYPE:ADJ } tag eng_adverb:medicinally{ MODIF_TYPE:ADJ } tag eng_adverb:metaphysically{ MODIF_TYPE:ADJ } tag eng_adverb:meteorologically{ MODIF_TYPE:ADJ } tag eng_adverb:methodologically{ MODIF_TYPE:ADJ } tag eng_adverb:morally{ MODIF_TYPE:ADJ } tag eng_adverb:morbidly{ MODIF_TYPE:ADJ } tag eng_adverb:mystically{ MODIF_TYPE:ADJ } tag eng_adverb:nonspecifically{ MODIF_TYPE:ADJ } tag eng_adverb:nutritionally{ MODIF_TYPE:ADJ } tag eng_adverb:opportunistically{ MODIF_TYPE:ADJ } tag eng_adverb:optically{ MODIF_TYPE:ADJ } tag eng_adverb:organizationally{ MODIF_TYPE:ADJ } tag eng_adverb:perceptually{ MODIF_TYPE:ADJ } tag eng_adverb:perpendicularly{ MODIF_TYPE:ADJ } tag eng_adverb:pharmacologically{ MODIF_TYPE:ADJ } tag eng_adverb:phenomenologically{ MODIF_TYPE:ADJ } tag eng_adverb:philosophically{ MODIF_TYPE:ADJ } tag eng_adverb:phonetically{ MODIF_TYPE:ADJ } tag eng_adverb:phonologically{ MODIF_TYPE:ADJ } tag eng_adverb:photographically{ MODIF_TYPE:ADJ } tag eng_adverb:pictorially{ MODIF_TYPE:ADJ } tag eng_adverb:pinnately{ MODIF_TYPE:ADJ } tag eng_adverb:politically{ MODIF_TYPE:ADJ } tag eng_adverb:pragmatically{ MODIF_TYPE:ADJ } tag eng_adverb:princely{ MODIF_TYPE:ADJ } tag eng_adverb:probabilistically{ MODIF_TYPE:ADJ } tag eng_adverb:prognostically{ MODIF_TYPE:ADJ } tag eng_adverb:pseudonymously{ MODIF_TYPE:ADJ } tag eng_adverb:psychically{ MODIF_TYPE:ADJ } tag eng_adverb:psychologically{ MODIF_TYPE:ADJ } tag eng_adverb:publically{ MODIF_TYPE:ADJ } tag eng_adverb:putatively{ MODIF_TYPE:ADJ } tag eng_adverb:quadratically{ MODIF_TYPE:ADJ } tag eng_adverb:questionably{ MODIF_TYPE:ADJ } tag eng_adverb:racially{ MODIF_TYPE:ADJ } tag eng_adverb:recreationally{ MODIF_TYPE:ADJ } tag eng_adverb:recursively{ MODIF_TYPE:ADJ } tag eng_adverb:ritually{ MODIF_TYPE:ADJ } tag eng_adverb:scientifically{ MODIF_TYPE:ADJ } tag eng_adverb:semantically{ MODIF_TYPE:ADJ } tag eng_adverb:sexually{ MODIF_TYPE:ADJ } tag eng_adverb:socially{ MODIF_TYPE:ADJ } tag eng_adverb:societally{ MODIF_TYPE:ADJ } tag eng_adverb:sociologically{ MODIF_TYPE:ADJ } tag eng_adverb:sonically{ MODIF_TYPE:ADJ } tag eng_adverb:spatially{ MODIF_TYPE:ADJ } tag eng_adverb:spherically{ MODIF_TYPE:ADJ } tag eng_adverb:spirally{ MODIF_TYPE:ADJ } tag eng_adverb:statistically{ MODIF_TYPE:ADJ } tag eng_adverb:statutorily{ MODIF_TYPE:ADJ } tag eng_adverb:steganographically{ MODIF_TYPE:ADJ } tag eng_adverb:stereotypically{ MODIF_TYPE:ADJ } tag eng_adverb:structurally{ MODIF_TYPE:ADJ } tag eng_adverb:stylistically{ MODIF_TYPE:ADJ } tag eng_adverb:supernaturally{ MODIF_TYPE:ADJ } tag eng_adverb:syllabically{ MODIF_TYPE:ADJ } tag eng_adverb:synonymously{ MODIF_TYPE:ADJ } tag eng_adverb:synoptically{ MODIF_TYPE:ADJ } tag eng_adverb:syntactically{ MODIF_TYPE:ADJ } tag eng_adverb:tangentially{ MODIF_TYPE:ADJ } tag eng_adverb:taxonomically{ MODIF_TYPE:ADJ } tag eng_adverb:technologically{ MODIF_TYPE:ADJ } tag eng_adverb:telepathically{ MODIF_TYPE:ADJ } tag eng_adverb:terrestrially{ MODIF_TYPE:ADJ } tag eng_adverb:theologically{ MODIF_TYPE:ADJ } tag eng_adverb:theoretically{ MODIF_TYPE:ADJ } tag eng_adverb:therapeutically{ MODIF_TYPE:ADJ } tag eng_adverb:topographically{ MODIF_TYPE:ADJ } tag eng_adverb:wirelessly{ MODIF_TYPE:ADJ } tag eng_adverb:finely{ MODIF_TYPE:ADJ } tag eng_adverb:specially{ MODIF_TYPE:ADJ } tag eng_adverb:literally{ MODIF_TYPE:ADJ } tag eng_adverb:heavily{ MODIF_TYPE:ADJ } tag eng_adverb:alternately{ MODIF_TYPE:ADJ } tag eng_adverb:severely{ MODIF_TYPE:ADJ } tag eng_adverb:dearly{ MODIF_TYPE:ADJ } tag eng_adverb:voluntarily{ MODIF_TYPE:ADJ } tag eng_adverb:dramatically{ MODIF_TYPE:ADJ } tag eng_adverb:flatly{ MODIF_TYPE:ADJ } tag eng_adverb:purposely{ MODIF_TYPE:ADJ } tag eng_adverb:jointly{ MODIF_TYPE:ADJ } tag eng_adverb:narrowly{ MODIF_TYPE:ADJ } tag eng_adverb:universally{ MODIF_TYPE:ADJ } tag eng_adverb:thickly{ MODIF_TYPE:ADJ } tag eng_adverb:widely{ MODIF_TYPE:ADJ } tag eng_adverb:roughly{ MODIF_TYPE:ADJ } tag eng_adverb:approximately{ MODIF_TYPE:ADJ } tag eng_adverb:gradually{ MODIF_TYPE:ADJ } tag eng_adverb:sadly{ MODIF_TYPE:ADJ } tag eng_adverb:broadly{ MODIF_TYPE:ADJ } tag eng_adverb:clearly{ MODIF_TYPE:ADJ } tag eng_adverb:annually{ MODIF_TYPE:ADJ } tag eng_adverb:characteristically{ MODIF_TYPE:ADJ } tag eng_adverb:comparatively{ MODIF_TYPE:ADJ } tag eng_adverb:confidentially{ MODIF_TYPE:ADJ } tag eng_adverb:currently{ MODIF_TYPE:ADJ } tag eng_adverb:fundamentally{ MODIF_TYPE:ADJ } tag eng_adverb:hypothetically{ MODIF_TYPE:ADJ } tag eng_adverb:ironically{ MODIF_TYPE:ADJ } tag eng_adverb:justifiably{ MODIF_TYPE:ADJ } tag eng_adverb:momentarily{ MODIF_TYPE:ADJ } tag eng_adverb:mercifully{ MODIF_TYPE:ADJ } tag eng_adverb:nominally{ MODIF_TYPE:ADJ } tag eng_adverb:ominously{ MODIF_TYPE:ADJ } tag eng_adverb:periodically{ MODIF_TYPE:ADJ } tag eng_adverb:precisely{ MODIF_TYPE:ADJ } tag eng_adverb:realistically{ MODIF_TYPE:ADJ } tag eng_adverb:simultaneously{ MODIF_TYPE:ADJ } tag eng_adverb:subsequently{ MODIF_TYPE:ADJ } tag eng_adverb:superficially{ MODIF_TYPE:ADJ } tag eng_adverb:thankfully{ MODIF_TYPE:ADJ } tag eng_adverb:unofficially{ MODIF_TYPE:ADJ } tag eng_adverb:effectively{ MODIF_TYPE:ADJ } tag eng_adverb:traditionally{ MODIF_TYPE:ADJ } tag eng_adverb:briefly{ MODIF_TYPE:ADJ } tag eng_adverb:eventually{ MODIF_TYPE:ADJ } tag eng_adverb:ultimately{ MODIF_TYPE:ADJ } tag eng_adverb:mysteriously{ MODIF_TYPE:ADJ } tag eng_adverb:naturally{ MODIF_TYPE:ADJ } tag eng_adverb:oddly{ MODIF_TYPE:ADJ } tag eng_adverb:plainly{ MODIF_TYPE:ADJ } tag eng_adverb:truthfully{ MODIF_TYPE:ADJ } tag eng_adverb:appropriately{ MODIF_TYPE:ADJ } tag eng_adverb:abjectly{ MODIF_TYPE:ADJ } tag eng_adverb:ably{ MODIF_TYPE:ADJ } tag eng_adverb:abnormally{ MODIF_TYPE:ADJ } tag eng_adverb:abortively{ MODIF_TYPE:ADJ } tag eng_adverb:abruptly{ MODIF_TYPE:ADJ } tag eng_adverb:absently{ MODIF_TYPE:ADJ } tag eng_adverb:absent-mindedly{ MODIF_TYPE:ADJ } tag eng_adverb:abusively{ MODIF_TYPE:ADJ } tag eng_adverb:abysmally{ MODIF_TYPE:ADJ } tag eng_adverb:accidentally{ MODIF_TYPE:ADJ } tag eng_adverb:accordingly{ MODIF_TYPE:ADJ } tag eng_adverb:accurately{ MODIF_TYPE:ADJ } tag eng_adverb:accusingly{ MODIF_TYPE:ADJ } tag eng_adverb:actively{ MODIF_TYPE:ADJ } tag eng_adverb:acutely{ MODIF_TYPE:ADJ } tag eng_adverb:adamantly{ MODIF_TYPE:ADJ } tag eng_adverb:adequately{ MODIF_TYPE:ADJ } tag eng_adverb:admirably{ MODIF_TYPE:ADJ } tag eng_adverb:admiringly{ MODIF_TYPE:ADJ } tag eng_adverb:adoringly{ MODIF_TYPE:ADJ } tag eng_adverb:adroitly{ MODIF_TYPE:ADJ } tag eng_adverb:adversely{ MODIF_TYPE:ADJ } tag eng_adverb:advisedly{ MODIF_TYPE:ADJ } tag eng_adverb:affably{ MODIF_TYPE:ADJ } tag eng_adverb:affectionately{ MODIF_TYPE:ADJ } tag eng_adverb:afield{ MODIF_TYPE:ADJ } tag eng_adverb:aggressively{ MODIF_TYPE:ADJ } tag eng_adverb:agreeably{ MODIF_TYPE:ADJ } tag eng_adverb:aimlessly{ MODIF_TYPE:ADJ } tag eng_adverb:airily{ MODIF_TYPE:ADJ } tag eng_adverb:alarmingly{ MODIF_TYPE:ADJ } tag eng_adverb:allegretto{ MODIF_TYPE:ADJ } tag eng_adverb:alphabetically{ MODIF_TYPE:ADJ } tag eng_adverb:ambiguously{ MODIF_TYPE:ADJ } tag eng_adverb:ambitiously{ MODIF_TYPE:ADJ } tag eng_adverb:amiably{ MODIF_TYPE:ADJ } tag eng_adverb:amicably{ MODIF_TYPE:ADJ } tag eng_adverb:amidships{ MODIF_TYPE:ADJ } tag eng_adverb:amorously{ MODIF_TYPE:ADJ } tag eng_adverb:amply{ MODIF_TYPE:ADJ } tag eng_adverb:amusingly{ MODIF_TYPE:ADJ } tag eng_adverb:analogously{ MODIF_TYPE:ADJ } tag eng_adverb:analytically{ MODIF_TYPE:ADJ } tag eng_adverb:anciently{ MODIF_TYPE:ADJ } tag eng_adverb:andante{ MODIF_TYPE:ADJ } tag eng_adverb:angelically{ MODIF_TYPE:ADJ } tag eng_adverb:angrily{ MODIF_TYPE:ADJ } tag eng_adverb:anon{ MODIF_TYPE:ADJ } tag eng_adverb:anonymously{ MODIF_TYPE:ADJ } tag eng_adverb:anticlockwise{ MODIF_TYPE:ADJ } tag eng_adverb:anxiously{ MODIF_TYPE:ADJ } tag eng_adverb:anyplace{ MODIF_TYPE:ADJ } tag eng_adverb:apace{ MODIF_TYPE:ADJ } tag eng_adverb:apathetically{ MODIF_TYPE:ADJ } tag eng_adverb:apologetically{ MODIF_TYPE:ADJ } tag eng_adverb:appreciably{ MODIF_TYPE:ADJ } tag eng_adverb:appreciatively{ MODIF_TYPE:ADJ } tag eng_adverb:approvingly{ MODIF_TYPE:ADJ } tag eng_adverb:aptly{ MODIF_TYPE:ADJ } tag eng_adverb:arbitrarily{ MODIF_TYPE:ADJ } tag eng_adverb:archly{ MODIF_TYPE:ADJ } tag eng_adverb:ardently{ MODIF_TYPE:ADJ } tag eng_adverb:arduously{ MODIF_TYPE:ADJ } tag eng_adverb:arrogantly{ MODIF_TYPE:ADJ } tag eng_adverb:artfully{ MODIF_TYPE:ADJ } tag eng_adverb:articulately{ MODIF_TYPE:ADJ } tag eng_adverb:artificially{ MODIF_TYPE:ADJ } tag eng_adverb:asexually{ MODIF_TYPE:ADJ } tag eng_adverb:assertively{ MODIF_TYPE:ADJ } tag eng_adverb:assiduously{ MODIF_TYPE:ADJ } tag eng_adverb:astutely{ MODIF_TYPE:ADJ } tag eng_adverb:asymmetrically{ MODIF_TYPE:ADJ } tag eng_adverb:asymptotically{ MODIF_TYPE:ADJ } tag eng_adverb:atrociously{ MODIF_TYPE:ADJ } tag eng_adverb:attentively{ MODIF_TYPE:ADJ } tag eng_adverb:attractively{ MODIF_TYPE:ADJ } tag eng_adverb:attributively{ MODIF_TYPE:ADJ } tag eng_adverb:audaciously{ MODIF_TYPE:ADJ } tag eng_adverb:audibly{ MODIF_TYPE:ADJ } tag eng_adverb:auspiciously{ MODIF_TYPE:ADJ } tag eng_adverb:austerely{ MODIF_TYPE:ADJ } tag eng_adverb:authentically{ MODIF_TYPE:ADJ } tag eng_adverb:authoritatively{ MODIF_TYPE:ADJ } tag eng_adverb:autocratically{ MODIF_TYPE:ADJ } tag eng_adverb:automatically{ MODIF_TYPE:ADJ } tag eng_adverb:avariciously{ MODIF_TYPE:ADJ } tag eng_adverb:avidly{ MODIF_TYPE:ADJ } tag eng_adverb:awake{ MODIF_TYPE:ADJ } tag eng_adverb:awesomely{ MODIF_TYPE:ADJ } tag eng_adverb:awkwardly{ MODIF_TYPE:ADJ } tag eng_adverb:backstage{ MODIF_TYPE:ADJ } tag eng_adverb:badly{ MODIF_TYPE:ADJ } tag eng_adverb:baldly{ MODIF_TYPE:ADJ } tag eng_adverb:barbarously{ MODIF_TYPE:ADJ } tag eng_adverb:bareback{ MODIF_TYPE:ADJ } tag eng_adverb:barebacked{ MODIF_TYPE:ADJ } tag eng_adverb:barefacedly{ MODIF_TYPE:ADJ } tag eng_adverb:barefooted{ MODIF_TYPE:ADJ } tag eng_adverb:bashfully{ MODIF_TYPE:ADJ } tag eng_adverb:beautifully{ MODIF_TYPE:ADJ } tag eng_adverb:becomingly{ MODIF_TYPE:ADJ } tag eng_adverb:beforehand{ MODIF_TYPE:ADJ } tag eng_adverb:begrudgingly{ MODIF_TYPE:ADJ } tag eng_adverb:belatedly{ MODIF_TYPE:ADJ } tag eng_adverb:belligerently{ MODIF_TYPE:ADJ } tag eng_adverb:beneficially{ MODIF_TYPE:ADJ } tag eng_adverb:benevolently{ MODIF_TYPE:ADJ } tag eng_adverb:benignly{ MODIF_TYPE:ADJ } tag eng_adverb:biennially{ MODIF_TYPE:ADJ } tag eng_adverb:bilaterally{ MODIF_TYPE:ADJ } tag eng_adverb:bitterly{ MODIF_TYPE:ADJ } tag eng_adverb:blandly{ MODIF_TYPE:ADJ } tag eng_adverb:blankly{ MODIF_TYPE:ADJ } tag eng_adverb:blasphemously{ MODIF_TYPE:ADJ } tag eng_adverb:blatantly{ MODIF_TYPE:ADJ } tag eng_adverb:bleakly{ MODIF_TYPE:ADJ } tag eng_adverb:blindly{ MODIF_TYPE:ADJ } tag eng_adverb:blissfully{ MODIF_TYPE:ADJ } tag eng_adverb:blithely{ MODIF_TYPE:ADJ } tag eng_adverb:bloodily{ MODIF_TYPE:ADJ } tag eng_adverb:bluntly{ MODIF_TYPE:ADJ } tag eng_adverb:boastfully{ MODIF_TYPE:ADJ } tag eng_adverb:boisterously{ MODIF_TYPE:ADJ } tag eng_adverb:boldly{ MODIF_TYPE:ADJ } tag eng_adverb:bombastically{ MODIF_TYPE:ADJ } tag eng_adverb:boundlessly{ MODIF_TYPE:ADJ } tag eng_adverb:boyishly{ MODIF_TYPE:ADJ } tag eng_adverb:bravely{ MODIF_TYPE:ADJ } tag eng_adverb:brazenly{ MODIF_TYPE:ADJ } tag eng_adverb:breathlessly{ MODIF_TYPE:ADJ } tag eng_adverb:breezily{ MODIF_TYPE:ADJ } tag eng_adverb:bright{ MODIF_TYPE:ADJ } tag eng_adverb:brightly{ MODIF_TYPE:ADJ } tag eng_adverb:brilliantly{ MODIF_TYPE:ADJ } tag eng_adverb:briskly{ MODIF_TYPE:ADJ } tag eng_adverb:brusquely{ MODIF_TYPE:ADJ } tag eng_adverb:brutally{ MODIF_TYPE:ADJ } tag eng_adverb:buoyantly{ MODIF_TYPE:ADJ } tag eng_adverb:busily{ MODIF_TYPE:ADJ } tag eng_adverb:callously{ MODIF_TYPE:ADJ } tag eng_adverb:calmly{ MODIF_TYPE:ADJ } tag eng_adverb:candidly{ MODIF_TYPE:ADJ } tag eng_adverb:cantankerously{ MODIF_TYPE:ADJ } tag eng_adverb:capably{ MODIF_TYPE:ADJ } tag eng_adverb:capriciously{ MODIF_TYPE:ADJ } tag eng_adverb:carefully{ MODIF_TYPE:ADJ } tag eng_adverb:carelessly{ MODIF_TYPE:ADJ } tag eng_adverb:casually{ MODIF_TYPE:ADJ } tag eng_adverb:categorically{ MODIF_TYPE:ADJ } tag eng_adverb:causally{ MODIF_TYPE:ADJ } tag eng_adverb:caustically{ MODIF_TYPE:ADJ } tag eng_adverb:cautiously{ MODIF_TYPE:ADJ } tag eng_adverb:cavalierly{ MODIF_TYPE:ADJ } tag eng_adverb:ceaselessly{ MODIF_TYPE:ADJ } tag eng_adverb:centrally{ MODIF_TYPE:ADJ } tag eng_adverb:ceremonially{ MODIF_TYPE:ADJ } tag eng_adverb:ceremoniously{ MODIF_TYPE:ADJ } tag eng_adverb:chaotically{ MODIF_TYPE:ADJ } tag eng_adverb:charitably{ MODIF_TYPE:ADJ } tag eng_adverb:charmingly{ MODIF_TYPE:ADJ } tag eng_adverb:chattily{ MODIF_TYPE:ADJ } tag eng_adverb:cheaply{ MODIF_TYPE:ADJ } tag eng_adverb:cheekily{ MODIF_TYPE:ADJ } tag eng_adverb:cheerfully{ MODIF_TYPE:ADJ } tag eng_adverb:cheerily{ MODIF_TYPE:ADJ } tag eng_adverb:childishly{ MODIF_TYPE:ADJ } tag eng_adverb:chivalrously{ MODIF_TYPE:ADJ } tag eng_adverb:chronologically{ MODIF_TYPE:ADJ } tag eng_adverb:classically{ MODIF_TYPE:ADJ } tag eng_adverb:clean{ MODIF_TYPE:ADJ } tag eng_adverb:cleanly{ MODIF_TYPE:ADJ } tag eng_adverb:cleverly{ MODIF_TYPE:ADJ } tag eng_adverb:clinically{ MODIF_TYPE:ADJ } tag eng_adverb:clockwise{ MODIF_TYPE:ADJ } tag eng_adverb:closely{ MODIF_TYPE:ADJ } tag eng_adverb:clumsily{ MODIF_TYPE:ADJ } tag eng_adverb:coarsely{ MODIF_TYPE:ADJ } tag eng_adverb:coherently{ MODIF_TYPE:ADJ } tag eng_adverb:cohesively{ MODIF_TYPE:ADJ } tag eng_adverb:coldly{ MODIF_TYPE:ADJ } tag eng_adverb:collectively{ MODIF_TYPE:ADJ } tag eng_adverb:colloquially{ MODIF_TYPE:ADJ } tag eng_adverb:colorfully{ MODIF_TYPE:ADJ } tag eng_adverb:combatively{ MODIF_TYPE:ADJ } tag eng_adverb:comfortably{ MODIF_TYPE:ADJ } tag eng_adverb:comfortingly{ MODIF_TYPE:ADJ } tag eng_adverb:comically{ MODIF_TYPE:ADJ } tag eng_adverb:commercially{ MODIF_TYPE:ADJ } tag eng_adverb:communally{ MODIF_TYPE:ADJ } tag eng_adverb:comparably{ MODIF_TYPE:ADJ } tag eng_adverb:compassionately{ MODIF_TYPE:ADJ } tag eng_adverb:competently{ MODIF_TYPE:ADJ } tag eng_adverb:competitively{ MODIF_TYPE:ADJ } tag eng_adverb:complacently{ MODIF_TYPE:ADJ } tag eng_adverb:comprehensively{ MODIF_TYPE:ADJ } tag eng_adverb:compulsively{ MODIF_TYPE:ADJ } tag eng_adverb:conceitedly{ MODIF_TYPE:ADJ } tag eng_adverb:concernedly{ MODIF_TYPE:ADJ } tag eng_adverb:concisely{ MODIF_TYPE:ADJ } tag eng_adverb:conclusively{ MODIF_TYPE:ADJ } tag eng_adverb:concretely{ MODIF_TYPE:ADJ } tag eng_adverb:concurrently{ MODIF_TYPE:ADJ } tag eng_adverb:condescendingly{ MODIF_TYPE:ADJ } tag eng_adverb:conditionally{ MODIF_TYPE:ADJ } tag eng_adverb:confidently{ MODIF_TYPE:ADJ } tag eng_adverb:confidingly{ MODIF_TYPE:ADJ } tag eng_adverb:confusingly{ MODIF_TYPE:ADJ } tag eng_adverb:congenially{ MODIF_TYPE:ADJ } tag eng_adverb:conjugally{ MODIF_TYPE:ADJ } tag eng_adverb:conscientiously{ MODIF_TYPE:ADJ } tag eng_adverb:consciously{ MODIF_TYPE:ADJ } tag eng_adverb:consecutively{ MODIF_TYPE:ADJ } tag eng_adverb:conservatively{ MODIF_TYPE:ADJ } tag eng_adverb:considerably{ MODIF_TYPE:ADJ } tag eng_adverb:considerately{ MODIF_TYPE:ADJ } tag eng_adverb:consistently{ MODIF_TYPE:ADJ } tag eng_adverb:conspicuously{ MODIF_TYPE:ADJ } tag eng_adverb:constantly{ MODIF_TYPE:ADJ } tag eng_adverb:constitutionally{ MODIF_TYPE:ADJ } tag eng_adverb:constructively{ MODIF_TYPE:ADJ } tag eng_adverb:contemporaneously{ MODIF_TYPE:ADJ } tag eng_adverb:contemporarily{ MODIF_TYPE:ADJ } tag eng_adverb:contemptuously{ MODIF_TYPE:ADJ } tag eng_adverb:contentedly{ MODIF_TYPE:ADJ } tag eng_adverb:continually{ MODIF_TYPE:ADJ } tag eng_adverb:continuously{ MODIF_TYPE:ADJ } tag eng_adverb:contrariwise{ MODIF_TYPE:ADJ } tag eng_adverb:contritely{ MODIF_TYPE:ADJ } tag eng_adverb:controversially{ MODIF_TYPE:ADJ } tag eng_adverb:conventionally{ MODIF_TYPE:ADJ } tag eng_adverb:conversationally{ MODIF_TYPE:ADJ } tag eng_adverb:convincingly{ MODIF_TYPE:ADJ } tag eng_adverb:convulsively{ MODIF_TYPE:ADJ } tag eng_adverb:coolly{ MODIF_TYPE:ADJ } tag eng_adverb:cooperatively{ MODIF_TYPE:ADJ } tag eng_adverb:co-operatively{ MODIF_TYPE:ADJ } tag eng_adverb:copiously{ MODIF_TYPE:ADJ } tag eng_adverb:cordially{ MODIF_TYPE:ADJ } tag eng_adverb:correctly{ MODIF_TYPE:ADJ } tag eng_adverb:correspondingly{ MODIF_TYPE:ADJ } tag eng_adverb:corruptly{ MODIF_TYPE:ADJ } tag eng_adverb:courageously{ MODIF_TYPE:ADJ } tag eng_adverb:courteously{ MODIF_TYPE:ADJ } tag eng_adverb:covertly{ MODIF_TYPE:ADJ } tag eng_adverb:coyly{ MODIF_TYPE:ADJ } tag eng_adverb:craftily{ MODIF_TYPE:ADJ } tag eng_adverb:crassly{ MODIF_TYPE:ADJ } tag eng_adverb:crazily{ MODIF_TYPE:ADJ } tag eng_adverb:creatively{ MODIF_TYPE:ADJ } tag eng_adverb:credibly{ MODIF_TYPE:ADJ } tag eng_adverb:creditably{ MODIF_TYPE:ADJ } tag eng_adverb:credulously{ MODIF_TYPE:ADJ } tag eng_adverb:criminally{ MODIF_TYPE:ADJ } tag eng_adverb:crisply{ MODIF_TYPE:ADJ } tag eng_adverb:crookedly{ MODIF_TYPE:ADJ } tag eng_adverb:cross-legged{ MODIF_TYPE:ADJ } tag eng_adverb:crossly{ MODIF_TYPE:ADJ } tag eng_adverb:crudely{ MODIF_TYPE:ADJ } tag eng_adverb:cruelly{ MODIF_TYPE:ADJ } tag eng_adverb:cryptically{ MODIF_TYPE:ADJ } tag eng_adverb:culturally{ MODIF_TYPE:ADJ } tag eng_adverb:cumulatively{ MODIF_TYPE:ADJ } tag eng_adverb:cunningly{ MODIF_TYPE:ADJ } tag eng_adverb:cursorily{ MODIF_TYPE:ADJ } tag eng_adverb:curtly{ MODIF_TYPE:ADJ } tag eng_adverb:cynically{ MODIF_TYPE:ADJ } tag eng_adverb:daintily{ MODIF_TYPE:ADJ } tag eng_adverb:damnably{ MODIF_TYPE:ADJ } tag eng_adverb:dangerously{ MODIF_TYPE:ADJ } tag eng_adverb:daringly{ MODIF_TYPE:ADJ } tag eng_adverb:darkly{ MODIF_TYPE:ADJ } tag eng_adverb:dashingly{ MODIF_TYPE:ADJ } tag eng_adverb:deceitfully{ MODIF_TYPE:ADJ } tag eng_adverb:deceivingly{ MODIF_TYPE:ADJ } tag eng_adverb:decently{ MODIF_TYPE:ADJ } tag eng_adverb:deceptively{ MODIF_TYPE:ADJ } tag eng_adverb:decisively{ MODIF_TYPE:ADJ } tag eng_adverb:decorously{ MODIF_TYPE:ADJ } tag eng_adverb:deductively{ MODIF_TYPE:ADJ } tag eng_adverb:deeply{ MODIF_TYPE:ADJ } tag eng_adverb:defectively{ MODIF_TYPE:ADJ } tag eng_adverb:defensively{ MODIF_TYPE:ADJ } tag eng_adverb:deferentially{ MODIF_TYPE:ADJ } tag eng_adverb:defiantly{ MODIF_TYPE:ADJ } tag eng_adverb:deftly{ MODIF_TYPE:ADJ } tag eng_adverb:dejectedly{ MODIF_TYPE:ADJ } tag eng_adverb:deliberately{ MODIF_TYPE:ADJ } tag eng_adverb:delicately{ MODIF_TYPE:ADJ } tag eng_adverb:delightedly{ MODIF_TYPE:ADJ } tag eng_adverb:delightfully{ MODIF_TYPE:ADJ } tag eng_adverb:deliriously{ MODIF_TYPE:ADJ } tag eng_adverb:democratically{ MODIF_TYPE:ADJ } tag eng_adverb:demoniacally{ MODIF_TYPE:ADJ } tag eng_adverb:demonstratively{ MODIF_TYPE:ADJ } tag eng_adverb:demurely{ MODIF_TYPE:ADJ } tag eng_adverb:densely{ MODIF_TYPE:ADJ } tag eng_adverb:dentally{ MODIF_TYPE:ADJ } tag eng_adverb:dependably{ MODIF_TYPE:ADJ } tag eng_adverb:deplorably{ MODIF_TYPE:ADJ } tag eng_adverb:derisively{ MODIF_TYPE:ADJ } tag eng_adverb:descriptively{ MODIF_TYPE:ADJ } tag eng_adverb:deservedly{ MODIF_TYPE:ADJ } tag eng_adverb:despairingly{ MODIF_TYPE:ADJ } tag eng_adverb:desperately{ MODIF_TYPE:ADJ } tag eng_adverb:despicably{ MODIF_TYPE:ADJ } tag eng_adverb:despondently{ MODIF_TYPE:ADJ } tag eng_adverb:destructively{ MODIF_TYPE:ADJ } tag eng_adverb:detestably{ MODIF_TYPE:ADJ } tag eng_adverb:detrimentally{ MODIF_TYPE:ADJ } tag eng_adverb:devilishly{ MODIF_TYPE:ADJ } tag eng_adverb:deviously{ MODIF_TYPE:ADJ } tag eng_adverb:devotedly{ MODIF_TYPE:ADJ } tag eng_adverb:devoutly{ MODIF_TYPE:ADJ } tag eng_adverb:dexterously{ MODIF_TYPE:ADJ } tag eng_adverb:diabolically{ MODIF_TYPE:ADJ } tag eng_adverb:diagonally{ MODIF_TYPE:ADJ } tag eng_adverb:diametrically{ MODIF_TYPE:ADJ } tag eng_adverb:didactically{ MODIF_TYPE:ADJ } tag eng_adverb:differentially{ MODIF_TYPE:ADJ } tag eng_adverb:diffidently{ MODIF_TYPE:ADJ } tag eng_adverb:diffusely{ MODIF_TYPE:ADJ } tag eng_adverb:digitally{ MODIF_TYPE:ADJ } tag eng_adverb:diligently{ MODIF_TYPE:ADJ } tag eng_adverb:dimly{ MODIF_TYPE:ADJ } tag eng_adverb:diplomatically{ MODIF_TYPE:ADJ } tag eng_adverb:directly{ MODIF_TYPE:ADJ } tag eng_adverb:disagreeably{ MODIF_TYPE:ADJ } tag eng_adverb:disappointedly{ MODIF_TYPE:ADJ } tag eng_adverb:disapprovingly{ MODIF_TYPE:ADJ } tag eng_adverb:disastrously{ MODIF_TYPE:ADJ } tag eng_adverb:disconcertingly{ MODIF_TYPE:ADJ } tag eng_adverb:discourteously{ MODIF_TYPE:ADJ } tag eng_adverb:discreetly{ MODIF_TYPE:ADJ } tag eng_adverb:discretely{ MODIF_TYPE:ADJ } tag eng_adverb:discursively{ MODIF_TYPE:ADJ } tag eng_adverb:disdainfully{ MODIF_TYPE:ADJ } tag eng_adverb:disgracefully{ MODIF_TYPE:ADJ } tag eng_adverb:disgustedly{ MODIF_TYPE:ADJ } tag eng_adverb:disgustingly{ MODIF_TYPE:ADJ } tag eng_adverb:dishonestly{ MODIF_TYPE:ADJ } tag eng_adverb:dishonourably{ MODIF_TYPE:ADJ } tag eng_adverb:disingenuously{ MODIF_TYPE:ADJ } tag eng_adverb:dismally{ MODIF_TYPE:ADJ } tag eng_adverb:disobediently{ MODIF_TYPE:ADJ } tag eng_adverb:disparagingly{ MODIF_TYPE:ADJ } tag eng_adverb:dispassionately{ MODIF_TYPE:ADJ } tag eng_adverb:dispiritedly{ MODIF_TYPE:ADJ } tag eng_adverb:disproportionately{ MODIF_TYPE:ADJ } tag eng_adverb:disrespectfully{ MODIF_TYPE:ADJ } tag eng_adverb:distantly{ MODIF_TYPE:ADJ } tag eng_adverb:distinctively{ MODIF_TYPE:ADJ } tag eng_adverb:distinctly{ MODIF_TYPE:ADJ } tag eng_adverb:distractedly{ MODIF_TYPE:ADJ } tag eng_adverb:distressingly{ MODIF_TYPE:ADJ } tag eng_adverb:distrustfully{ MODIF_TYPE:ADJ } tag eng_adverb:disturbingly{ MODIF_TYPE:ADJ } tag eng_adverb:diversely{ MODIF_TYPE:ADJ } tag eng_adverb:divinely{ MODIF_TYPE:ADJ } tag eng_adverb:dizzily{ MODIF_TYPE:ADJ } tag eng_adverb:doggedly{ MODIF_TYPE:ADJ } tag eng_adverb:dogmatically{ MODIF_TYPE:ADJ } tag eng_adverb:dolefully{ MODIF_TYPE:ADJ } tag eng_adverb:domestically{ MODIF_TYPE:ADJ } tag eng_adverb:doubly{ MODIF_TYPE:ADJ } tag eng_adverb:doubtfully{ MODIF_TYPE:ADJ } tag eng_adverb:dourly{ MODIF_TYPE:ADJ } tag eng_adverb:drably{ MODIF_TYPE:ADJ } tag eng_adverb:drastically{ MODIF_TYPE:ADJ } tag eng_adverb:dreadfully{ MODIF_TYPE:ADJ } tag eng_adverb:dreamily{ MODIF_TYPE:ADJ } tag eng_adverb:drearily{ MODIF_TYPE:ADJ } tag eng_adverb:drily{ MODIF_TYPE:ADJ } tag eng_adverb:drowsily{ MODIF_TYPE:ADJ } tag eng_adverb:drunkenly{ MODIF_TYPE:ADJ } tag eng_adverb:dryly{ MODIF_TYPE:ADJ } tag eng_adverb:dubiously{ MODIF_TYPE:ADJ } tag eng_adverb:dumbly{ MODIF_TYPE:ADJ } tag eng_adverb:dutifully{ MODIF_TYPE:ADJ } tag eng_adverb:dynamically{ MODIF_TYPE:ADJ } tag eng_adverb:eagarly{ MODIF_TYPE:ADJ } tag eng_adverb:eagerly{ MODIF_TYPE:ADJ } tag eng_adverb:earnestly{ MODIF_TYPE:ADJ } tag eng_adverb:easily{ MODIF_TYPE:ADJ } tag eng_adverb:eastwards{ MODIF_TYPE:ADJ } tag eng_adverb:ebulliently{ MODIF_TYPE:ADJ } tag eng_adverb:ecstatically{ MODIF_TYPE:ADJ } tag eng_adverb:edgewise{ MODIF_TYPE:ADJ } tag eng_adverb:eerily{ MODIF_TYPE:ADJ } tag eng_adverb:efficaciously{ MODIF_TYPE:ADJ } tag eng_adverb:efficiently{ MODIF_TYPE:ADJ } tag eng_adverb:effortlessly{ MODIF_TYPE:ADJ } tag eng_adverb:effusively{ MODIF_TYPE:ADJ } tag eng_adverb:egotistically{ MODIF_TYPE:ADJ } tag eng_adverb:elaborately{ MODIF_TYPE:ADJ } tag eng_adverb:electrically{ MODIF_TYPE:ADJ } tag eng_adverb:electronically{ MODIF_TYPE:ADJ } tag eng_adverb:elegantly{ MODIF_TYPE:ADJ } tag eng_adverb:eloquently{ MODIF_TYPE:ADJ } tag eng_adverb:embarrassingly{ MODIF_TYPE:ADJ } tag eng_adverb:eminently{ MODIF_TYPE:ADJ } tag eng_adverb:emotionally{ MODIF_TYPE:ADJ } tag eng_adverb:emphatically{ MODIF_TYPE:ADJ } tag eng_adverb:encouragingly{ MODIF_TYPE:ADJ } tag eng_adverb:endearingly{ MODIF_TYPE:ADJ } tag eng_adverb:endlessly{ MODIF_TYPE:ADJ } tag eng_adverb:energetically{ MODIF_TYPE:ADJ } tag eng_adverb:engagingly{ MODIF_TYPE:ADJ } tag eng_adverb:enigmatically{ MODIF_TYPE:ADJ } tag eng_adverb:enormously{ MODIF_TYPE:ADJ } tag eng_adverb:enquiringly{ MODIF_TYPE:ADJ } tag eng_adverb:enterprisingly{ MODIF_TYPE:ADJ } tag eng_adverb:entertainingly{ MODIF_TYPE:ADJ } tag eng_adverb:enthusiastically{ MODIF_TYPE:ADJ } tag eng_adverb:enviously{ MODIF_TYPE:ADJ } tag eng_adverb:epidurally{ MODIF_TYPE:ADJ } tag eng_adverb:eponymously{ MODIF_TYPE:ADJ } tag eng_adverb:equably{ MODIF_TYPE:ADJ } tag eng_adverb:equitably{ MODIF_TYPE:ADJ } tag eng_adverb:erratically{ MODIF_TYPE:ADJ } tag eng_adverb:erroneously{ MODIF_TYPE:ADJ } tag eng_adverb:eruditely{ MODIF_TYPE:ADJ } tag eng_adverb:eternally{ MODIF_TYPE:ADJ } tag eng_adverb:euphemistically{ MODIF_TYPE:ADJ } tag eng_adverb:evasively{ MODIF_TYPE:ADJ } tag eng_adverb:evenly{ MODIF_TYPE:ADJ } tag eng_adverb:evermore{ MODIF_TYPE:ADJ } tag eng_adverb:excellently{ MODIF_TYPE:ADJ } tag eng_adverb:excessively{ MODIF_TYPE:ADJ } tag eng_adverb:excitedly{ MODIF_TYPE:ADJ } tag eng_adverb:excitingly{ MODIF_TYPE:ADJ } tag eng_adverb:exclusively{ MODIF_TYPE:ADJ } tag eng_adverb:excruciatingly{ MODIF_TYPE:ADJ } tag eng_adverb:exhaustively{ MODIF_TYPE:ADJ } tag eng_adverb:exorbitantly{ MODIF_TYPE:ADJ } tag eng_adverb:expansively{ MODIF_TYPE:ADJ } tag eng_adverb:expectantly{ MODIF_TYPE:ADJ } tag eng_adverb:experimentally{ MODIF_TYPE:ADJ } tag eng_adverb:expertly{ MODIF_TYPE:ADJ } tag eng_adverb:explicitly{ MODIF_TYPE:ADJ } tag eng_adverb:explosively{ MODIF_TYPE:ADJ } tag eng_adverb:exponentially{ MODIF_TYPE:ADJ } tag eng_adverb:expressively{ MODIF_TYPE:ADJ } tag eng_adverb:expressly{ MODIF_TYPE:ADJ } tag eng_adverb:exquisitely{ MODIF_TYPE:ADJ } tag eng_adverb:extemporaneously{ MODIF_TYPE:ADJ } tag eng_adverb:extensively{ MODIF_TYPE:ADJ } tag eng_adverb:externally{ MODIF_TYPE:ADJ } tag eng_adverb:extravagantly{ MODIF_TYPE:ADJ } tag eng_adverb:exuberantly{ MODIF_TYPE:ADJ } tag eng_adverb:exultantly{ MODIF_TYPE:ADJ } tag eng_adverb:facetiously{ MODIF_TYPE:ADJ } tag eng_adverb:facially{ MODIF_TYPE:ADJ } tag eng_adverb:faintly{ MODIF_TYPE:ADJ } tag eng_adverb:faithfully{ MODIF_TYPE:ADJ } tag eng_adverb:falsely{ MODIF_TYPE:ADJ } tag eng_adverb:famously{ MODIF_TYPE:ADJ } tag eng_adverb:fanatically{ MODIF_TYPE:ADJ } tag eng_adverb:fantastically{ MODIF_TYPE:ADJ } //tag eng_adverb:fast{ MODIF_TYPE:ADJ } tag eng_adverb:fastidiously{ MODIF_TYPE:ADJ } tag eng_adverb:fatally{ MODIF_TYPE:ADJ } tag eng_adverb:fatuously{ MODIF_TYPE:ADJ } tag eng_adverb:faultlessly{ MODIF_TYPE:ADJ } tag eng_adverb:favorably{ MODIF_TYPE:ADJ } tag eng_adverb:favourably{ MODIF_TYPE:ADJ } tag eng_adverb:fearfully{ MODIF_TYPE:ADJ } tag eng_adverb:fearlessly{ MODIF_TYPE:ADJ } tag eng_adverb:feebly{ MODIF_TYPE:ADJ } tag eng_adverb:ferociously{ MODIF_TYPE:ADJ } tag eng_adverb:fervently{ MODIF_TYPE:ADJ } tag eng_adverb:fervidly{ MODIF_TYPE:ADJ } tag eng_adverb:feverishly{ MODIF_TYPE:ADJ } tag eng_adverb:fiendishly{ MODIF_TYPE:ADJ } tag eng_adverb:fiercely{ MODIF_TYPE:ADJ } tag eng_adverb:figuratively{ MODIF_TYPE:ADJ } tag eng_adverb:firmly{ MODIF_TYPE:ADJ } tag eng_adverb:first-class{ MODIF_TYPE:ADJ } tag eng_adverb:first-hand{ MODIF_TYPE:ADJ } tag eng_adverb:fiscally{ MODIF_TYPE:ADJ } tag eng_adverb:fitfully{ MODIF_TYPE:ADJ } tag eng_adverb:fittingly{ MODIF_TYPE:ADJ } tag eng_adverb:flagrantly{ MODIF_TYPE:ADJ } tag eng_adverb:flamboyantly{ MODIF_TYPE:ADJ } tag eng_adverb:flashily{ MODIF_TYPE:ADJ } tag eng_adverb:flawlessly{ MODIF_TYPE:ADJ } tag eng_adverb:flexibly{ MODIF_TYPE:ADJ } tag eng_adverb:flippantly{ MODIF_TYPE:ADJ } tag eng_adverb:flirtatiously{ MODIF_TYPE:ADJ } tag eng_adverb:fluently{ MODIF_TYPE:ADJ } tag eng_adverb:fondly{ MODIF_TYPE:ADJ } tag eng_adverb:foolishly{ MODIF_TYPE:ADJ } tag eng_adverb:forbiddingly{ MODIF_TYPE:ADJ } tag eng_adverb:forcefully{ MODIF_TYPE:ADJ } tag eng_adverb:forcibly{ MODIF_TYPE:ADJ } tag eng_adverb:forgivingly{ MODIF_TYPE:ADJ } tag eng_adverb:forlornly{ MODIF_TYPE:ADJ } tag eng_adverb:formally{ MODIF_TYPE:ADJ } tag eng_adverb:formidably{ MODIF_TYPE:ADJ } tag eng_adverb:forthwith{ MODIF_TYPE:ADJ } tag eng_adverb:fortissimo{ MODIF_TYPE:ADJ } tag eng_adverb:fortnightly{ MODIF_TYPE:ADJ } tag eng_adverb:fortuitously{ MODIF_TYPE:ADJ } tag eng_adverb:frankly{ MODIF_TYPE:ADJ } tag eng_adverb:frantically{ MODIF_TYPE:ADJ } tag eng_adverb:fraternally{ MODIF_TYPE:ADJ } tag eng_adverb:fraudulently{ MODIF_TYPE:ADJ } tag eng_adverb:freakishly{ MODIF_TYPE:ADJ } tag eng_adverb:freely{ MODIF_TYPE:ADJ } tag eng_adverb:frequently{ MODIF_TYPE:ADJ } tag eng_adverb:freshly{ MODIF_TYPE:ADJ } tag eng_adverb:fretfully{ MODIF_TYPE:ADJ } tag eng_adverb:frigidly{ MODIF_TYPE:ADJ } tag eng_adverb:friskily{ MODIF_TYPE:ADJ } tag eng_adverb:frivolously{ MODIF_TYPE:ADJ } tag eng_adverb:frostily{ MODIF_TYPE:ADJ } tag eng_adverb:frugally{ MODIF_TYPE:ADJ } tag eng_adverb:fruitfully{ MODIF_TYPE:ADJ } tag eng_adverb:fruitlessly{ MODIF_TYPE:ADJ } tag eng_adverb:full-time{ MODIF_TYPE:ADJ } tag eng_adverb:functionally{ MODIF_TYPE:ADJ } tag eng_adverb:funnily{ MODIF_TYPE:ADJ } tag eng_adverb:furiously{ MODIF_TYPE:ADJ } tag eng_adverb:furtively{ MODIF_TYPE:ADJ } tag eng_adverb:fussily{ MODIF_TYPE:ADJ } tag eng_adverb:gaily{ MODIF_TYPE:ADJ } tag eng_adverb:gainfully{ MODIF_TYPE:ADJ } tag eng_adverb:gallantly{ MODIF_TYPE:ADJ } tag eng_adverb:galore{ MODIF_TYPE:ADJ } tag eng_adverb:gamely{ MODIF_TYPE:ADJ } tag eng_adverb:garishly{ MODIF_TYPE:ADJ } tag eng_adverb:gaudily{ MODIF_TYPE:ADJ } tag eng_adverb:generously{ MODIF_TYPE:ADJ } tag eng_adverb:genially{ MODIF_TYPE:ADJ } tag eng_adverb:genteelly{ MODIF_TYPE:ADJ } tag eng_adverb:gently{ MODIF_TYPE:ADJ } tag eng_adverb:giddily{ MODIF_TYPE:ADJ } tag eng_adverb:girlishly{ MODIF_TYPE:ADJ } tag eng_adverb:gladly{ MODIF_TYPE:ADJ } tag eng_adverb:gleefully{ MODIF_TYPE:ADJ } tag eng_adverb:glibly{ MODIF_TYPE:ADJ } tag eng_adverb:gloatingly{ MODIF_TYPE:ADJ } tag eng_adverb:globally{ MODIF_TYPE:ADJ } tag eng_adverb:gloomily{ MODIF_TYPE:ADJ } tag eng_adverb:gloriously{ MODIF_TYPE:ADJ } tag eng_adverb:glowingly{ MODIF_TYPE:ADJ } tag eng_adverb:glumly{ MODIF_TYPE:ADJ } tag eng_adverb:gorgeously{ MODIF_TYPE:ADJ } tag eng_adverb:gracefully{ MODIF_TYPE:ADJ } tag eng_adverb:graciously{ MODIF_TYPE:ADJ } tag eng_adverb:grandly{ MODIF_TYPE:ADJ } tag eng_adverb:graphically{ MODIF_TYPE:ADJ } tag eng_adverb:gratefully{ MODIF_TYPE:ADJ } tag eng_adverb:gratis{ MODIF_TYPE:ADJ } tag eng_adverb:gratuitously{ MODIF_TYPE:ADJ } tag eng_adverb:gravely{ MODIF_TYPE:ADJ } tag eng_adverb:greedily{ MODIF_TYPE:ADJ } tag eng_adverb:gregariously{ MODIF_TYPE:ADJ } tag eng_adverb:grievously{ MODIF_TYPE:ADJ } tag eng_adverb:grimly{ MODIF_TYPE:ADJ } tag eng_adverb:grotesquely{ MODIF_TYPE:ADJ } tag eng_adverb:grudgingly{ MODIF_TYPE:ADJ } tag eng_adverb:gruffly{ MODIF_TYPE:ADJ } tag eng_adverb:grumpily{ MODIF_TYPE:ADJ } tag eng_adverb:guardedly{ MODIF_TYPE:ADJ } tag eng_adverb:guiltily{ MODIF_TYPE:ADJ } tag eng_adverb:gushingly{ MODIF_TYPE:ADJ } tag eng_adverb:habitually{ MODIF_TYPE:ADJ } tag eng_adverb:half-heartedly{ MODIF_TYPE:ADJ } tag eng_adverb:halfway{ MODIF_TYPE:ADJ } tag eng_adverb:haltingly{ MODIF_TYPE:ADJ } tag eng_adverb:handily{ MODIF_TYPE:ADJ } tag eng_adverb:handsomely{ MODIF_TYPE:ADJ } tag eng_adverb:haphazardly{ MODIF_TYPE:ADJ } tag eng_adverb:happily{ MODIF_TYPE:ADJ } tag eng_adverb:harmoniously{ MODIF_TYPE:ADJ } tag eng_adverb:harshly{ MODIF_TYPE:ADJ } tag eng_adverb:hastily{ MODIF_TYPE:ADJ } tag eng_adverb:hatefully{ MODIF_TYPE:ADJ } tag eng_adverb:haughtily{ MODIF_TYPE:ADJ } tag eng_adverb:headlong{ MODIF_TYPE:ADJ } tag eng_adverb:head-on{ MODIF_TYPE:ADJ } tag eng_adverb:heartily{ MODIF_TYPE:ADJ } tag eng_adverb:heartlessly{ MODIF_TYPE:ADJ } tag eng_adverb:heatedly{ MODIF_TYPE:ADJ } tag eng_adverb:helpfully{ MODIF_TYPE:ADJ } tag eng_adverb:helplessly{ MODIF_TYPE:ADJ } tag eng_adverb:helter-skelter{ MODIF_TYPE:ADJ } tag eng_adverb:henceforth{ MODIF_TYPE:ADJ } tag eng_adverb:hereabouts{ MODIF_TYPE:ADJ } tag eng_adverb:hereafter{ MODIF_TYPE:ADJ } tag eng_adverb:hermetically{ MODIF_TYPE:ADJ } tag eng_adverb:heroically{ MODIF_TYPE:ADJ } tag eng_adverb:hesitantly{ MODIF_TYPE:ADJ } tag eng_adverb:hesitatingly{ MODIF_TYPE:ADJ } tag eng_adverb:hideously{ MODIF_TYPE:ADJ } tag eng_adverb:higgledy-piggledy{ MODIF_TYPE:ADJ } tag eng_adverb:high-handedly{ MODIF_TYPE:ADJ } tag eng_adverb:hilariously{ MODIF_TYPE:ADJ } tag eng_adverb:hither{ MODIF_TYPE:ADJ } tag eng_adverb:hitherto{ MODIF_TYPE:ADJ } tag eng_adverb:hoarsely{ MODIF_TYPE:ADJ } tag eng_adverb:homeward{ MODIF_TYPE:ADJ } tag eng_adverb:homewards{ MODIF_TYPE:ADJ } tag eng_adverb:honestly{ MODIF_TYPE:ADJ } tag eng_adverb:honorably{ MODIF_TYPE:ADJ } tag eng_adverb:honourably{ MODIF_TYPE:ADJ } tag eng_adverb:hopelessly{ MODIF_TYPE:ADJ } tag eng_adverb:horizontally{ MODIF_TYPE:ADJ } tag eng_adverb:horribly{ MODIF_TYPE:ADJ } tag eng_adverb:horrifically{ MODIF_TYPE:ADJ } tag eng_adverb:hospitably{ MODIF_TYPE:ADJ } tag eng_adverb:hotly{ MODIF_TYPE:ADJ } tag eng_adverb:huffily{ MODIF_TYPE:ADJ } tag eng_adverb:humanely{ MODIF_TYPE:ADJ } tag eng_adverb:humbly{ MODIF_TYPE:ADJ } tag eng_adverb:humorously{ MODIF_TYPE:ADJ } tag eng_adverb:hungrily{ MODIF_TYPE:ADJ } tag eng_adverb:hurriedly{ MODIF_TYPE:ADJ } tag eng_adverb:huskily{ MODIF_TYPE:ADJ } tag eng_adverb:hypocritically{ MODIF_TYPE:ADJ } tag eng_adverb:hysterically{ MODIF_TYPE:ADJ } tag eng_adverb:icily{ MODIF_TYPE:ADJ } tag eng_adverb:identically{ MODIF_TYPE:ADJ } tag eng_adverb:ideologically{ MODIF_TYPE:ADJ } tag eng_adverb:idiomatically{ MODIF_TYPE:ADJ } tag eng_adverb:idly{ MODIF_TYPE:ADJ } tag eng_adverb:illegally{ MODIF_TYPE:ADJ } tag eng_adverb:illegibly{ MODIF_TYPE:ADJ } tag eng_adverb:illegitimately{ MODIF_TYPE:ADJ } tag eng_adverb:illicitly{ MODIF_TYPE:ADJ } tag eng_adverb:illustriously{ MODIF_TYPE:ADJ } tag eng_adverb:imaginatively{ MODIF_TYPE:ADJ } tag eng_adverb:immaculately{ MODIF_TYPE:ADJ } tag eng_adverb:immeasurably{ MODIF_TYPE:ADJ } tag eng_adverb:immensely{ MODIF_TYPE:ADJ } tag eng_adverb:imminently{ MODIF_TYPE:ADJ } tag eng_adverb:immodestly{ MODIF_TYPE:ADJ } tag eng_adverb:immorally{ MODIF_TYPE:ADJ } tag eng_adverb:impartially{ MODIF_TYPE:ADJ } tag eng_adverb:impassively{ MODIF_TYPE:ADJ } tag eng_adverb:impatiently{ MODIF_TYPE:ADJ } tag eng_adverb:impeccably{ MODIF_TYPE:ADJ } tag eng_adverb:imperceptibly{ MODIF_TYPE:ADJ } tag eng_adverb:imperfectly{ MODIF_TYPE:ADJ } tag eng_adverb:imperially{ MODIF_TYPE:ADJ } tag eng_adverb:imperiously{ MODIF_TYPE:ADJ } tag eng_adverb:impertinently{ MODIF_TYPE:ADJ } tag eng_adverb:impetuously{ MODIF_TYPE:ADJ } tag eng_adverb:impishly{ MODIF_TYPE:ADJ } tag eng_adverb:implausibly{ MODIF_TYPE:ADJ } tag eng_adverb:implicitly{ MODIF_TYPE:ADJ } tag eng_adverb:imploringly{ MODIF_TYPE:ADJ } tag eng_adverb:impolitely{ MODIF_TYPE:ADJ } tag eng_adverb:imposingly{ MODIF_TYPE:ADJ } tag eng_adverb:impossibly{ MODIF_TYPE:ADJ } tag eng_adverb:impractically{ MODIF_TYPE:ADJ } tag eng_adverb:imprecisely{ MODIF_TYPE:ADJ } tag eng_adverb:impressively{ MODIF_TYPE:ADJ } tag eng_adverb:improperly{ MODIF_TYPE:ADJ } tag eng_adverb:imprudently{ MODIF_TYPE:ADJ } tag eng_adverb:impudently{ MODIF_TYPE:ADJ } tag eng_adverb:impulsively{ MODIF_TYPE:ADJ } tag eng_adverb:inaccurately{ MODIF_TYPE:ADJ } tag eng_adverb:inadequately{ MODIF_TYPE:ADJ } tag eng_adverb:inadvertantly{ MODIF_TYPE:ADJ } tag eng_adverb:inadvertently{ MODIF_TYPE:ADJ } tag eng_adverb:inanely{ MODIF_TYPE:ADJ } tag eng_adverb:inappropriately{ MODIF_TYPE:ADJ } tag eng_adverb:inarticulately{ MODIF_TYPE:ADJ } tag eng_adverb:incessantly{ MODIF_TYPE:ADJ } tag eng_adverb:incisively{ MODIF_TYPE:ADJ } tag eng_adverb:inclusively{ MODIF_TYPE:ADJ } tag eng_adverb:incognito{ MODIF_TYPE:ADJ } tag eng_adverb:incoherently{ MODIF_TYPE:ADJ } tag eng_adverb:incompetently{ MODIF_TYPE:ADJ } tag eng_adverb:incompletely{ MODIF_TYPE:ADJ } tag eng_adverb:inconclusively{ MODIF_TYPE:ADJ } tag eng_adverb:incongruously{ MODIF_TYPE:ADJ } tag eng_adverb:inconsiderately{ MODIF_TYPE:ADJ } tag eng_adverb:inconsistently{ MODIF_TYPE:ADJ } tag eng_adverb:inconspicuously{ MODIF_TYPE:ADJ } tag eng_adverb:inconveniently{ MODIF_TYPE:ADJ } tag eng_adverb:incorrectly{ MODIF_TYPE:ADJ } tag eng_adverb:incredulously{ MODIF_TYPE:ADJ } tag eng_adverb:indecently{ MODIF_TYPE:ADJ } tag eng_adverb:indecisively{ MODIF_TYPE:ADJ } tag eng_adverb:indefinitely{ MODIF_TYPE:ADJ } tag eng_adverb:indelibly{ MODIF_TYPE:ADJ } tag eng_adverb:indifferently{ MODIF_TYPE:ADJ } tag eng_adverb:indignantly{ MODIF_TYPE:ADJ } tag eng_adverb:indirectly{ MODIF_TYPE:ADJ } tag eng_adverb:indiscreetly{ MODIF_TYPE:ADJ } tag eng_adverb:indiscriminately{ MODIF_TYPE:ADJ } tag eng_adverb:individually{ MODIF_TYPE:ADJ } tag eng_adverb:indolently{ MODIF_TYPE:ADJ } tag eng_adverb:industriously{ MODIF_TYPE:ADJ } tag eng_adverb:ineffably{ MODIF_TYPE:ADJ } tag eng_adverb:ineffectively{ MODIF_TYPE:ADJ } tag eng_adverb:ineffectually{ MODIF_TYPE:ADJ } tag eng_adverb:inefficiently{ MODIF_TYPE:ADJ } tag eng_adverb:inelegantly{ MODIF_TYPE:ADJ } tag eng_adverb:ineptly{ MODIF_TYPE:ADJ } tag eng_adverb:inescapably{ MODIF_TYPE:ADJ } tag eng_adverb:inexorably{ MODIF_TYPE:ADJ } tag eng_adverb:inexpensively{ MODIF_TYPE:ADJ } tag eng_adverb:inexplicably{ MODIF_TYPE:ADJ } tag eng_adverb:inextricably{ MODIF_TYPE:ADJ } tag eng_adverb:infamously{ MODIF_TYPE:ADJ } tag eng_adverb:inflexibly{ MODIF_TYPE:ADJ } tag eng_adverb:informally{ MODIF_TYPE:ADJ } tag eng_adverb:informatively{ MODIF_TYPE:ADJ } tag eng_adverb:infrequently{ MODIF_TYPE:ADJ } tag eng_adverb:ingeniously{ MODIF_TYPE:ADJ } tag eng_adverb:ingratiatingly{ MODIF_TYPE:ADJ } tag eng_adverb:inhumanely{ MODIF_TYPE:ADJ } tag eng_adverb:inimitably{ MODIF_TYPE:ADJ } tag eng_adverb:innately{ MODIF_TYPE:ADJ } tag eng_adverb:innocently{ MODIF_TYPE:ADJ } tag eng_adverb:inoffensively{ MODIF_TYPE:ADJ } tag eng_adverb:inordinately{ MODIF_TYPE:ADJ } tag eng_adverb:inorganically{ MODIF_TYPE:ADJ } tag eng_adverb:inquiringly{ MODIF_TYPE:ADJ } tag eng_adverb:inquisitively{ MODIF_TYPE:ADJ } tag eng_adverb:insanely{ MODIF_TYPE:ADJ } tag eng_adverb:insatiably{ MODIF_TYPE:ADJ } tag eng_adverb:insecurely{ MODIF_TYPE:ADJ } tag eng_adverb:insensitively{ MODIF_TYPE:ADJ } tag eng_adverb:insidiously{ MODIF_TYPE:ADJ } tag eng_adverb:insightfully{ MODIF_TYPE:ADJ } tag eng_adverb:insinuatingly{ MODIF_TYPE:ADJ } tag eng_adverb:insipidly{ MODIF_TYPE:ADJ } tag eng_adverb:insistently{ MODIF_TYPE:ADJ } tag eng_adverb:insolently{ MODIF_TYPE:ADJ } tag eng_adverb:instantaneously{ MODIF_TYPE:ADJ } tag eng_adverb:instantly{ MODIF_TYPE:ADJ } tag eng_adverb:instinctively{ MODIF_TYPE:ADJ } tag eng_adverb:insufferably{ MODIF_TYPE:ADJ } tag eng_adverb:insufficiently{ MODIF_TYPE:ADJ } tag eng_adverb:insultingly{ MODIF_TYPE:ADJ } tag eng_adverb:insuperably{ MODIF_TYPE:ADJ } tag eng_adverb:integrally{ MODIF_TYPE:ADJ } tag eng_adverb:intellectually{ MODIF_TYPE:ADJ } tag eng_adverb:intelligently{ MODIF_TYPE:ADJ } tag eng_adverb:intelligibly{ MODIF_TYPE:ADJ } tag eng_adverb:intensely{ MODIF_TYPE:ADJ } tag eng_adverb:intensively{ MODIF_TYPE:ADJ } tag eng_adverb:intentionally{ MODIF_TYPE:ADJ } tag eng_adverb:intently{ MODIF_TYPE:ADJ } tag eng_adverb:interchangeably{ MODIF_TYPE:ADJ } tag eng_adverb:interminably{ MODIF_TYPE:ADJ } tag eng_adverb:intermittently{ MODIF_TYPE:ADJ } tag eng_adverb:internally{ MODIF_TYPE:ADJ } // an internally controlled environment tag eng_adverb:internationally{ MODIF_TYPE:ADJ } tag eng_adverb:interrogatively{ MODIF_TYPE:ADJ } tag eng_adverb:intimately{ MODIF_TYPE:ADJ } tag eng_adverb:intransitively{ MODIF_TYPE:ADJ } tag eng_adverb:intravenously{ MODIF_TYPE:ADJ } tag eng_adverb:intrepidly{ MODIF_TYPE:ADJ } tag eng_adverb:intricately{ MODIF_TYPE:ADJ } tag eng_adverb:intrinsically{ MODIF_TYPE:ADJ } // There are also intrinsically multidimensional FFT algorithms. tag eng_adverb:intuitively{ MODIF_TYPE:ADJ } tag eng_adverb:inventively{ MODIF_TYPE:ADJ } tag eng_adverb:inversely{ MODIF_TYPE:ADJ } tag eng_adverb:invisibly{ MODIF_TYPE:ADJ } tag eng_adverb:invitingly{ MODIF_TYPE:ADJ } tag eng_adverb:involuntarily{ MODIF_TYPE:ADJ } tag eng_adverb:inwardly{ MODIF_TYPE:ADJ } tag eng_adverb:irately{ MODIF_TYPE:ADJ } tag eng_adverb:irmly{ MODIF_TYPE:ADJ } tag eng_adverb:irrationally{ MODIF_TYPE:ADJ } tag eng_adverb:irregularly{ MODIF_TYPE:ADJ } tag eng_adverb:irrelevantly{ MODIF_TYPE:ADJ } tag eng_adverb:irreparably{ MODIF_TYPE:ADJ } tag eng_adverb:irresistibly{ MODIF_TYPE:ADJ } tag eng_adverb:irresponsibly{ MODIF_TYPE:ADJ } tag eng_adverb:irretrievably{ MODIF_TYPE:ADJ } tag eng_adverb:irreverently{ MODIF_TYPE:ADJ } tag eng_adverb:irreversibly{ MODIF_TYPE:ADJ } tag eng_adverb:irritably{ MODIF_TYPE:ADJ } tag eng_adverb:jarringly{ MODIF_TYPE:ADJ } tag eng_adverb:jauntily{ MODIF_TYPE:ADJ } tag eng_adverb:jealously{ MODIF_TYPE:ADJ } tag eng_adverb:jerkily{ MODIF_TYPE:ADJ } tag eng_adverb:jestingly{ MODIF_TYPE:ADJ } tag eng_adverb:jocosely{ MODIF_TYPE:ADJ } tag eng_adverb:jocularly{ MODIF_TYPE:ADJ } tag eng_adverb:jokingly{ MODIF_TYPE:ADJ } tag eng_adverb:jovially{ MODIF_TYPE:ADJ } tag eng_adverb:joyfully{ MODIF_TYPE:ADJ } tag eng_adverb:joyously{ MODIF_TYPE:ADJ } tag eng_adverb:jubilantly{ MODIF_TYPE:ADJ } tag eng_adverb:judiciously{ MODIF_TYPE:ADJ } tag eng_adverb:justly{ MODIF_TYPE:ADJ } tag eng_adverb:keenly{ MODIF_TYPE:ADJ } tag eng_adverb:knowingly{ MODIF_TYPE:ADJ } tag eng_adverb:laboriously{ MODIF_TYPE:ADJ } tag eng_adverb:lackadaisically{ MODIF_TYPE:ADJ } tag eng_adverb:laconically{ MODIF_TYPE:ADJ } tag eng_adverb:lamely{ MODIF_TYPE:ADJ } tag eng_adverb:landward{ MODIF_TYPE:ADJ } tag eng_adverb:languidly{ MODIF_TYPE:ADJ } tag eng_adverb:languorously{ MODIF_TYPE:ADJ } tag eng_adverb:lasciviously{ MODIF_TYPE:ADJ } tag eng_adverb:laterally{ MODIF_TYPE:ADJ } tag eng_adverb:latterly{ MODIF_TYPE:ADJ } tag eng_adverb:laudably{ MODIF_TYPE:ADJ } tag eng_adverb:laughingly{ MODIF_TYPE:ADJ } tag eng_adverb:lavishly{ MODIF_TYPE:ADJ } tag eng_adverb:lawfully{ MODIF_TYPE:ADJ } tag eng_adverb:lazily{ MODIF_TYPE:ADJ } tag eng_adverb:learnedly{ MODIF_TYPE:ADJ } tag eng_adverb:legally{ MODIF_TYPE:ADJ } tag eng_adverb:legibly{ MODIF_TYPE:ADJ } tag eng_adverb:legislatively{ MODIF_TYPE:ADJ } tag eng_adverb:legitimately{ MODIF_TYPE:ADJ } tag eng_adverb:lengthily{ MODIF_TYPE:ADJ } tag eng_adverb:lengthways{ MODIF_TYPE:ADJ } tag eng_adverb:leniently{ MODIF_TYPE:ADJ } tag eng_adverb:lento{ MODIF_TYPE:ADJ } tag eng_adverb:lethargically{ MODIF_TYPE:ADJ } tag eng_adverb:lewdly{ MODIF_TYPE:ADJ } tag eng_adverb:lexically{ MODIF_TYPE:ADJ } tag eng_adverb:liberally{ MODIF_TYPE:ADJ } tag eng_adverb:licentiously{ MODIF_TYPE:ADJ } tag eng_adverb:lifelessly{ MODIF_TYPE:ADJ } tag eng_adverb:light-headedly{ MODIF_TYPE:ADJ } tag eng_adverb:light-heartedly{ MODIF_TYPE:ADJ } tag eng_adverb:lightheartedly{ MODIF_TYPE:ADJ } tag eng_adverb:lightly{ MODIF_TYPE:ADJ } tag eng_adverb:limply{ MODIF_TYPE:ADJ } tag eng_adverb:linearly{ MODIF_TYPE:ADJ } tag eng_adverb:listlessly{ MODIF_TYPE:ADJ } tag eng_adverb:locally{ MODIF_TYPE:ADJ } tag eng_adverb:loftily{ MODIF_TYPE:ADJ } tag eng_adverb:logarithmically{ MODIF_TYPE:ADJ } tag eng_adverb:longingly{ MODIF_TYPE:ADJ } tag eng_adverb:longitudinally{ MODIF_TYPE:ADJ } tag eng_adverb:longways{ MODIF_TYPE:ADJ } tag eng_adverb:loosely{ MODIF_TYPE:ADJ } tag eng_adverb:loquaciously{ MODIF_TYPE:ADJ } tag eng_adverb:loudly{ MODIF_TYPE:ADJ } tag eng_adverb:lovingly{ MODIF_TYPE:ADJ } tag eng_adverb:loyally{ MODIF_TYPE:ADJ } tag eng_adverb:lucidly{ MODIF_TYPE:ADJ } tag eng_adverb:ludicrously{ MODIF_TYPE:ADJ } tag eng_adverb:lugubriously{ MODIF_TYPE:ADJ } tag eng_adverb:lukewarmly{ MODIF_TYPE:ADJ } tag eng_adverb:luridly{ MODIF_TYPE:ADJ } tag eng_adverb:lustfully{ MODIF_TYPE:ADJ } tag eng_adverb:lustily{ MODIF_TYPE:ADJ } tag eng_adverb:luxuriantly{ MODIF_TYPE:ADJ } tag eng_adverb:luxuriously{ MODIF_TYPE:ADJ } tag eng_adverb:lyrically{ MODIF_TYPE:ADJ } tag eng_adverb:magically{ MODIF_TYPE:ADJ } tag eng_adverb:magisterially{ MODIF_TYPE:ADJ } tag eng_adverb:magnanimously{ MODIF_TYPE:ADJ } tag eng_adverb:magnetically{ MODIF_TYPE:ADJ } tag eng_adverb:magnificently{ MODIF_TYPE:ADJ } tag eng_adverb:majestically{ MODIF_TYPE:ADJ } tag eng_adverb:malevolently{ MODIF_TYPE:ADJ } tag eng_adverb:maliciously{ MODIF_TYPE:ADJ } tag eng_adverb:malignantly{ MODIF_TYPE:ADJ } tag eng_adverb:manageably{ MODIF_TYPE:ADJ } tag eng_adverb:manfully{ MODIF_TYPE:ADJ } tag eng_adverb:manifestly{ MODIF_TYPE:ADJ } tag eng_adverb:manually{ MODIF_TYPE:ADJ } tag eng_adverb:markedly{ MODIF_TYPE:ADJ } tag eng_adverb:marvellously{ MODIF_TYPE:ADJ } tag eng_adverb:marvelously{ MODIF_TYPE:ADJ } tag eng_adverb:massively{ MODIF_TYPE:ADJ } tag eng_adverb:masterfully{ MODIF_TYPE:ADJ } tag eng_adverb:maternally{ MODIF_TYPE:ADJ } tag eng_adverb:maturely{ MODIF_TYPE:ADJ } tag eng_adverb:maximally{ MODIF_TYPE:ADJ } tag eng_adverb:meagrely{ MODIF_TYPE:ADJ } tag eng_adverb:meaningfully{ MODIF_TYPE:ADJ } tag eng_adverb:meanly{ MODIF_TYPE:ADJ } tag eng_adverb:measurably{ MODIF_TYPE:ADJ } tag eng_adverb:mechanically{ MODIF_TYPE:ADJ } tag eng_adverb:mechanistically{ MODIF_TYPE:ADJ } tag eng_adverb:meditatively{ MODIF_TYPE:ADJ } tag eng_adverb:meekly{ MODIF_TYPE:ADJ } tag eng_adverb:melodiously{ MODIF_TYPE:ADJ } tag eng_adverb:melodramatically{ MODIF_TYPE:ADJ } tag eng_adverb:memorably{ MODIF_TYPE:ADJ } tag eng_adverb:menacingly{ MODIF_TYPE:ADJ } tag eng_adverb:menially{ MODIF_TYPE:ADJ } tag eng_adverb:mentally{ MODIF_TYPE:ADJ } tag eng_adverb:mercilessly{ MODIF_TYPE:ADJ } tag eng_adverb:merrily{ MODIF_TYPE:ADJ } tag eng_adverb:metaphorically{ MODIF_TYPE:ADJ } tag eng_adverb:methodically{ MODIF_TYPE:ADJ } tag eng_adverb:meticulously{ MODIF_TYPE:ADJ } tag eng_adverb:metrically{ MODIF_TYPE:ADJ } tag eng_adverb:microscopically{ MODIF_TYPE:ADJ } tag eng_adverb:mightily{ MODIF_TYPE:ADJ } tag eng_adverb:mildly{ MODIF_TYPE:ADJ } tag eng_adverb:militarily{ MODIF_TYPE:ADJ } tag eng_adverb:mindlessly{ MODIF_TYPE:ADJ } tag eng_adverb:minimally{ MODIF_TYPE:ADJ } tag eng_adverb:ministerially{ MODIF_TYPE:ADJ } tag eng_adverb:minorly{ MODIF_TYPE:ADJ } tag eng_adverb:minutely{ MODIF_TYPE:ADJ } tag eng_adverb:mirthfully{ MODIF_TYPE:ADJ } tag eng_adverb:mischievously{ MODIF_TYPE:ADJ } tag eng_adverb:miserably{ MODIF_TYPE:ADJ } tag eng_adverb:mistakenly{ MODIF_TYPE:ADJ } tag eng_adverb:mistrustfully{ MODIF_TYPE:ADJ } tag eng_adverb:mockingly{ MODIF_TYPE:ADJ } tag eng_adverb:modestly{ MODIF_TYPE:ADJ } tag eng_adverb:momentously{ MODIF_TYPE:ADJ } tag eng_adverb:monetarily{ MODIF_TYPE:ADJ } tag eng_adverb:monotonously{ MODIF_TYPE:ADJ } tag eng_adverb:monstrously{ MODIF_TYPE:ADJ } tag eng_adverb:moodily{ MODIF_TYPE:ADJ } tag eng_adverb:morosely{ MODIF_TYPE:ADJ } tag eng_adverb:mortally{ MODIF_TYPE:ADJ } tag eng_adverb:mournfully{ MODIF_TYPE:ADJ } tag eng_adverb:municipally{ MODIF_TYPE:ADJ } tag eng_adverb:musically{ MODIF_TYPE:ADJ } tag eng_adverb:musingly{ MODIF_TYPE:ADJ } tag eng_adverb:mutely{ MODIF_TYPE:ADJ } tag eng_adverb:mutually{ MODIF_TYPE:ADJ } tag eng_adverb:naively{ MODIF_TYPE:ADJ } tag eng_adverb:narrow-mindedly{ MODIF_TYPE:ADJ } tag eng_adverb:nasally{ MODIF_TYPE:ADJ } tag eng_adverb:nastily{ MODIF_TYPE:ADJ } tag eng_adverb:nationally{ MODIF_TYPE:ADJ } tag eng_adverb:neatly{ MODIF_TYPE:ADJ } tag eng_adverb:needlessly{ MODIF_TYPE:ADJ } tag eng_adverb:nefariously{ MODIF_TYPE:ADJ } tag eng_adverb:negatively{ MODIF_TYPE:ADJ } tag eng_adverb:negligently{ MODIF_TYPE:ADJ } tag eng_adverb:nervously{ MODIF_TYPE:ADJ } tag eng_adverb:neurotically{ MODIF_TYPE:ADJ } tag eng_adverb:nicely{ MODIF_TYPE:ADJ } tag eng_adverb:nimbly{ MODIF_TYPE:ADJ } tag eng_adverb:nobly{ MODIF_TYPE:ADJ } tag eng_adverb:noisily{ MODIF_TYPE:ADJ } tag eng_adverb:nonchalantly{ MODIF_TYPE:ADJ } tag eng_adverb:nonstop{ MODIF_TYPE:ADJ } tag eng_adverb:normally{ MODIF_TYPE:ADJ } tag eng_adverb:northwards{ MODIF_TYPE:ADJ } tag eng_adverb:nostalgically{ MODIF_TYPE:ADJ } tag eng_adverb:noticeably{ MODIF_TYPE:ADJ } tag eng_adverb:numbly{ MODIF_TYPE:ADJ } tag eng_adverb:numerically{ MODIF_TYPE:ADJ } tag eng_adverb:obdurately{ MODIF_TYPE:ADJ } tag eng_adverb:obediently{ MODIF_TYPE:ADJ } tag eng_adverb:objectionably{ MODIF_TYPE:ADJ } tag eng_adverb:objectively{ MODIF_TYPE:ADJ } tag eng_adverb:obligingly{ MODIF_TYPE:ADJ } tag eng_adverb:obliquely{ MODIF_TYPE:ADJ } tag eng_adverb:obnoxiously{ MODIF_TYPE:ADJ } tag eng_adverb:obscenely{ MODIF_TYPE:ADJ } tag eng_adverb:obscurely{ MODIF_TYPE:ADJ } tag eng_adverb:obsequiously{ MODIF_TYPE:ADJ } tag eng_adverb:observantly{ MODIF_TYPE:ADJ } tag eng_adverb:obsessively{ MODIF_TYPE:ADJ } tag eng_adverb:obstinately{ MODIF_TYPE:ADJ } tag eng_adverb:obstreperously{ MODIF_TYPE:ADJ } tag eng_adverb:obstructively{ MODIF_TYPE:ADJ } tag eng_adverb:obtrusively{ MODIF_TYPE:ADJ } tag eng_adverb:obtusely{ MODIF_TYPE:ADJ } tag eng_adverb:odiously{ MODIF_TYPE:ADJ } tag eng_adverb:offensively{ MODIF_TYPE:ADJ } tag eng_adverb:offhand{ MODIF_TYPE:ADJ } tag eng_adverb:offhandedly{ MODIF_TYPE:ADJ } tag eng_adverb:officially{ MODIF_TYPE:ADJ } tag eng_adverb:officiously{ MODIF_TYPE:ADJ } tag eng_adverb:offstage{ MODIF_TYPE:ADJ } tag eng_adverb:onerously{ MODIF_TYPE:ADJ } tag eng_adverb:onshore{ MODIF_TYPE:ADJ } tag eng_adverb:onward{ MODIF_TYPE:ADJ } tag eng_adverb:onwards{ MODIF_TYPE:ADJ } tag eng_adverb:opaquely{ MODIF_TYPE:ADJ } tag eng_adverb:openly{ MODIF_TYPE:ADJ } tag eng_adverb:oppressively{ MODIF_TYPE:ADJ } tag eng_adverb:optimally{ MODIF_TYPE:ADJ } tag eng_adverb:optimistically{ MODIF_TYPE:ADJ } tag eng_adverb:optionally{ MODIF_TYPE:ADJ } tag eng_adverb:opulently{ MODIF_TYPE:ADJ } tag eng_adverb:orally{ MODIF_TYPE:ADJ } tag eng_adverb:organically{ MODIF_TYPE:ADJ } tag eng_adverb:ornately{ MODIF_TYPE:ADJ } tag eng_adverb:orthogonally{ MODIF_TYPE:ADJ } tag eng_adverb:ostentatiously{ MODIF_TYPE:ADJ } tag eng_adverb:outrageously{ MODIF_TYPE:ADJ } tag eng_adverb:outspokenly{ MODIF_TYPE:ADJ } tag eng_adverb:outstandingly{ MODIF_TYPE:ADJ } tag eng_adverb:outwardly{ MODIF_TYPE:ADJ } tag eng_adverb:overbearingly{ MODIF_TYPE:ADJ } tag eng_adverb:overboard{ MODIF_TYPE:ADJ } tag eng_adverb:overtly{ MODIF_TYPE:ADJ } tag eng_adverb:overwhelmingly{ MODIF_TYPE:ADJ } tag eng_adverb:painfully{ MODIF_TYPE:ADJ } tag eng_adverb:painlessly{ MODIF_TYPE:ADJ } tag eng_adverb:painstakingly{ MODIF_TYPE:ADJ } tag eng_adverb:palatably{ MODIF_TYPE:ADJ } tag eng_adverb:palmately{ MODIF_TYPE:ADJ } tag eng_adverb:palpably{ MODIF_TYPE:ADJ } tag eng_adverb:parentally{ MODIF_TYPE:ADJ } tag eng_adverb:parenthetically{ MODIF_TYPE:ADJ } tag eng_adverb:parochially{ MODIF_TYPE:ADJ } tag eng_adverb:part-time{ MODIF_TYPE:ADJ } tag eng_adverb:passably{ MODIF_TYPE:ADJ } tag eng_adverb:passim{ MODIF_TYPE:ADJ } tag eng_adverb:passionately{ MODIF_TYPE:ADJ } tag eng_adverb:passively{ MODIF_TYPE:ADJ } tag eng_adverb:paternally{ MODIF_TYPE:ADJ } tag eng_adverb:pathetically{ MODIF_TYPE:ADJ } tag eng_adverb:pathologically{ MODIF_TYPE:ADJ } tag eng_adverb:patiently{ MODIF_TYPE:ADJ } tag eng_adverb:patriotically{ MODIF_TYPE:ADJ } tag eng_adverb:patronizingly{ MODIF_TYPE:ADJ } tag eng_adverb:peaceably{ MODIF_TYPE:ADJ } tag eng_adverb:peacefully{ MODIF_TYPE:ADJ } tag eng_adverb:peculiarly{ MODIF_TYPE:ADJ } tag eng_adverb:pedantically{ MODIF_TYPE:ADJ } tag eng_adverb:peevishly{ MODIF_TYPE:ADJ } tag eng_adverb:pejoratively{ MODIF_TYPE:ADJ } tag eng_adverb:pell-mell{ MODIF_TYPE:ADJ } tag eng_adverb:penetratingly{ MODIF_TYPE:ADJ } tag eng_adverb:pensively{ MODIF_TYPE:ADJ } tag eng_adverb:perceptibly{ MODIF_TYPE:ADJ } tag eng_adverb:perceptively{ MODIF_TYPE:ADJ } tag eng_adverb:perchance{ MODIF_TYPE:ADJ } tag eng_adverb:peremptorily{ MODIF_TYPE:ADJ } tag eng_adverb:perenially{ MODIF_TYPE:ADJ } tag eng_adverb:perennially{ MODIF_TYPE:ADJ } tag eng_adverb:perfectly{ MODIF_TYPE:ADJ } tag eng_adverb:perfunctorily{ MODIF_TYPE:ADJ } tag eng_adverb:perilously{ MODIF_TYPE:ADJ } tag eng_adverb:permanently{ MODIF_TYPE:ADJ } tag eng_adverb:perniciously{ MODIF_TYPE:ADJ } tag eng_adverb:perpetually{ MODIF_TYPE:ADJ } tag eng_adverb:persistently{ MODIF_TYPE:ADJ } tag eng_adverb:personally{ MODIF_TYPE:ADJ } tag eng_adverb:persuasively{ MODIF_TYPE:ADJ } tag eng_adverb:pervasively{ MODIF_TYPE:ADJ } tag eng_adverb:perversely{ MODIF_TYPE:ADJ } tag eng_adverb:pessimistically{ MODIF_TYPE:ADJ } tag eng_adverb:petulantly{ MODIF_TYPE:ADJ } tag eng_adverb:phenomenally{ MODIF_TYPE:ADJ } tag eng_adverb:physically{ MODIF_TYPE:ADJ } tag eng_adverb:pianissimo{ MODIF_TYPE:ADJ } tag eng_adverb:picturesquely{ MODIF_TYPE:ADJ } tag eng_adverb:piercingly{ MODIF_TYPE:ADJ } tag eng_adverb:pig-headedly{ MODIF_TYPE:ADJ } tag eng_adverb:piously{ MODIF_TYPE:ADJ } tag eng_adverb:pithily{ MODIF_TYPE:ADJ } tag eng_adverb:pitifully{ MODIF_TYPE:ADJ } tag eng_adverb:pizzicato{ MODIF_TYPE:ADJ } tag eng_adverb:placidly{ MODIF_TYPE:ADJ } tag eng_adverb:plaintively{ MODIF_TYPE:ADJ } tag eng_adverb:plausibly{ MODIF_TYPE:ADJ } tag eng_adverb:playfully{ MODIF_TYPE:ADJ } tag eng_adverb:pleadingly{ MODIF_TYPE:ADJ } tag eng_adverb:pleasantly{ MODIF_TYPE:ADJ } tag eng_adverb:ploddingly{ MODIF_TYPE:ADJ } tag eng_adverb:pneumatically{ MODIF_TYPE:ADJ } tag eng_adverb:poetically{ MODIF_TYPE:ADJ } tag eng_adverb:poignantly{ MODIF_TYPE:ADJ } tag eng_adverb:point-blank{ MODIF_TYPE:ADJ } tag eng_adverb:pointedly{ MODIF_TYPE:ADJ } tag eng_adverb:polemically{ MODIF_TYPE:ADJ } tag eng_adverb:politely{ MODIF_TYPE:ADJ } tag eng_adverb:pompously{ MODIF_TYPE:ADJ } tag eng_adverb:ponderously{ MODIF_TYPE:ADJ } tag eng_adverb:poorly{ MODIF_TYPE:ADJ } tag eng_adverb:popularly{ MODIF_TYPE:ADJ } tag eng_adverb:portentously{ MODIF_TYPE:ADJ } tag eng_adverb:positively{ MODIF_TYPE:ADJ } tag eng_adverb:possessively{ MODIF_TYPE:ADJ } tag eng_adverb:posthumously{ MODIF_TYPE:ADJ } tag eng_adverb:potently{ MODIF_TYPE:ADJ } tag eng_adverb:powerfully{ MODIF_TYPE:ADJ } tag eng_adverb:precariously{ MODIF_TYPE:ADJ } tag eng_adverb:precipitously{ MODIF_TYPE:ADJ } tag eng_adverb:pre-eminently{ MODIF_TYPE:ADJ } tag eng_adverb:prematurely{ MODIF_TYPE:ADJ } tag eng_adverb:presently{ MODIF_TYPE:ADJ } tag eng_adverb:prestissimo{ MODIF_TYPE:ADJ } tag eng_adverb:presumptuously{ MODIF_TYPE:ADJ } tag eng_adverb:pretentiously{ MODIF_TYPE:ADJ } tag eng_adverb:previously{ MODIF_TYPE:ADJ } tag eng_adverb:primitively{ MODIF_TYPE:ADJ } tag eng_adverb:primly{ MODIF_TYPE:ADJ } tag eng_adverb:privately{ MODIF_TYPE:ADJ } tag eng_adverb:proactively{ MODIF_TYPE:ADJ } tag eng_adverb:prodigiously{ MODIF_TYPE:ADJ } tag eng_adverb:productively{ MODIF_TYPE:ADJ } tag eng_adverb:profanely{ MODIF_TYPE:ADJ } tag eng_adverb:professionally{ MODIF_TYPE:ADJ } tag eng_adverb:proficiently{ MODIF_TYPE:ADJ } tag eng_adverb:profitably{ MODIF_TYPE:ADJ } tag eng_adverb:profoundly{ MODIF_TYPE:ADJ } tag eng_adverb:profusely{ MODIF_TYPE:ADJ } tag eng_adverb:programmatically{ MODIF_TYPE:ADJ } tag eng_adverb:progressively{ MODIF_TYPE:ADJ } tag eng_adverb:prohibitively{ MODIF_TYPE:ADJ } tag eng_adverb:prolifically{ MODIF_TYPE:ADJ } tag eng_adverb:prominently{ MODIF_TYPE:ADJ } tag eng_adverb:promiscuously{ MODIF_TYPE:ADJ } tag eng_adverb:promptly{ MODIF_TYPE:ADJ } tag eng_adverb:prophetically{ MODIF_TYPE:ADJ } tag eng_adverb:proportionally{ MODIF_TYPE:ADJ } tag eng_adverb:proportionately{ MODIF_TYPE:ADJ } tag eng_adverb:prosaically{ MODIF_TYPE:ADJ } tag eng_adverb:protectively{ MODIF_TYPE:ADJ } tag eng_adverb:proudly{ MODIF_TYPE:ADJ } tag eng_adverb:providently{ MODIF_TYPE:ADJ } tag eng_adverb:provincially{ MODIF_TYPE:ADJ } tag eng_adverb:provisionally{ MODIF_TYPE:ADJ } tag eng_adverb:provocatively{ MODIF_TYPE:ADJ } tag eng_adverb:prudently{ MODIF_TYPE:ADJ } tag eng_adverb:prudishly{ MODIF_TYPE:ADJ } tag eng_adverb:publicly{ MODIF_TYPE:ADJ } tag eng_adverb:punctually{ MODIF_TYPE:ADJ } tag eng_adverb:puritanically{ MODIF_TYPE:ADJ } tag eng_adverb:purportedly{ MODIF_TYPE:ADJ } tag eng_adverb:purposefully{ MODIF_TYPE:ADJ } tag eng_adverb:quaintly{ MODIF_TYPE:ADJ } tag eng_adverb:qualitatively{ MODIF_TYPE:ADJ } tag eng_adverb:quantitatively{ MODIF_TYPE:ADJ } tag eng_adverb:quick{ MODIF_TYPE:ADJ } tag eng_adverb:quickly{ MODIF_TYPE:ADJ } tag eng_adverb:quiescently{ MODIF_TYPE:ADJ } tag eng_adverb:quietly{ MODIF_TYPE:ADJ } tag eng_adverb:quixotically{ MODIF_TYPE:ADJ } tag eng_adverb:quizzically{ MODIF_TYPE:ADJ } tag eng_adverb:radially{ MODIF_TYPE:ADJ } tag eng_adverb:radiantly{ MODIF_TYPE:ADJ } tag eng_adverb:radically{ MODIF_TYPE:ADJ } tag eng_adverb:rampantly{ MODIF_TYPE:ADJ } tag eng_adverb:randomly{ MODIF_TYPE:ADJ } tag eng_adverb:rapidly{ MODIF_TYPE:ADJ } tag eng_adverb:rapturously{ MODIF_TYPE:ADJ } tag eng_adverb:rarely{ MODIF_TYPE:ADJ } tag eng_adverb:rashly{ MODIF_TYPE:ADJ } tag eng_adverb:rationally{ MODIF_TYPE:ADJ } tag eng_adverb:raucously{ MODIF_TYPE:ADJ } tag eng_adverb:ravenously{ MODIF_TYPE:ADJ } tag eng_adverb:readily{ MODIF_TYPE:ADJ } tag eng_adverb:reassuringly{ MODIF_TYPE:ADJ } tag eng_adverb:recklessly{ MODIF_TYPE:ADJ } tag eng_adverb:recognizably{ MODIF_TYPE:ADJ } tag eng_adverb:redundantly{ MODIF_TYPE:ADJ } tag eng_adverb:reflectively{ MODIF_TYPE:ADJ } tag eng_adverb:refreshingly{ MODIF_TYPE:ADJ } tag eng_adverb:regally{ MODIF_TYPE:ADJ } tag eng_adverb:regionally{ MODIF_TYPE:ADJ } tag eng_adverb:regretfully{ MODIF_TYPE:ADJ } tag eng_adverb:regularly{ MODIF_TYPE:ADJ } tag eng_adverb:relentlessly{ MODIF_TYPE:ADJ } tag eng_adverb:reliably{ MODIF_TYPE:ADJ } tag eng_adverb:religiously{ MODIF_TYPE:ADJ } tag eng_adverb:reluctantly{ MODIF_TYPE:ADJ } tag eng_adverb:remorsefully{ MODIF_TYPE:ADJ } tag eng_adverb:remorselessly{ MODIF_TYPE:ADJ } tag eng_adverb:remotely{ MODIF_TYPE:ADJ } tag eng_adverb:repeatably{ MODIF_TYPE:ADJ } tag eng_adverb:repeatedly{ MODIF_TYPE:ADJ } tag eng_adverb:repentantly{ MODIF_TYPE:ADJ } tag eng_adverb:repetitively{ MODIF_TYPE:ADJ } tag eng_adverb:reproachfully{ MODIF_TYPE:ADJ } tag eng_adverb:reprovingly{ MODIF_TYPE:ADJ } tag eng_adverb:resentfully{ MODIF_TYPE:ADJ } tag eng_adverb:resignedly{ MODIF_TYPE:ADJ } tag eng_adverb:resolutely{ MODIF_TYPE:ADJ } tag eng_adverb:resoundingly{ MODIF_TYPE:ADJ } tag eng_adverb:resourcefully{ MODIF_TYPE:ADJ } tag eng_adverb:respectfully{ MODIF_TYPE:ADJ } tag eng_adverb:responsibly{ MODIF_TYPE:ADJ } tag eng_adverb:restively{ MODIF_TYPE:ADJ } tag eng_adverb:restlessly{ MODIF_TYPE:ADJ } tag eng_adverb:reticently{ MODIF_TYPE:ADJ } tag eng_adverb:retroactively{ MODIF_TYPE:ADJ } tag eng_adverb:retrospectively{ MODIF_TYPE:ADJ } tag eng_adverb:reverentially{ MODIF_TYPE:ADJ } tag eng_adverb:reverently{ MODIF_TYPE:ADJ } tag eng_adverb:rhetorically{ MODIF_TYPE:ADJ } tag eng_adverb:richly{ MODIF_TYPE:ADJ } tag eng_adverb:righteously{ MODIF_TYPE:ADJ } tag eng_adverb:rightfully{ MODIF_TYPE:ADJ } tag eng_adverb:rigidly{ MODIF_TYPE:ADJ } tag eng_adverb:rigorously{ MODIF_TYPE:ADJ } tag eng_adverb:riotously{ MODIF_TYPE:ADJ } tag eng_adverb:robustly{ MODIF_TYPE:ADJ } tag eng_adverb:romantically{ MODIF_TYPE:ADJ } tag eng_adverb:roundly{ MODIF_TYPE:ADJ } tag eng_adverb:routinely{ MODIF_TYPE:ADJ } tag eng_adverb:rowdily{ MODIF_TYPE:ADJ } tag eng_adverb:royally{ MODIF_TYPE:ADJ } tag eng_adverb:rudely{ MODIF_TYPE:ADJ } tag eng_adverb:ruefully{ MODIF_TYPE:ADJ } tag eng_adverb:ruggedly{ MODIF_TYPE:ADJ } tag eng_adverb:ruthlessly{ MODIF_TYPE:ADJ } tag eng_adverb:sadistically{ MODIF_TYPE:ADJ } tag eng_adverb:safely{ MODIF_TYPE:ADJ } tag eng_adverb:sanctimoniously{ MODIF_TYPE:ADJ } tag eng_adverb:sarcastically{ MODIF_TYPE:ADJ } tag eng_adverb:sardonically{ MODIF_TYPE:ADJ } tag eng_adverb:satirically{ MODIF_TYPE:ADJ } tag eng_adverb:satisfactorily{ MODIF_TYPE:ADJ } tag eng_adverb:savagely{ MODIF_TYPE:ADJ } tag eng_adverb:scantily{ MODIF_TYPE:ADJ } tag eng_adverb:scathingly{ MODIF_TYPE:ADJ } tag eng_adverb:sceptically{ MODIF_TYPE:ADJ } tag eng_adverb:schematically{ MODIF_TYPE:ADJ } tag eng_adverb:scornfully{ MODIF_TYPE:ADJ } tag eng_adverb:scot-free{ MODIF_TYPE:ADJ } tag eng_adverb:scrupulously{ MODIF_TYPE:ADJ } tag eng_adverb:seamlessly{ MODIF_TYPE:ADJ } tag eng_adverb:seasonally{ MODIF_TYPE:ADJ } tag eng_adverb:seawards{ MODIF_TYPE:ADJ } tag eng_adverb:secretively{ MODIF_TYPE:ADJ } tag eng_adverb:secretly{ MODIF_TYPE:ADJ } tag eng_adverb:securely{ MODIF_TYPE:ADJ } tag eng_adverb:sedately{ MODIF_TYPE:ADJ } tag eng_adverb:seductively{ MODIF_TYPE:ADJ } tag eng_adverb:selectively{ MODIF_TYPE:ADJ } tag eng_adverb:selfconsciously{ MODIF_TYPE:ADJ } tag eng_adverb:self-consciously{ MODIF_TYPE:ADJ } tag eng_adverb:selfishly{ MODIF_TYPE:ADJ } tag eng_adverb:selflessly{ MODIF_TYPE:ADJ } tag eng_adverb:sensationally{ MODIF_TYPE:ADJ } tag eng_adverb:senselessly{ MODIF_TYPE:ADJ } tag eng_adverb:sensibly{ MODIF_TYPE:ADJ } tag eng_adverb:sensitively{ MODIF_TYPE:ADJ } tag eng_adverb:sensuously{ MODIF_TYPE:ADJ } tag eng_adverb:sentimentally{ MODIF_TYPE:ADJ } tag eng_adverb:separately{ MODIF_TYPE:ADJ } tag eng_adverb:sequentially{ MODIF_TYPE:ADJ } tag eng_adverb:serenely{ MODIF_TYPE:ADJ } tag eng_adverb:serially{ MODIF_TYPE:ADJ } tag eng_adverb:seriatim{ MODIF_TYPE:ADJ } tag eng_adverb:seriously{ MODIF_TYPE:ADJ } tag eng_adverb:severally{ MODIF_TYPE:ADJ } tag eng_adverb:shabbily{ MODIF_TYPE:ADJ } tag eng_adverb:shamefully{ MODIF_TYPE:ADJ } tag eng_adverb:shamelessly{ MODIF_TYPE:ADJ } tag eng_adverb:sharply{ MODIF_TYPE:ADJ } tag eng_adverb:sheepishly{ MODIF_TYPE:ADJ } tag eng_adverb:shockingly{ MODIF_TYPE:ADJ } tag eng_adverb:shrewdly{ MODIF_TYPE:ADJ } tag eng_adverb:shrilly{ MODIF_TYPE:ADJ } tag eng_adverb:shyly{ MODIF_TYPE:ADJ } tag eng_adverb:side-saddle{ MODIF_TYPE:ADJ } tag eng_adverb:silently{ MODIF_TYPE:ADJ } tag eng_adverb:simple-mindedly{ MODIF_TYPE:ADJ } tag eng_adverb:sincerely{ MODIF_TYPE:ADJ } tag eng_adverb:single-handed{ MODIF_TYPE:ADJ } tag eng_adverb:singlehandedly{ MODIF_TYPE:ADJ } tag eng_adverb:singly{ MODIF_TYPE:ADJ } tag eng_adverb:skeptically{ MODIF_TYPE:ADJ } tag eng_adverb:skilfully{ MODIF_TYPE:ADJ } tag eng_adverb:skillfully{ MODIF_TYPE:ADJ } tag eng_adverb:sky-high{ MODIF_TYPE:ADJ } tag eng_adverb:skyward{ MODIF_TYPE:ADJ } tag eng_adverb:skywards{ MODIF_TYPE:ADJ } tag eng_adverb:slavishly{ MODIF_TYPE:ADJ } tag eng_adverb:sleepily{ MODIF_TYPE:ADJ } tag eng_adverb:slickly{ MODIF_TYPE:ADJ } tag eng_adverb:sloppily{ MODIF_TYPE:ADJ } tag eng_adverb:sluggishly{ MODIF_TYPE:ADJ } tag eng_adverb:slyly{ MODIF_TYPE:ADJ } tag eng_adverb:smartly{ MODIF_TYPE:ADJ } tag eng_adverb:smilingly{ MODIF_TYPE:ADJ } tag eng_adverb:smoothly{ MODIF_TYPE:ADJ } tag eng_adverb:smugly{ MODIF_TYPE:ADJ } tag eng_adverb:sneeringly{ MODIF_TYPE:ADJ } tag eng_adverb:snobbishly{ MODIF_TYPE:ADJ } tag eng_adverb:snootily{ MODIF_TYPE:ADJ } tag eng_adverb:snugly{ MODIF_TYPE:ADJ } tag eng_adverb:soberly{ MODIF_TYPE:ADJ } tag eng_adverb:sociably{ MODIF_TYPE:ADJ } tag eng_adverb:softly{ MODIF_TYPE:ADJ } tag eng_adverb:solemnly{ MODIF_TYPE:ADJ } tag eng_adverb:solidly{ MODIF_TYPE:ADJ } tag eng_adverb:somberly{ MODIF_TYPE:ADJ } tag eng_adverb:sombrely{ MODIF_TYPE:ADJ } tag eng_adverb:sonorously{ MODIF_TYPE:ADJ } tag eng_adverb:soothingly{ MODIF_TYPE:ADJ } tag eng_adverb:sorely{ MODIF_TYPE:ADJ } tag eng_adverb:sorrowfully{ MODIF_TYPE:ADJ } tag eng_adverb:soundly{ MODIF_TYPE:ADJ } tag eng_adverb:sourly{ MODIF_TYPE:ADJ } tag eng_adverb:southwards{ MODIF_TYPE:ADJ } tag eng_adverb:spaciously{ MODIF_TYPE:ADJ } tag eng_adverb:sparingly{ MODIF_TYPE:ADJ } tag eng_adverb:sparsely{ MODIF_TYPE:ADJ } tag eng_adverb:spasmodically{ MODIF_TYPE:ADJ } tag eng_adverb:speciously{ MODIF_TYPE:ADJ } tag eng_adverb:spectacularly{ MODIF_TYPE:ADJ } tag eng_adverb:speedily{ MODIF_TYPE:ADJ } tag eng_adverb:spiritually{ MODIF_TYPE:ADJ } tag eng_adverb:spitefully{ MODIF_TYPE:ADJ } tag eng_adverb:splendidly{ MODIF_TYPE:ADJ } tag eng_adverb:spontaneously{ MODIF_TYPE:ADJ } tag eng_adverb:sporadically{ MODIF_TYPE:ADJ } tag eng_adverb:spotlessly{ MODIF_TYPE:ADJ } tag eng_adverb:spuriously{ MODIF_TYPE:ADJ } tag eng_adverb:squarely{ MODIF_TYPE:ADJ } tag eng_adverb:staggeringly{ MODIF_TYPE:ADJ } tag eng_adverb:staidly{ MODIF_TYPE:ADJ } tag eng_adverb:starkly{ MODIF_TYPE:ADJ } tag eng_adverb:statically{ MODIF_TYPE:ADJ } tag eng_adverb:staunchly{ MODIF_TYPE:ADJ } tag eng_adverb:steadfastly{ MODIF_TYPE:ADJ } tag eng_adverb:steadily{ MODIF_TYPE:ADJ } tag eng_adverb:stealthily{ MODIF_TYPE:ADJ } tag eng_adverb:steeply{ MODIF_TYPE:ADJ } tag eng_adverb:sternly{ MODIF_TYPE:ADJ } tag eng_adverb:stiffly{ MODIF_TYPE:ADJ } tag eng_adverb:stirringly{ MODIF_TYPE:ADJ } tag eng_adverb:stochastically{ MODIF_TYPE:ADJ } tag eng_adverb:stoically{ MODIF_TYPE:ADJ } tag eng_adverb:stonily{ MODIF_TYPE:ADJ } tag eng_adverb:stoutly{ MODIF_TYPE:ADJ } tag eng_adverb:straightforwardly{ MODIF_TYPE:ADJ } tag eng_adverb:strategically{ MODIF_TYPE:ADJ } tag eng_adverb:strenuously{ MODIF_TYPE:ADJ } tag eng_adverb:stridently{ MODIF_TYPE:ADJ } tag eng_adverb:strikingly{ MODIF_TYPE:ADJ } tag eng_adverb:stringently{ MODIF_TYPE:ADJ } tag eng_adverb:strong{ MODIF_TYPE:ADJ } tag eng_adverb:strongly{ MODIF_TYPE:ADJ } tag eng_adverb:stubbornly{ MODIF_TYPE:ADJ } tag eng_adverb:studiously{ MODIF_TYPE:ADJ } tag eng_adverb:stuffily{ MODIF_TYPE:ADJ } tag eng_adverb:stunningly{ MODIF_TYPE:ADJ } tag eng_adverb:stupendously{ MODIF_TYPE:ADJ } tag eng_adverb:stupidly{ MODIF_TYPE:ADJ } tag eng_adverb:sturdily{ MODIF_TYPE:ADJ } tag eng_adverb:stylishly{ MODIF_TYPE:ADJ } tag eng_adverb:suavely{ MODIF_TYPE:ADJ } tag eng_adverb:subconsciously{ MODIF_TYPE:ADJ } tag eng_adverb:subjectively{ MODIF_TYPE:ADJ } tag eng_adverb:sublimely{ MODIF_TYPE:ADJ } tag eng_adverb:subserviently{ MODIF_TYPE:ADJ } tag eng_adverb:subtly{ MODIF_TYPE:ADJ } tag eng_adverb:successfully{ MODIF_TYPE:ADJ } tag eng_adverb:successively{ MODIF_TYPE:ADJ } tag eng_adverb:succinctly{ MODIF_TYPE:ADJ } tag eng_adverb:suddenly{ MODIF_TYPE:ADJ } tag eng_adverb:suggestively{ MODIF_TYPE:ADJ } tag eng_adverb:suitably{ MODIF_TYPE:ADJ } tag eng_adverb:sullenly{ MODIF_TYPE:ADJ } tag eng_adverb:summarily{ MODIF_TYPE:ADJ } tag eng_adverb:sumptuously{ MODIF_TYPE:ADJ } tag eng_adverb:superbly{ MODIF_TYPE:ADJ } tag eng_adverb:superciliously{ MODIF_TYPE:ADJ } tag eng_adverb:superfluously{ MODIF_TYPE:ADJ } tag eng_adverb:surgically{ MODIF_TYPE:ADJ } tag eng_adverb:surpassingly{ MODIF_TYPE:ADJ } tag eng_adverb:surreptitiously{ MODIF_TYPE:ADJ } tag eng_adverb:suspiciously{ MODIF_TYPE:ADJ } tag eng_adverb:sustainably{ MODIF_TYPE:ADJ } tag eng_adverb:sweetly{ MODIF_TYPE:ADJ } tag eng_adverb:swiftly{ MODIF_TYPE:ADJ } tag eng_adverb:symbolically{ MODIF_TYPE:ADJ } tag eng_adverb:symmetrically{ MODIF_TYPE:ADJ } tag eng_adverb:sympathetically{ MODIF_TYPE:ADJ } tag eng_adverb:synthetically{ MODIF_TYPE:ADJ } tag eng_adverb:systematically{ MODIF_TYPE:ADJ } tag eng_adverb:tacitly{ MODIF_TYPE:ADJ } tag eng_adverb:tactfully{ MODIF_TYPE:ADJ } tag eng_adverb:tactically{ MODIF_TYPE:ADJ } tag eng_adverb:tactlessly{ MODIF_TYPE:ADJ } tag eng_adverb:tangibly{ MODIF_TYPE:ADJ } tag eng_adverb:tartly{ MODIF_TYPE:ADJ } tag eng_adverb:tastefully{ MODIF_TYPE:ADJ } tag eng_adverb:tastelessly{ MODIF_TYPE:ADJ } tag eng_adverb:tauntingly{ MODIF_TYPE:ADJ } tag eng_adverb:tearfully{ MODIF_TYPE:ADJ } tag eng_adverb:technically{ MODIF_TYPE:ADJ } tag eng_adverb:tediously{ MODIF_TYPE:ADJ } tag eng_adverb:tellingly{ MODIF_TYPE:ADJ } tag eng_adverb:temperamentally{ MODIF_TYPE:ADJ } tag eng_adverb:temporarily{ MODIF_TYPE:ADJ } tag eng_adverb:tenaciously{ MODIF_TYPE:ADJ } tag eng_adverb:tenderly{ MODIF_TYPE:ADJ } tag eng_adverb:tensely{ MODIF_TYPE:ADJ } tag eng_adverb:tentatively{ MODIF_TYPE:ADJ } tag eng_adverb:tenuously{ MODIF_TYPE:ADJ } tag eng_adverb:terminally{ MODIF_TYPE:ADJ } tag eng_adverb:terrifically{ MODIF_TYPE:ADJ } tag eng_adverb:tersely{ MODIF_TYPE:ADJ } tag eng_adverb:testily{ MODIF_TYPE:ADJ } tag eng_adverb:theatrically{ MODIF_TYPE:ADJ } tag eng_adverb:thermally{ MODIF_TYPE:ADJ } tag eng_adverb:thinly{ MODIF_TYPE:ADJ } tag eng_adverb:thoroughly{ MODIF_TYPE:ADJ } tag eng_adverb:thoughtfully{ MODIF_TYPE:ADJ } tag eng_adverb:thoughtlessly{ MODIF_TYPE:ADJ } tag eng_adverb:threateningly{ MODIF_TYPE:ADJ } tag eng_adverb:tightly{ MODIF_TYPE:ADJ } tag eng_adverb:timidly{ MODIF_TYPE:ADJ } tag eng_adverb:tirelessly{ MODIF_TYPE:ADJ } tag eng_adverb:tolerably{ MODIF_TYPE:ADJ } tag eng_adverb:tolerantly{ MODIF_TYPE:ADJ } tag eng_adverb:topically{ MODIF_TYPE:ADJ } tag eng_adverb:transitively{ MODIF_TYPE:ADJ } tag eng_adverb:transparently{ MODIF_TYPE:ADJ } tag eng_adverb:treacherously{ MODIF_TYPE:ADJ } tag eng_adverb:tremendously{ MODIF_TYPE:ADJ } tag eng_adverb:trenchantly{ MODIF_TYPE:ADJ } tag eng_adverb:tritely{ MODIF_TYPE:ADJ } tag eng_adverb:triumphantly{ MODIF_TYPE:ADJ } tag eng_adverb:trivially{ MODIF_TYPE:ADJ } tag eng_adverb:truculently{ MODIF_TYPE:ADJ } tag eng_adverb:trustfully{ MODIF_TYPE:ADJ } tag eng_adverb:typographically{ MODIF_TYPE:ADJ } tag eng_adverb:unabashedly{ MODIF_TYPE:ADJ } tag eng_adverb:unambiguously{ MODIF_TYPE:ADJ } tag eng_adverb:unanimously{ MODIF_TYPE:ADJ } tag eng_adverb:unashamedly{ MODIF_TYPE:ADJ } tag eng_adverb:unassumingly{ MODIF_TYPE:ADJ } tag eng_adverb:unawares{ MODIF_TYPE:ADJ } tag eng_adverb:unceasingly{ MODIF_TYPE:ADJ } tag eng_adverb:unceremoniously{ MODIF_TYPE:ADJ } tag eng_adverb:uncomfortably{ MODIF_TYPE:ADJ } tag eng_adverb:uncommonly{ MODIF_TYPE:ADJ } tag eng_adverb:uncomplainingly{ MODIF_TYPE:ADJ } tag eng_adverb:unconditionally{ MODIF_TYPE:ADJ } tag eng_adverb:unconsciously{ MODIF_TYPE:ADJ } tag eng_adverb:uncontrollably{ MODIF_TYPE:ADJ } tag eng_adverb:unconventionally{ MODIF_TYPE:ADJ } tag eng_adverb:unconvincingly{ MODIF_TYPE:ADJ } tag eng_adverb:uncritically{ MODIF_TYPE:ADJ } tag eng_adverb:underarm{ MODIF_TYPE:ADJ } tag eng_adverb:underhand{ MODIF_TYPE:ADJ } tag eng_adverb:undiplomatically{ MODIF_TYPE:ADJ } tag eng_adverb:uneasily{ MODIF_TYPE:ADJ } tag eng_adverb:unemotionally{ MODIF_TYPE:ADJ } tag eng_adverb:unenthusiastically{ MODIF_TYPE:ADJ } tag eng_adverb:unequally{ MODIF_TYPE:ADJ } tag eng_adverb:unequivocably{ MODIF_TYPE:ADJ } tag eng_adverb:unequivocally{ MODIF_TYPE:ADJ } tag eng_adverb:unerringly{ MODIF_TYPE:ADJ } tag eng_adverb:unethically{ MODIF_TYPE:ADJ } tag eng_adverb:unevenly{ MODIF_TYPE:ADJ } tag eng_adverb:uneventfully{ MODIF_TYPE:ADJ } tag eng_adverb:unexpectedly{ MODIF_TYPE:ADJ } tag eng_adverb:unfailingly{ MODIF_TYPE:ADJ } tag eng_adverb:unfairly{ MODIF_TYPE:ADJ } tag eng_adverb:unfaithfully{ MODIF_TYPE:ADJ } tag eng_adverb:unfalteringly{ MODIF_TYPE:ADJ } tag eng_adverb:unfavorably{ MODIF_TYPE:ADJ } tag eng_adverb:unfavourably{ MODIF_TYPE:ADJ } tag eng_adverb:unfeelingly{ MODIF_TYPE:ADJ } tag eng_adverb:unflinchingly{ MODIF_TYPE:ADJ } tag eng_adverb:unforgivably{ MODIF_TYPE:ADJ } tag eng_adverb:ungraciously{ MODIF_TYPE:ADJ } tag eng_adverb:ungrammatically{ MODIF_TYPE:ADJ } tag eng_adverb:ungratefully{ MODIF_TYPE:ADJ } tag eng_adverb:ungrudgingly{ MODIF_TYPE:ADJ } tag eng_adverb:unhappily{ MODIF_TYPE:ADJ } tag eng_adverb:unhelpfully{ MODIF_TYPE:ADJ } tag eng_adverb:unhesitatingly{ MODIF_TYPE:ADJ } tag eng_adverb:unhurriedly{ MODIF_TYPE:ADJ } tag eng_adverb:uniformly{ MODIF_TYPE:ADJ } tag eng_adverb:unilaterally{ MODIF_TYPE:ADJ } tag eng_adverb:unimaginatively{ MODIF_TYPE:ADJ } tag eng_adverb:unimpressively{ MODIF_TYPE:ADJ } tag eng_adverb:unintelligibly{ MODIF_TYPE:ADJ } tag eng_adverb:unintentionally{ MODIF_TYPE:ADJ } tag eng_adverb:uninterruptedly{ MODIF_TYPE:ADJ } tag eng_adverb:uniquely{ MODIF_TYPE:ADJ } tag eng_adverb:unjustifiably{ MODIF_TYPE:ADJ } tag eng_adverb:unjustly{ MODIF_TYPE:ADJ } tag eng_adverb:unknowingly{ MODIF_TYPE:ADJ } tag eng_adverb:unlawfully{ MODIF_TYPE:ADJ } tag eng_adverb:unmusically{ MODIF_TYPE:ADJ } tag eng_adverb:unnecessarily{ MODIF_TYPE:ADJ } tag eng_adverb:unobtrusively{ MODIF_TYPE:ADJ } tag eng_adverb:unpleasantly{ MODIF_TYPE:ADJ } tag eng_adverb:unreliably{ MODIF_TYPE:ADJ } tag eng_adverb:unreservedly{ MODIF_TYPE:ADJ } tag eng_adverb:unsatisfactorily{ MODIF_TYPE:ADJ } tag eng_adverb:unscientifically{ MODIF_TYPE:ADJ } tag eng_adverb:unscrupulously{ MODIF_TYPE:ADJ } tag eng_adverb:unseasonably{ MODIF_TYPE:ADJ } tag eng_adverb:seasonably{ MODIF_TYPE:ADJ } tag eng_adverb:unselfconsciously{ MODIF_TYPE:ADJ } tag eng_adverb:unselfishly{ MODIF_TYPE:ADJ } tag eng_adverb:unsparingly{ MODIF_TYPE:ADJ } tag eng_adverb:unsuccessfully{ MODIF_TYPE:ADJ } tag eng_adverb:unsurprisingly{ MODIF_TYPE:ADJ } tag eng_adverb:unsuspectingly{ MODIF_TYPE:ADJ } tag eng_adverb:unthinkingly{ MODIF_TYPE:ADJ } tag eng_adverb:untruthfully{ MODIF_TYPE:ADJ } tag eng_adverb:unwaveringly{ MODIF_TYPE:ADJ } tag eng_adverb:unwillingly{ MODIF_TYPE:ADJ } tag eng_adverb:unwisely{ MODIF_TYPE:ADJ } tag eng_adverb:unwittingly{ MODIF_TYPE:ADJ } tag eng_adverb:uphill{ MODIF_TYPE:ADJ } tag eng_adverb:upright{ MODIF_TYPE:ADJ } tag eng_adverb:uproariously{ MODIF_TYPE:ADJ } tag eng_adverb:upstage{ MODIF_TYPE:ADJ } tag eng_adverb:upwardly{ MODIF_TYPE:ADJ } tag eng_adverb:urbanely{ MODIF_TYPE:ADJ } tag eng_adverb:urgently{ MODIF_TYPE:ADJ } tag eng_adverb:vacantly{ MODIF_TYPE:ADJ } tag eng_adverb:vaguely{ MODIF_TYPE:ADJ } tag eng_adverb:vainly{ MODIF_TYPE:ADJ } tag eng_adverb:valiantly{ MODIF_TYPE:ADJ } tag eng_adverb:variously{ MODIF_TYPE:ADJ } tag eng_adverb:varyingly{ MODIF_TYPE:ADJ } tag eng_adverb:vastly{ MODIF_TYPE:ADJ } tag eng_adverb:vehemently{ MODIF_TYPE:ADJ } tag eng_adverb:venomously{ MODIF_TYPE:ADJ } tag eng_adverb:verbally{ MODIF_TYPE:ADJ } tag eng_adverb:verbosely{ MODIF_TYPE:ADJ } tag eng_adverb:vertically{ MODIF_TYPE:ADJ } tag eng_adverb:vibrantly{ MODIF_TYPE:ADJ } tag eng_adverb:vicariously{ MODIF_TYPE:ADJ } tag eng_adverb:viciously{ MODIF_TYPE:ADJ } tag eng_adverb:victoriously{ MODIF_TYPE:ADJ } tag eng_adverb:vigilantly{ MODIF_TYPE:ADJ } tag eng_adverb:vigorously{ MODIF_TYPE:ADJ } tag eng_adverb:vindictively{ MODIF_TYPE:ADJ } tag eng_adverb:violently{ MODIF_TYPE:ADJ } tag eng_adverb:virtuously{ MODIF_TYPE:ADJ } tag eng_adverb:virulently{ MODIF_TYPE:ADJ } tag eng_adverb:visibly{ MODIF_TYPE:ADJ } tag eng_adverb:visually{ MODIF_TYPE:ADJ } tag eng_adverb:vivace{ MODIF_TYPE:ADJ } tag eng_adverb:vivaciously{ MODIF_TYPE:ADJ } tag eng_adverb:vividly{ MODIF_TYPE:ADJ } tag eng_adverb:vocally{ MODIF_TYPE:ADJ } tag eng_adverb:vociferously{ MODIF_TYPE:ADJ } tag eng_adverb:voraciously{ MODIF_TYPE:ADJ } tag eng_adverb:vulgarly{ MODIF_TYPE:ADJ } tag eng_adverb:wanly{ MODIF_TYPE:ADJ } tag eng_adverb:warily{ MODIF_TYPE:ADJ } tag eng_adverb:warmly{ MODIF_TYPE:ADJ } tag eng_adverb:weakly{ MODIF_TYPE:ADJ } tag eng_adverb:wearily{ MODIF_TYPE:ADJ } tag eng_adverb:weirdly{ MODIF_TYPE:ADJ } tag eng_adverb:westwards{ MODIF_TYPE:ADJ } tag eng_adverb:whereabout{ MODIF_TYPE:ADJ } tag eng_adverb:whereabouts{ MODIF_TYPE:ADJ } tag eng_adverb:whimsically{ MODIF_TYPE:ADJ } tag eng_adverb:wholeheartedly{ MODIF_TYPE:ADJ } tag eng_adverb:wickedly{ MODIF_TYPE:ADJ } tag eng_adverb:wildly{ MODIF_TYPE:ADJ } tag eng_adverb:wilfully{ MODIF_TYPE:ADJ } tag eng_adverb:willingly{ MODIF_TYPE:ADJ } tag eng_adverb:wisely{ MODIF_TYPE:ADJ } tag eng_adverb:wistfully{ MODIF_TYPE:ADJ } tag eng_adverb:woefully{ MODIF_TYPE:ADJ } tag eng_adverb:wonderfully{ MODIF_TYPE:ADJ } tag eng_adverb:worriedly{ MODIF_TYPE:ADJ } tag eng_adverb:wrongfully{ MODIF_TYPE:ADJ } tag eng_adverb:wrong-headedly{ MODIF_TYPE:ADJ } tag eng_adverb:wrongly{ MODIF_TYPE:ADJ } tag eng_adverb:wryly{ MODIF_TYPE:ADJ } tag eng_adverb:yearningly{ MODIF_TYPE:ADJ } tag eng_adverb:zealously{ MODIF_TYPE:ADJ } tag eng_adverb:zestfully{ MODIF_TYPE:ADJ } tag eng_adverb:differently{ MODIF_TYPE:ADJ } tag eng_adverb:independently{ MODIF_TYPE:ADJ } tag eng_adverb:too{ MODIF_TYPE:ADJ } tag eng_adverb:aberrantly{ MODIF_TYPE:ADJ } tag eng_adverb:abstractly{ MODIF_TYPE:ADJ } tag eng_adverb:acceptably{ MODIF_TYPE:ADJ } tag eng_adverb:acoustically{ MODIF_TYPE:ADJ } tag eng_adverb:acronymically{ MODIF_TYPE:ADJ } tag eng_adverb:actinically{ MODIF_TYPE:ADJ } tag eng_adverb:adaptively{ MODIF_TYPE:ADJ } tag eng_adverb:additively{ MODIF_TYPE:ADJ } tag eng_adverb:adjectively{ MODIF_TYPE:ADJ } tag eng_adverb:adjunctively{ MODIF_TYPE:ADJ } tag eng_adverb:ad nauseam{ MODIF_TYPE:ADJ } tag eng_adverb:adoptively{ MODIF_TYPE:ADJ } tag eng_adverb:adventitiously{ MODIF_TYPE:ADJ } tag eng_adverb:aerobically{ MODIF_TYPE:ADJ } tag eng_adverb:affectively{ MODIF_TYPE:ADJ } tag eng_adverb:affirmatively{ MODIF_TYPE:ADJ } tag eng_adverb:affordably{ MODIF_TYPE:ADJ } tag eng_adverb:agonistically{ MODIF_TYPE:ADJ } tag eng_adverb:algorithmically{ MODIF_TYPE:ADJ } tag eng_adverb:allosterically{ MODIF_TYPE:ADJ } tag eng_adverb:alphanumerically{ MODIF_TYPE:ADJ } tag eng_adverb:anaerobically{ MODIF_TYPE:ADJ } tag eng_adverb:anecdotally{ MODIF_TYPE:ADJ } tag eng_adverb:aneurysmally{ MODIF_TYPE:ADJ } tag eng_adverb:angiographically{ MODIF_TYPE:ADJ } tag eng_adverb:anionically{ MODIF_TYPE:ADJ } tag eng_adverb:anomalously{ MODIF_TYPE:ADJ } tag eng_adverb:antagonistically{ MODIF_TYPE:ADJ } tag eng_adverb:antenatally{ MODIF_TYPE:ADJ } tag eng_adverb:anteriorly{ MODIF_TYPE:ADJ } tag eng_adverb:anterogradely{ MODIF_TYPE:ADJ } tag eng_adverb:anteroposteriorly{ MODIF_TYPE:ADJ } tag eng_adverb:anthropometrically{ MODIF_TYPE:ADJ } tag eng_adverb:anthropomorphically{ MODIF_TYPE:ADJ } tag eng_adverb:antidromically{ MODIF_TYPE:ADJ } tag eng_adverb:antigenically{ MODIF_TYPE:ADJ } tag eng_adverb:antithetically{ MODIF_TYPE:ADJ } tag eng_adverb:antivirally{ MODIF_TYPE:ADJ } tag eng_adverb:any time{ MODIF_TYPE:ADJ } tag eng_adverb:apically{ MODIF_TYPE:ADJ } tag eng_adverb:archaeologically{ MODIF_TYPE:ADJ } tag eng_adverb:artefactually{ MODIF_TYPE:ADJ } tag eng_adverb:asynchronously{ MODIF_TYPE:ADJ } tag eng_adverb:atomistically{ MODIF_TYPE:ADJ } tag eng_adverb:attentionally{ MODIF_TYPE:ADJ } tag eng_adverb:audiovisually{ MODIF_TYPE:ADJ } tag eng_adverb:aurally{ MODIF_TYPE:ADJ } tag eng_adverb:autocatalytically{ MODIF_TYPE:ADJ } tag eng_adverb:autogenously{ MODIF_TYPE:ADJ } tag eng_adverb:autonomically{ MODIF_TYPE:ADJ } tag eng_adverb:autonomously{ MODIF_TYPE:ADJ } tag eng_adverb:autosomally{ MODIF_TYPE:ADJ } tag eng_adverb:autotrophically{ MODIF_TYPE:ADJ } tag eng_adverb:averagely{ MODIF_TYPE:ADJ } tag eng_adverb:axenically{ MODIF_TYPE:ADJ } tag eng_adverb:biannually{ MODIF_TYPE:ADJ } tag eng_adverb:bibliographically{ MODIF_TYPE:ADJ } tag eng_adverb:bidimensionally{ MODIF_TYPE:ADJ } tag eng_adverb:bifunctionally{ MODIF_TYPE:ADJ } tag eng_adverb:bimodally{ MODIF_TYPE:ADJ } tag eng_adverb:binocularly{ MODIF_TYPE:ADJ } tag eng_adverb:biomechanically{ MODIF_TYPE:ADJ } tag eng_adverb:biomedically{ MODIF_TYPE:ADJ } tag eng_adverb:biometrically{ MODIF_TYPE:ADJ } tag eng_adverb:biophysically{ MODIF_TYPE:ADJ } tag eng_adverb:biosynthetically{ MODIF_TYPE:ADJ } tag eng_adverb:biphasically{ MODIF_TYPE:ADJ } tag eng_adverb:bronchoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:calorimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:canonically{ MODIF_TYPE:ADJ } tag eng_adverb:cartographically{ MODIF_TYPE:ADJ } tag eng_adverb:catalytically{ MODIF_TYPE:ADJ } tag eng_adverb:catastrophically{ MODIF_TYPE:ADJ } tag eng_adverb:caudally{ MODIF_TYPE:ADJ } tag eng_adverb:cellularly{ MODIF_TYPE:ADJ } tag eng_adverb:centrifugally{ MODIF_TYPE:ADJ } tag eng_adverb:cheerlessly{ MODIF_TYPE:ADJ } tag eng_adverb:cholinergically{ MODIF_TYPE:ADJ } tag eng_adverb:chromatographically{ MODIF_TYPE:ADJ } tag eng_adverb:chromosomally{ MODIF_TYPE:ADJ } tag eng_adverb:cinematographically{ MODIF_TYPE:ADJ } tag eng_adverb:circularly{ MODIF_TYPE:ADJ } tag eng_adverb:circumferentially{ MODIF_TYPE:ADJ } tag eng_adverb:circumstantially{ MODIF_TYPE:ADJ } tag eng_adverb:cladistically{ MODIF_TYPE:ADJ } tag eng_adverb:clinicopathologically{ MODIF_TYPE:ADJ } tag eng_adverb:clonally{ MODIF_TYPE:ADJ } tag eng_adverb:advantageously{ MODIF_TYPE:ADJ } tag eng_adverb:abdominally{ MODIF_TYPE:ADJ } tag eng_adverb:anally{ MODIF_TYPE:ADJ } tag eng_adverb:ante meridiem{ MODIF_TYPE:ADJ } tag eng_adverb:anteromedially{ MODIF_TYPE:ADJ } tag eng_adverb:arterially{ MODIF_TYPE:ADJ } tag eng_adverb:axially{ MODIF_TYPE:ADJ } tag eng_adverb:buccally{ MODIF_TYPE:ADJ } tag eng_adverb:buccolingually{ MODIF_TYPE:ADJ } tag eng_adverb:cardiovascularly{ MODIF_TYPE:ADJ } tag eng_adverb:centroparietally{ MODIF_TYPE:ADJ } tag eng_adverb:centrotemporally{ MODIF_TYPE:ADJ } tag eng_adverb:contiguously{ MODIF_TYPE:ADJ } tag eng_adverb:cutaneously{ MODIF_TYPE:ADJ } tag eng_adverb:dermally{ MODIF_TYPE:ADJ } tag eng_adverb:dorso-ventrally{ MODIF_TYPE:ADJ } tag eng_adverb:ectodermally{ MODIF_TYPE:ADJ } tag eng_adverb:endotracheally{ MODIF_TYPE:ADJ } tag eng_adverb:epithelially{ MODIF_TYPE:ADJ } tag eng_adverb:extradurally{ MODIF_TYPE:ADJ } tag eng_adverb:extrahepatically{ MODIF_TYPE:ADJ } tag eng_adverb:incisionally{ MODIF_TYPE:ADJ } tag eng_adverb:inferolaterally{ MODIF_TYPE:ADJ } tag eng_adverb:inferoposteriorly{ MODIF_TYPE:ADJ } tag eng_adverb:inferotemporally{ MODIF_TYPE:ADJ } tag eng_adverb:intercellularly{ MODIF_TYPE:ADJ } tag eng_adverb:interfollicularly{ MODIF_TYPE:ADJ } tag eng_adverb:interictally{ MODIF_TYPE:ADJ } tag eng_adverb:intermolecularly{ MODIF_TYPE:ADJ } tag eng_adverb:interoinferiorly{ MODIF_TYPE:ADJ } tag eng_adverb:intestinally{ MODIF_TYPE:ADJ } tag eng_adverb:intra-abdominally{ MODIF_TYPE:ADJ } tag eng_adverb:intra-amniotically{ MODIF_TYPE:ADJ } tag eng_adverb:intra-arterially{ MODIF_TYPE:ADJ } tag eng_adverb:intra-atrially{ MODIF_TYPE:ADJ } tag eng_adverb:intracellularly{ MODIF_TYPE:ADJ } tag eng_adverb:intracerebroventricularly{ MODIF_TYPE:ADJ } tag eng_adverb:intradermally{ MODIF_TYPE:ADJ } tag eng_adverb:intragastrically{ MODIF_TYPE:ADJ } tag eng_adverb:intralymphatically{ MODIF_TYPE:ADJ } tag eng_adverb:intralymphocytically{ MODIF_TYPE:ADJ } tag eng_adverb:intramolecularly{ MODIF_TYPE:ADJ } tag eng_adverb:intramuscularly{ MODIF_TYPE:ADJ } tag eng_adverb:intranasally{ MODIF_TYPE:ADJ } tag eng_adverb:intraneuronally{ MODIF_TYPE:ADJ } tag eng_adverb:intraocularly{ MODIF_TYPE:ADJ } tag eng_adverb:intraorganically{ MODIF_TYPE:ADJ } tag eng_adverb:intraperitonally{ MODIF_TYPE:ADJ } tag eng_adverb:intraperitoneally{ MODIF_TYPE:ADJ } tag eng_adverb:intrapleurally{ MODIF_TYPE:ADJ } tag eng_adverb:intrathecally{ MODIF_TYPE:ADJ } tag eng_adverb:intravascularly{ MODIF_TYPE:ADJ } tag eng_adverb:intravitreally{ MODIF_TYPE:ADJ } tag eng_adverb:labially{ MODIF_TYPE:ADJ } tag eng_adverb:lingually{ MODIF_TYPE:ADJ } tag eng_adverb:linguoapically{ MODIF_TYPE:ADJ } tag eng_adverb:medially{ MODIF_TYPE:ADJ } tag eng_adverb:mesially{ MODIF_TYPE:ADJ } tag eng_adverb:mesothoracically{ MODIF_TYPE:ADJ } tag eng_adverb:neonatally{ MODIF_TYPE:ADJ } tag eng_adverb:neurally{ MODIF_TYPE:ADJ } tag eng_adverb:neuroectodermally{ MODIF_TYPE:ADJ } tag eng_adverb:nonsimultaneously{ MODIF_TYPE:ADJ } tag eng_adverb:peripherally{ MODIF_TYPE:ADJ } tag eng_adverb:pertrochanterically{ MODIF_TYPE:ADJ } tag eng_adverb:postanoxically{ MODIF_TYPE:ADJ } tag eng_adverb:postbulbarly{ MODIF_TYPE:ADJ } tag eng_adverb:posteriorly{ MODIF_TYPE:ADJ } tag eng_adverb:postero-anteriorly{ MODIF_TYPE:ADJ } tag eng_adverb:postsynaptically{ MODIF_TYPE:ADJ } tag eng_adverb:presynaptically{ MODIF_TYPE:ADJ } tag eng_adverb:proximally{ MODIF_TYPE:ADJ } tag eng_adverb:subcutaneously{ MODIF_TYPE:ADJ } tag eng_adverb:subdermally{ MODIF_TYPE:ADJ } tag eng_adverb:supraaortically{ MODIF_TYPE:ADJ } tag eng_adverb:suprabasally{ MODIF_TYPE:ADJ } tag eng_adverb:suprapubically{ MODIF_TYPE:ADJ } tag eng_adverb:thereto{ MODIF_TYPE:ADJ } tag eng_adverb:transversely{ MODIF_TYPE:ADJ } //tag eng_adverb:up and down{ MODIF_TYPE:ADJ } tag eng_adverb:ventrally{ MODIF_TYPE:ADJ } tag eng_adverb:aetiopathogenetically{ MODIF_TYPE:ADJ } tag eng_adverb:agricuturally{ MODIF_TYPE:ADJ } tag eng_adverb:cytochemically{ MODIF_TYPE:ADJ } tag eng_adverb:esthetically{ MODIF_TYPE:ADJ } tag eng_adverb:ethnoculturally{ MODIF_TYPE:ADJ } tag eng_adverb:overridingly{ MODIF_TYPE:ADJ } tag eng_adverb:pathogenetically{ MODIF_TYPE:ADJ } tag eng_adverb:priestly{ MODIF_TYPE:ADJ } tag eng_adverb:pseudomorphically{ MODIF_TYPE:ADJ } tag eng_adverb:psionically{ MODIF_TYPE:ADJ } tag eng_adverb:revolutionally{ MODIF_TYPE:ADJ } tag eng_adverb:abluminally{ MODIF_TYPE:ADJ } tag eng_adverb:a capite ad calcem{ MODIF_TYPE:ADJ } tag eng_adverb:accelographically{ MODIF_TYPE:ADJ } tag eng_adverb:acrosomally{ MODIF_TYPE:ADJ } tag eng_adverb:adaptometrically{ MODIF_TYPE:ADJ } tag eng_adverb:adenovirally{ MODIF_TYPE:ADJ } tag eng_adverb:adrenergically{ MODIF_TYPE:ADJ } tag eng_adverb:aesthesiometrically{ MODIF_TYPE:ADJ } tag eng_adverb:aetiologically{ MODIF_TYPE:ADJ } tag eng_adverb:agee{ MODIF_TYPE:ADJ } tag eng_adverb:allergologically{ MODIF_TYPE:ADJ } tag eng_adverb:allometrically{ MODIF_TYPE:ADJ } tag eng_adverb:allotopically{ MODIF_TYPE:ADJ } tag eng_adverb:amblyoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:amnioscopically{ MODIF_TYPE:ADJ } tag eng_adverb:amperometrically{ MODIF_TYPE:ADJ } tag eng_adverb:amphotropically{ MODIF_TYPE:ADJ } tag eng_adverb:anesthaesiologically{ MODIF_TYPE:ADJ } tag eng_adverb:anesthesiologically{ MODIF_TYPE:ADJ } tag eng_adverb:angiodynographically{ MODIF_TYPE:ADJ } tag eng_adverb:angiologically{ MODIF_TYPE:ADJ } tag eng_adverb:angioscopically{ MODIF_TYPE:ADJ } tag eng_adverb:angiospirometrically{ MODIF_TYPE:ADJ } tag eng_adverb:ante cibum{ MODIF_TYPE:ADJ } tag eng_adverb:anomaloscopically{ MODIF_TYPE:ADJ } tag eng_adverb:antero-inferiorly{ MODIF_TYPE:ADJ } tag eng_adverb:anteroinferiorly{ MODIF_TYPE:ADJ } tag eng_adverb:antero-posteriorly{ MODIF_TYPE:ADJ } tag eng_adverb:antero-superiorly{ MODIF_TYPE:ADJ } tag eng_adverb:anterosuperiorly{ MODIF_TYPE:ADJ } tag eng_adverb:aortographically{ MODIF_TYPE:ADJ } tag eng_adverb:arteriographically{ MODIF_TYPE:ADJ } tag eng_adverb:arteriometrically{ MODIF_TYPE:ADJ } tag eng_adverb:arterioscopically{ MODIF_TYPE:ADJ } tag eng_adverb:arthrographically{ MODIF_TYPE:ADJ } tag eng_adverb:arthrometrically{ MODIF_TYPE:ADJ } tag eng_adverb:arthroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:artifactually{ MODIF_TYPE:ADJ } tag eng_adverb:asymptomatically{ MODIF_TYPE:ADJ } tag eng_adverb:autoradiographically{ MODIF_TYPE:ADJ } tag eng_adverb:auscultoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:atraumatically{ MODIF_TYPE:ADJ } tag eng_adverb:ataxiagraphically{ MODIF_TYPE:ADJ } tag eng_adverb:auditorily{ MODIF_TYPE:ADJ } tag eng_adverb:aversively{ MODIF_TYPE:ADJ } tag eng_adverb:axonally{ MODIF_TYPE:ADJ } tag eng_adverb:bacterially{ MODIF_TYPE:ADJ } tag eng_adverb:bacteriologically{ MODIF_TYPE:ADJ } tag eng_adverb:baculovirally{ MODIF_TYPE:ADJ } tag eng_adverb:balefully{ MODIF_TYPE:ADJ } tag eng_adverb:ballistocardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:basally{ MODIF_TYPE:ADJ } tag eng_adverb:basolaterally{ MODIF_TYPE:ADJ } tag eng_adverb:bimanually{ MODIF_TYPE:ADJ } tag eng_adverb:bioptically{ MODIF_TYPE:ADJ } tag eng_adverb:bioreductively{ MODIF_TYPE:ADJ } tag eng_adverb:biospecifically{ MODIF_TYPE:ADJ } tag eng_adverb:bivariately{ MODIF_TYPE:ADJ } tag eng_adverb:bronchospirometrically{ MODIF_TYPE:ADJ } tag eng_adverb:capillaroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:capnographically{ MODIF_TYPE:ADJ } tag eng_adverb:capnometrically{ MODIF_TYPE:ADJ } tag eng_adverb:cardiodynametrically{ MODIF_TYPE:ADJ } tag eng_adverb:cardiointegraphically{ MODIF_TYPE:ADJ } tag eng_adverb:cardiologically{ MODIF_TYPE:ADJ } tag eng_adverb:cardiophonically{ MODIF_TYPE:ADJ } tag eng_adverb:cardioscopically{ MODIF_TYPE:ADJ } tag eng_adverb:cardiotocographically{ MODIF_TYPE:ADJ } tag eng_adverb:cataclysmally{ MODIF_TYPE:ADJ } tag eng_adverb:cavographically{ MODIF_TYPE:ADJ } tag eng_adverb:centrifugationally{ MODIF_TYPE:ADJ } tag eng_adverb:centripetally{ MODIF_TYPE:ADJ } tag eng_adverb:centrosymmetrically{ MODIF_TYPE:ADJ } tag eng_adverb:chemotactically{ MODIF_TYPE:ADJ } tag eng_adverb:chemotaxonomically{ MODIF_TYPE:ADJ } tag eng_adverb:chemotrophically{ MODIF_TYPE:ADJ } tag eng_adverb:chirally{ MODIF_TYPE:ADJ } tag eng_adverb:chloridometrically{ MODIF_TYPE:ADJ } tag eng_adverb:cholangiographically{ MODIF_TYPE:ADJ } tag eng_adverb:cholangioscopically{ MODIF_TYPE:ADJ } tag eng_adverb:cholecystographically{ MODIF_TYPE:ADJ } tag eng_adverb:choledochoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:chromoradiometrically{ MODIF_TYPE:ADJ } tag eng_adverb:chronometrically{ MODIF_TYPE:ADJ } tag eng_adverb:chronomyometrically{ MODIF_TYPE:ADJ } tag eng_adverb:chronotropically{ MODIF_TYPE:ADJ } tag eng_adverb:cineangiographically{ MODIF_TYPE:ADJ } tag eng_adverb:cinefluoroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:cineradiographically{ MODIF_TYPE:ADJ } tag eng_adverb:clonotypically{ MODIF_TYPE:ADJ } tag eng_adverb:coagulantly{ MODIF_TYPE:ADJ } tag eng_adverb:coaxially{ MODIF_TYPE:ADJ } tag eng_adverb:coincidently{ MODIF_TYPE:ADJ } tag eng_adverb:cold-bloodedly{ MODIF_TYPE:ADJ } tag eng_adverb:cold-heartedly{ MODIF_TYPE:ADJ } tag eng_adverb:collaboratively{ MODIF_TYPE:ADJ } tag eng_adverb:collegially{ MODIF_TYPE:ADJ } tag eng_adverb:colonoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:colorimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:colposcopically{ MODIF_TYPE:ADJ } tag eng_adverb:combinatorially{ MODIF_TYPE:ADJ } tag eng_adverb:compactly{ MODIF_TYPE:ADJ } tag eng_adverb:compimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:complementarily{ MODIF_TYPE:ADJ } tag eng_adverb:complexly{ MODIF_TYPE:ADJ } tag eng_adverb:concentrically{ MODIF_TYPE:ADJ } tag eng_adverb:concertedly{ MODIF_TYPE:ADJ } tag eng_adverb:concomitantly{ MODIF_TYPE:ADJ } tag eng_adverb:concordantly{ MODIF_TYPE:ADJ } tag eng_adverb:conformally{ MODIF_TYPE:ADJ } tag eng_adverb:conformationally{ MODIF_TYPE:ADJ } tag eng_adverb:congenitally{ MODIF_TYPE:ADJ } tag eng_adverb:conjointly{ MODIF_TYPE:ADJ } tag eng_adverb:consensually{ MODIF_TYPE:ADJ } tag eng_adverb:constitutively{ MODIF_TYPE:ADJ } tag eng_adverb:contourographically{ MODIF_TYPE:ADJ } tag eng_adverb:contralaterally{ MODIF_TYPE:ADJ } tag eng_adverb:convergently{ MODIF_TYPE:ADJ } tag eng_adverb:convolutely{ MODIF_TYPE:ADJ } tag eng_adverb:coordinately{ MODIF_TYPE:ADJ } tag eng_adverb:coronally{ MODIF_TYPE:ADJ } tag eng_adverb:cortically{ MODIF_TYPE:ADJ } tag eng_adverb:cosmetically{ MODIF_TYPE:ADJ } tag eng_adverb:cotranslationally{ MODIF_TYPE:ADJ } tag eng_adverb:coulometrically{ MODIF_TYPE:ADJ } tag eng_adverb:covalently{ MODIF_TYPE:ADJ } tag eng_adverb:cross-reactively{ MODIF_TYPE:ADJ } tag eng_adverb:crossreactively{ MODIF_TYPE:ADJ } tag eng_adverb:cross sectionally{ MODIF_TYPE:ADJ } tag eng_adverb:cross-sectionally{ MODIF_TYPE:ADJ } tag eng_adverb:cryometrically{ MODIF_TYPE:ADJ } tag eng_adverb:crystallographically{ MODIF_TYPE:ADJ } tag eng_adverb:curatively{ MODIF_TYPE:ADJ } tag eng_adverb:curvilinearly{ MODIF_TYPE:ADJ } tag eng_adverb:cyclically{ MODIF_TYPE:ADJ } tag eng_adverb:cyclonically{ MODIF_TYPE:ADJ } tag eng_adverb:cystically{ MODIF_TYPE:ADJ } tag eng_adverb:cystometrically{ MODIF_TYPE:ADJ } tag eng_adverb:cystoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:cystourethroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:cyto-architecturally{ MODIF_TYPE:ADJ } tag eng_adverb:cytoarchitecturally{ MODIF_TYPE:ADJ } tag eng_adverb:cytofluorimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:cytofluorographically{ MODIF_TYPE:ADJ } tag eng_adverb:cytogenetically{ MODIF_TYPE:ADJ } tag eng_adverb:cytologically{ MODIF_TYPE:ADJ } tag eng_adverb:cytometrically{ MODIF_TYPE:ADJ } tag eng_adverb:cytomorphologically{ MODIF_TYPE:ADJ } tag eng_adverb:cytopathologically{ MODIF_TYPE:ADJ } tag eng_adverb:cytophotometrically{ MODIF_TYPE:ADJ } tag eng_adverb:cytoplasmically{ MODIF_TYPE:ADJ } tag eng_adverb:cytotoxically{ MODIF_TYPE:ADJ } tag eng_adverb:definitively{ MODIF_TYPE:ADJ } tag eng_adverb:deleteriously{ MODIF_TYPE:ADJ } tag eng_adverb:demographically{ MODIF_TYPE:ADJ } tag eng_adverb:de novo{ MODIF_TYPE:ADJ } tag eng_adverb:densitometrically{ MODIF_TYPE:ADJ } tag eng_adverb:dependantly{ MODIF_TYPE:ADJ } tag eng_adverb:dependently{ MODIF_TYPE:ADJ } tag eng_adverb:dermatoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:despitefully{ MODIF_TYPE:ADJ } tag eng_adverb:desultorily{ MODIF_TYPE:ADJ } tag eng_adverb:detectably{ MODIF_TYPE:ADJ } tag eng_adverb:deterministically{ MODIF_TYPE:ADJ } tag eng_adverb:developmentally{ MODIF_TYPE:ADJ } tag eng_adverb:diagnosably{ MODIF_TYPE:ADJ } tag eng_adverb:diagnostically{ MODIF_TYPE:ADJ } tag eng_adverb:dialectically{ MODIF_TYPE:ADJ } tag eng_adverb:dialytically{ MODIF_TYPE:ADJ } tag eng_adverb:diastereomerically{ MODIF_TYPE:ADJ } tag eng_adverb:dichotomously{ MODIF_TYPE:ADJ } tag eng_adverb:dihedrally{ MODIF_TYPE:ADJ } tag eng_adverb:dilatometrically{ MODIF_TYPE:ADJ } tag eng_adverb:dimensionally{ MODIF_TYPE:ADJ } tag eng_adverb:diopsimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:dioptometrically{ MODIF_TYPE:ADJ } tag eng_adverb:diplopiometrically{ MODIF_TYPE:ADJ } tag eng_adverb:directionally{ MODIF_TYPE:ADJ } tag eng_adverb:directoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:direfully{ MODIF_TYPE:ADJ } tag eng_adverb:discontinuously{ MODIF_TYPE:ADJ } tag eng_adverb:discordantly{ MODIF_TYPE:ADJ } tag eng_adverb:discrepantly{ MODIF_TYPE:ADJ } tag eng_adverb:disparately{ MODIF_TYPE:ADJ } tag eng_adverb:disproportionally{ MODIF_TYPE:ADJ } tag eng_adverb:disquietingly{ MODIF_TYPE:ADJ } tag eng_adverb:distally{ MODIF_TYPE:ADJ } tag eng_adverb:diurnally{ MODIF_TYPE:ADJ } tag eng_adverb:divergently{ MODIF_TYPE:ADJ } tag eng_adverb:dolorimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:dominantly{ MODIF_TYPE:ADJ } tag eng_adverb:dorsally{ MODIF_TYPE:ADJ } tag eng_adverb:dorsoventrally{ MODIF_TYPE:ADJ } tag eng_adverb:dosimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:dually{ MODIF_TYPE:ADJ } tag eng_adverb:duodenoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:dyadically{ MODIF_TYPE:ADJ } tag eng_adverb:dynographically{ MODIF_TYPE:ADJ } tag eng_adverb:eccentrically{ MODIF_TYPE:ADJ } tag eng_adverb:echocardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:echoencephalographically{ MODIF_TYPE:ADJ } tag eng_adverb:echographically{ MODIF_TYPE:ADJ } tag eng_adverb:echoophthalmographically{ MODIF_TYPE:ADJ } tag eng_adverb:echotomographically{ MODIF_TYPE:ADJ } tag eng_adverb:eclectically{ MODIF_TYPE:ADJ } tag eng_adverb:econometrically{ MODIF_TYPE:ADJ } tag eng_adverb:ectopically{ MODIF_TYPE:ADJ } tag eng_adverb:edematogenically{ MODIF_TYPE:ADJ } tag eng_adverb:effectually{ MODIF_TYPE:ADJ } tag eng_adverb:egomaniacally{ MODIF_TYPE:ADJ } tag eng_adverb:eikonometrically{ MODIF_TYPE:ADJ } tag eng_adverb:ektacytometrically{ MODIF_TYPE:ADJ } tag eng_adverb:electively{ MODIF_TYPE:ADJ } tag eng_adverb:electro-acoustically{ MODIF_TYPE:ADJ } tag eng_adverb:electroacoustically{ MODIF_TYPE:ADJ } tag eng_adverb:electrobasographically{ MODIF_TYPE:ADJ } //tag eng_adverb:electrocardiocontourographically{ MODIF_TYPE:ADJ } tag eng_adverb:electrocardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:electrocardioscopically{ MODIF_TYPE:ADJ } tag eng_adverb:electrochemically{ MODIF_TYPE:ADJ } tag eng_adverb:electrocorticographically{ MODIF_TYPE:ADJ } //tag eng_adverb:electroencephalographically{ MODIF_TYPE:ADJ } tag eng_adverb:electroencephaloscopically{ MODIF_TYPE:ADJ } tag eng_adverb:electrogastrographically{ MODIF_TYPE:ADJ } tag eng_adverb:electroglottographically{ MODIF_TYPE:ADJ } tag eng_adverb:electrogoniometrically{ MODIF_TYPE:ADJ } tag eng_adverb:electrographically{ MODIF_TYPE:ADJ } tag eng_adverb:electrohydraulically{ MODIF_TYPE:ADJ } tag eng_adverb:electromagnetically{ MODIF_TYPE:ADJ } tag eng_adverb:electromanometrically{ MODIF_TYPE:ADJ } tag eng_adverb:electromechanically{ MODIF_TYPE:ADJ } tag eng_adverb:electromicroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:electromyographically{ MODIF_TYPE:ADJ } tag eng_adverb:electroneurographically{ MODIF_TYPE:ADJ } tag eng_adverb:electroneuromyographically{ MODIF_TYPE:ADJ } tag eng_adverb:electron-microscopically{ MODIF_TYPE:ADJ } tag eng_adverb:electronmicroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:electronystagmographically{ MODIF_TYPE:ADJ } tag eng_adverb:electrooculographically{ MODIF_TYPE:ADJ } //tag eng_adverb:electrophonocardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:electrophorectically{ MODIF_TYPE:ADJ } tag eng_adverb:electrophoretically{ MODIF_TYPE:ADJ } tag eng_adverb:electrophysiologically{ MODIF_TYPE:ADJ } tag eng_adverb:electropupillographically{ MODIF_TYPE:ADJ } tag eng_adverb:electrostatically{ MODIF_TYPE:ADJ } tag eng_adverb:electrosurgically{ MODIF_TYPE:ADJ } tag eng_adverb:embryologically{ MODIF_TYPE:ADJ } tag eng_adverb:emergently{ MODIF_TYPE:ADJ } tag eng_adverb:empathetically{ MODIF_TYPE:ADJ } tag eng_adverb:empathically{ MODIF_TYPE:ADJ } tag eng_adverb:enantiomerically{ MODIF_TYPE:ADJ } tag eng_adverb:en bloc{ MODIF_TYPE:ADJ } tag eng_adverb:encephalographically{ MODIF_TYPE:ADJ } tag eng_adverb:encephaloscopically{ MODIF_TYPE:ADJ } tag eng_adverb:endobronchially{ MODIF_TYPE:ADJ } tag eng_adverb:endocrinologically{ MODIF_TYPE:ADJ } tag eng_adverb:endodontically{ MODIF_TYPE:ADJ } tag eng_adverb:endogenously{ MODIF_TYPE:ADJ } tag eng_adverb:endonasally{ MODIF_TYPE:ADJ } tag eng_adverb:endonucleolytically{ MODIF_TYPE:ADJ } tag eng_adverb:endoradiographically{ MODIF_TYPE:ADJ } tag eng_adverb:endoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:endosmotically{ MODIF_TYPE:ADJ } tag eng_adverb:endourologically{ MODIF_TYPE:ADJ } tag eng_adverb:en face{ MODIF_TYPE:ADJ } tag eng_adverb:en passant{ MODIF_TYPE:ADJ } tag eng_adverb:enterally{ MODIF_TYPE:ADJ } tag eng_adverb:enterically{ MODIF_TYPE:ADJ } tag eng_adverb:enthalpically{ MODIF_TYPE:ADJ } tag eng_adverb:entomologically{ MODIF_TYPE:ADJ } tag eng_adverb:entoptoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:entropically{ MODIF_TYPE:ADJ } tag eng_adverb:enzymatically{ MODIF_TYPE:ADJ } tag eng_adverb:enzymically{ MODIF_TYPE:ADJ } tag eng_adverb:enzymocytochemically{ MODIF_TYPE:ADJ } tag eng_adverb:epicutaneously{ MODIF_TYPE:ADJ } tag eng_adverb:epidemiologically{ MODIF_TYPE:ADJ } tag eng_adverb:episodically{ MODIF_TYPE:ADJ } tag eng_adverb:episomally{ MODIF_TYPE:ADJ } tag eng_adverb:epistatically{ MODIF_TYPE:ADJ } tag eng_adverb:equipotently{ MODIF_TYPE:ADJ } tag eng_adverb:equivalently{ MODIF_TYPE:ADJ } tag eng_adverb:equivocally{ MODIF_TYPE:ADJ } tag eng_adverb:ergometrically{ MODIF_TYPE:ADJ } tag eng_adverb:ergonomically{ MODIF_TYPE:ADJ } tag eng_adverb:ergospirometrically{ MODIF_TYPE:ADJ } tag eng_adverb:esthesiometrically{ MODIF_TYPE:ADJ } tag eng_adverb:etiologically{ MODIF_TYPE:ADJ } tag eng_adverb:etiopathogenetically{ MODIF_TYPE:ADJ } tag eng_adverb:etymologically{ MODIF_TYPE:ADJ } tag eng_adverb:evolutionally{ MODIF_TYPE:ADJ } tag eng_adverb:evolutionarily{ MODIF_TYPE:ADJ } tag eng_adverb:excisionally{ MODIF_TYPE:ADJ } tag eng_adverb:exocyclically{ MODIF_TYPE:ADJ } tag eng_adverb:exogenously{ MODIF_TYPE:ADJ } tag eng_adverb:expandingly{ MODIF_TYPE:ADJ } tag eng_adverb:expectedly{ MODIF_TYPE:ADJ } tag eng_adverb:expeditionally{ MODIF_TYPE:ADJ } tag eng_adverb:expeditionaly{ MODIF_TYPE:ADJ } tag eng_adverb:expeditiously{ MODIF_TYPE:ADJ } tag eng_adverb:expensively{ MODIF_TYPE:ADJ } tag eng_adverb:ex planta{ MODIF_TYPE:ADJ } tag eng_adverb:exploratively{ MODIF_TYPE:ADJ } tag eng_adverb:extra-cellularly{ MODIF_TYPE:ADJ } tag eng_adverb:extracellularly{ MODIF_TYPE:ADJ } tag eng_adverb:extrathymically{ MODIF_TYPE:ADJ } tag eng_adverb:ex vivo{ MODIF_TYPE:ADJ } tag eng_adverb:facultatively{ MODIF_TYPE:ADJ } tag eng_adverb:feelingly{ MODIF_TYPE:ADJ } tag eng_adverb:fenestrometrically{ MODIF_TYPE:ADJ } tag eng_adverb:ferrokinetically{ MODIF_TYPE:ADJ } tag eng_adverb:fetascopically{ MODIF_TYPE:ADJ } tag eng_adverb:fiberscopically{ MODIF_TYPE:ADJ } tag eng_adverb:figurally{ MODIF_TYPE:ADJ } tag eng_adverb:filtrometrically{ MODIF_TYPE:ADJ } tag eng_adverb:firstly{ MODIF_TYPE:ADJ } tag eng_adverb:fluorescently{ MODIF_TYPE:ADJ } tag eng_adverb:fluorimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:fluorometrically{ MODIF_TYPE:ADJ } tag eng_adverb:fluorophotometrically{ MODIF_TYPE:ADJ } tag eng_adverb:fluoroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:focally{ MODIF_TYPE:ADJ } tag eng_adverb:foetascopically{ MODIF_TYPE:ADJ } tag eng_adverb:forensically{ MODIF_TYPE:ADJ } tag eng_adverb:for ever{ MODIF_TYPE:ADJ } tag eng_adverb:fractally{ MODIF_TYPE:ADJ } tag eng_adverb:fractionally{ MODIF_TYPE:ADJ } tag eng_adverb:fragmentographically{ MODIF_TYPE:ADJ } tag eng_adverb:frictionally{ MODIF_TYPE:ADJ } tag eng_adverb:fro{ MODIF_TYPE:ADJ } tag eng_adverb:frontally{ MODIF_TYPE:ADJ } tag eng_adverb:futuristically{ MODIF_TYPE:ADJ } tag eng_adverb:gastroduodenoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:gastroenterologically{ MODIF_TYPE:ADJ } tag eng_adverb:gastrographically{ MODIF_TYPE:ADJ } tag eng_adverb:gayly{ MODIF_TYPE:ADJ } tag eng_adverb:genomically{ MODIF_TYPE:ADJ } tag eng_adverb:genotypically{ MODIF_TYPE:ADJ } tag eng_adverb:geochemically{ MODIF_TYPE:ADJ } tag eng_adverb:geomagnetically{ MODIF_TYPE:ADJ } tag eng_adverb:gerontologically{ MODIF_TYPE:ADJ } tag eng_adverb:gerontopsychiatrically{ MODIF_TYPE:ADJ } tag eng_adverb:gestationally{ MODIF_TYPE:ADJ } tag eng_adverb:gesturally{ MODIF_TYPE:ADJ } tag eng_adverb:gingivally{ MODIF_TYPE:ADJ } tag eng_adverb:glucometrically{ MODIF_TYPE:ADJ } tag eng_adverb:glycosidically{ MODIF_TYPE:ADJ } tag eng_adverb:goniometrically{ MODIF_TYPE:ADJ } tag eng_adverb:gonioscopically{ MODIF_TYPE:ADJ } tag eng_adverb:gravitationally{ MODIF_TYPE:ADJ } tag eng_adverb:gustometrically{ MODIF_TYPE:ADJ } tag eng_adverb:gynecologically{ MODIF_TYPE:ADJ } tag eng_adverb:haemacytometrically{ MODIF_TYPE:ADJ } tag eng_adverb:haematofluorometrically{ MODIF_TYPE:ADJ } tag eng_adverb:haematologically{ MODIF_TYPE:ADJ } tag eng_adverb:haematopoetically{ MODIF_TYPE:ADJ } tag eng_adverb:haematopoietically{ MODIF_TYPE:ADJ } tag eng_adverb:haemodynamically{ MODIF_TYPE:ADJ } tag eng_adverb:haemoglobinometrically{ MODIF_TYPE:ADJ } tag eng_adverb:haemolytically{ MODIF_TYPE:ADJ } tag eng_adverb:haemorheologically{ MODIF_TYPE:ADJ } tag eng_adverb:haemorrheologically{ MODIF_TYPE:ADJ } tag eng_adverb:haemostatically{ MODIF_TYPE:ADJ } tag eng_adverb:half-maximally{ MODIF_TYPE:ADJ } tag eng_adverb:halfmaximally{ MODIF_TYPE:ADJ } tag eng_adverb:hand to knee{ MODIF_TYPE:ADJ } tag eng_adverb:haptically{ MODIF_TYPE:ADJ } tag eng_adverb:harmlessly{ MODIF_TYPE:ADJ } tag eng_adverb:head first{ MODIF_TYPE:ADJ } tag eng_adverb:head-first{ MODIF_TYPE:ADJ } tag eng_adverb:headfirst{ MODIF_TYPE:ADJ } tag eng_adverb:heedfully{ MODIF_TYPE:ADJ } tag eng_adverb:heedlessly{ MODIF_TYPE:ADJ } tag eng_adverb:heel to knee{ MODIF_TYPE:ADJ } tag eng_adverb:helically{ MODIF_TYPE:ADJ } tag eng_adverb:hemacytometrically{ MODIF_TYPE:ADJ } tag eng_adverb:hematofluorometrically{ MODIF_TYPE:ADJ } tag eng_adverb:hematologically{ MODIF_TYPE:ADJ } tag eng_adverb:hematopoetically{ MODIF_TYPE:ADJ } tag eng_adverb:hematopoietically{ MODIF_TYPE:ADJ } tag eng_adverb:hemodynamically{ MODIF_TYPE:ADJ } tag eng_adverb:hemoglobinometrically{ MODIF_TYPE:ADJ } tag eng_adverb:hemolytically{ MODIF_TYPE:ADJ } tag eng_adverb:hemorheologically{ MODIF_TYPE:ADJ } tag eng_adverb:hemorrheologically{ MODIF_TYPE:ADJ } tag eng_adverb:hemostatically{ MODIF_TYPE:ADJ } tag eng_adverb:hepatically{ MODIF_TYPE:ADJ } tag eng_adverb:hereof{ MODIF_TYPE:ADJ } tag eng_adverb:hereto{ MODIF_TYPE:ADJ } tag eng_adverb:herniographically{ MODIF_TYPE:ADJ } tag eng_adverb:heterogeneously{ MODIF_TYPE:ADJ } tag eng_adverb:heterogenously{ MODIF_TYPE:ADJ } tag eng_adverb:heterologously{ MODIF_TYPE:ADJ } //tag eng_adverb:heterosexually{ MODIF_TYPE:ADJ } tag eng_adverb:heterosynaptically{ MODIF_TYPE:ADJ } tag eng_adverb:heterotopically{ MODIF_TYPE:ADJ } tag eng_adverb:heterotrophically{ MODIF_TYPE:ADJ } tag eng_adverb:heterotypically{ MODIF_TYPE:ADJ } tag eng_adverb:heterozygously{ MODIF_TYPE:ADJ } tag eng_adverb:hierarchically{ MODIF_TYPE:ADJ } tag eng_adverb:histoautoradiographically{ MODIF_TYPE:ADJ } tag eng_adverb:histo-cytologically{ MODIF_TYPE:ADJ } tag eng_adverb:histocytologically{ MODIF_TYPE:ADJ } tag eng_adverb:histogenetically{ MODIF_TYPE:ADJ } tag eng_adverb:histologically{ MODIF_TYPE:ADJ } tag eng_adverb:histometrically{ MODIF_TYPE:ADJ } tag eng_adverb:histomorphologically{ MODIF_TYPE:ADJ } tag eng_adverb:histomorphometrically{ MODIF_TYPE:ADJ } tag eng_adverb:histopathologically{ MODIF_TYPE:ADJ } tag eng_adverb:histo-structurally{ MODIF_TYPE:ADJ } tag eng_adverb:histostructurally{ MODIF_TYPE:ADJ } tag eng_adverb:histotypically{ MODIF_TYPE:ADJ } tag eng_adverb:holographically{ MODIF_TYPE:ADJ } tag eng_adverb:homeostatically{ MODIF_TYPE:ADJ } tag eng_adverb:homogeneously{ MODIF_TYPE:ADJ } tag eng_adverb:homologously{ MODIF_TYPE:ADJ } tag eng_adverb:homosexually{ MODIF_TYPE:ADJ } tag eng_adverb:homotypically{ MODIF_TYPE:ADJ } tag eng_adverb:homozygously{ MODIF_TYPE:ADJ } tag eng_adverb:hormonally{ MODIF_TYPE:ADJ } tag eng_adverb:humanistically{ MODIF_TYPE:ADJ } tag eng_adverb:humorally{ MODIF_TYPE:ADJ } tag eng_adverb:hydrodensitometrically{ MODIF_TYPE:ADJ } tag eng_adverb:hydrolytically{ MODIF_TYPE:ADJ } tag eng_adverb:hydrophobically{ MODIF_TYPE:ADJ } tag eng_adverb:hydropically{ MODIF_TYPE:ADJ } tag eng_adverb:hydroponically{ MODIF_TYPE:ADJ } tag eng_adverb:hyperacutely{ MODIF_TYPE:ADJ } tag eng_adverb:hyperbolically{ MODIF_TYPE:ADJ } tag eng_adverb:hyperosmotically{ MODIF_TYPE:ADJ } tag eng_adverb:hyperoxically{ MODIF_TYPE:ADJ } tag eng_adverb:hyperreflexically{ MODIF_TYPE:ADJ } tag eng_adverb:hypersensitively{ MODIF_TYPE:ADJ } tag eng_adverb:hypoxically{ MODIF_TYPE:ADJ } tag eng_adverb:hysteroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:iatrogenically{ MODIF_TYPE:ADJ } tag eng_adverb:iconically{ MODIF_TYPE:ADJ } tag eng_adverb:iconographically{ MODIF_TYPE:ADJ } tag eng_adverb:ictally{ MODIF_TYPE:ADJ } tag eng_adverb:idiotypically{ MODIF_TYPE:ADJ } tag eng_adverb:immunobiologically{ MODIF_TYPE:ADJ } tag eng_adverb:immunochemically{ MODIF_TYPE:ADJ } tag eng_adverb:immunocyto-chemically{ MODIF_TYPE:ADJ } tag eng_adverb:immunofluorometrically{ MODIF_TYPE:ADJ } tag eng_adverb:immunogenetically{ MODIF_TYPE:ADJ } tag eng_adverb:immunohistochemically{ MODIF_TYPE:ADJ } tag eng_adverb:immunohistologically{ MODIF_TYPE:ADJ } tag eng_adverb:immunologically{ MODIF_TYPE:ADJ } tag eng_adverb:immunomorphologically{ MODIF_TYPE:ADJ } tag eng_adverb:immunospecifically{ MODIF_TYPE:ADJ } tag eng_adverb:inaptly{ MODIF_TYPE:ADJ } tag eng_adverb:inaudibly{ MODIF_TYPE:ADJ } tag eng_adverb:incrementally{ MODIF_TYPE:ADJ } tag eng_adverb:indecorously{ MODIF_TYPE:ADJ } tag eng_adverb:in dies{ MODIF_TYPE:ADJ } tag eng_adverb:indigenously{ MODIF_TYPE:ADJ } tag eng_adverb:inducibly{ MODIF_TYPE:ADJ } tag eng_adverb:inductively{ MODIF_TYPE:ADJ } tag eng_adverb:industrially{ MODIF_TYPE:ADJ } tag eng_adverb:inertially{ MODIF_TYPE:ADJ } tag eng_adverb:inexcusably{ MODIF_TYPE:ADJ } tag eng_adverb:in extenso{ MODIF_TYPE:ADJ } tag eng_adverb:infero-laterally{ MODIF_TYPE:ADJ } tag eng_adverb:infero-medially{ MODIF_TYPE:ADJ } tag eng_adverb:infero-posteriorly{ MODIF_TYPE:ADJ } tag eng_adverb:infero-temporally{ MODIF_TYPE:ADJ } tag eng_adverb:infiltratively{ MODIF_TYPE:ADJ } tag eng_adverb:infrahepatically{ MODIF_TYPE:ADJ } tag eng_adverb:in fundo{ MODIF_TYPE:ADJ } tag eng_adverb:inhibitorily{ MODIF_TYPE:ADJ } tag eng_adverb:inhomogeneously{ MODIF_TYPE:ADJ } tag eng_adverb:in lieu{ MODIF_TYPE:ADJ } tag eng_adverb:inotropically{ MODIF_TYPE:ADJ } tag eng_adverb:insecticidally{ MODIF_TYPE:ADJ } tag eng_adverb:inseparably{ MODIF_TYPE:ADJ } tag eng_adverb:insertionally{ MODIF_TYPE:ADJ } tag eng_adverb:inside-out{ MODIF_TYPE:ADJ } tag eng_adverb:insignificantly{ MODIF_TYPE:ADJ } tag eng_adverb:insofar{ MODIF_TYPE:ADJ } tag eng_adverb:interactively{ MODIF_TYPE:ADJ } tag eng_adverb:interatomically{ MODIF_TYPE:ADJ } tag eng_adverb:interferometrically{ MODIF_TYPE:ADJ } tag eng_adverb:intergenerically{ MODIF_TYPE:ADJ } tag eng_adverb:intermediately{ MODIF_TYPE:ADJ } tag eng_adverb:interpretatively{ MODIF_TYPE:ADJ } tag eng_adverb:interpretively{ MODIF_TYPE:ADJ } tag eng_adverb:interstitially{ MODIF_TYPE:ADJ } tag eng_adverb:intraabdominally{ MODIF_TYPE:ADJ } tag eng_adverb:intra-amnionically{ MODIF_TYPE:ADJ } tag eng_adverb:intraamnionically{ MODIF_TYPE:ADJ } tag eng_adverb:intraamniotically{ MODIF_TYPE:ADJ } tag eng_adverb:intraaortically{ MODIF_TYPE:ADJ } tag eng_adverb:intraarterially{ MODIF_TYPE:ADJ } tag eng_adverb:intraarticularly{ MODIF_TYPE:ADJ } tag eng_adverb:intra-cellularly{ MODIF_TYPE:ADJ } tag eng_adverb:intracerebrally{ MODIF_TYPE:ADJ } tag eng_adverb:intracervically{ MODIF_TYPE:ADJ } tag eng_adverb:intracolonically{ MODIF_TYPE:ADJ } tag eng_adverb:intracortically{ MODIF_TYPE:ADJ } tag eng_adverb:intracranially{ MODIF_TYPE:ADJ } tag eng_adverb:intraduodenally{ MODIF_TYPE:ADJ } tag eng_adverb:intra-epidermally{ MODIF_TYPE:ADJ } tag eng_adverb:intraepidermally{ MODIF_TYPE:ADJ } tag eng_adverb:intra-epithelially{ MODIF_TYPE:ADJ } tag eng_adverb:intraepithelially{ MODIF_TYPE:ADJ } tag eng_adverb:intrahypothalamically{ MODIF_TYPE:ADJ } tag eng_adverb:intra-individually{ MODIF_TYPE:ADJ } tag eng_adverb:intraindividually{ MODIF_TYPE:ADJ } tag eng_adverb:intrajejunally{ MODIF_TYPE:ADJ } tag eng_adverb:intralesionally{ MODIF_TYPE:ADJ } tag eng_adverb:intraluminally{ MODIF_TYPE:ADJ } tag eng_adverb:intramurally{ MODIF_TYPE:ADJ } tag eng_adverb:intra-muscularly{ MODIF_TYPE:ADJ } tag eng_adverb:intra-operatively{ MODIF_TYPE:ADJ } tag eng_adverb:intraoperatively{ MODIF_TYPE:ADJ } tag eng_adverb:intraorally{ MODIF_TYPE:ADJ } tag eng_adverb:intraportally{ MODIF_TYPE:ADJ } tag eng_adverb:intrarenally{ MODIF_TYPE:ADJ } tag eng_adverb:intrasplenically{ MODIF_TYPE:ADJ } tag eng_adverb:intratracheally{ MODIF_TYPE:ADJ } tag eng_adverb:intratypically{ MODIF_TYPE:ADJ } tag eng_adverb:intra-venously{ MODIF_TYPE:ADJ } tag eng_adverb:intravitally{ MODIF_TYPE:ADJ } tag eng_adverb:intriguingly{ MODIF_TYPE:ADJ } tag eng_adverb:intrusively{ MODIF_TYPE:ADJ } tag eng_adverb:invasively{ MODIF_TYPE:ADJ } tag eng_adverb:invertedly{ MODIF_TYPE:ADJ } tag eng_adverb:in vitro{ MODIF_TYPE:ADJ } tag eng_adverb:in vivo{ MODIF_TYPE:ADJ } tag eng_adverb:iontophoretically{ MODIF_TYPE:ADJ } tag eng_adverb:ipsilaterally{ MODIF_TYPE:ADJ } tag eng_adverb:irrevocably{ MODIF_TYPE:ADJ } tag eng_adverb:ischemically{ MODIF_TYPE:ADJ } tag eng_adverb:isometrically{ MODIF_TYPE:ADJ } tag eng_adverb:isotachophoretically{ MODIF_TYPE:ADJ } tag eng_adverb:isothermally{ MODIF_TYPE:ADJ } tag eng_adverb:isotopically{ MODIF_TYPE:ADJ } tag eng_adverb:isotropically{ MODIF_TYPE:ADJ } tag eng_adverb:iteratively{ MODIF_TYPE:ADJ } tag eng_adverb:karyotypically{ MODIF_TYPE:ADJ } tag eng_adverb:keratoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:kinaesthesiometrically{ MODIF_TYPE:ADJ } tag eng_adverb:kinematically{ MODIF_TYPE:ADJ } tag eng_adverb:kinesimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:kinesthesiometrically{ MODIF_TYPE:ADJ } tag eng_adverb:kinetically{ MODIF_TYPE:ADJ } tag eng_adverb:laminagraphically{ MODIF_TYPE:ADJ } tag eng_adverb:laparoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:laryngostroboscopically{ MODIF_TYPE:ADJ } tag eng_adverb:latently{ MODIF_TYPE:ADJ } tag eng_adverb:legalistically{ MODIF_TYPE:ADJ } tag eng_adverb:lensometrically{ MODIF_TYPE:ADJ } tag eng_adverb:lethally{ MODIF_TYPE:ADJ } tag eng_adverb:likewise{ MODIF_TYPE:ADJ } tag eng_adverb:limitedly{ MODIF_TYPE:ADJ } tag eng_adverb:linguo-apically{ MODIF_TYPE:ADJ } tag eng_adverb:lithometrically{ MODIF_TYPE:ADJ } tag eng_adverb:lithoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:lumboscopically{ MODIF_TYPE:ADJ } tag eng_adverb:luminometrically{ MODIF_TYPE:ADJ } tag eng_adverb:lymphangiographically{ MODIF_TYPE:ADJ } tag eng_adverb:lymphographically{ MODIF_TYPE:ADJ } tag eng_adverb:lymphoscintigraphically{ MODIF_TYPE:ADJ } tag eng_adverb:lytically{ MODIF_TYPE:ADJ } tag eng_adverb:macroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:magnetocardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:magnocellularly{ MODIF_TYPE:ADJ } tag eng_adverb:mammographically{ MODIF_TYPE:ADJ } tag eng_adverb:manipulatively{ MODIF_TYPE:ADJ } tag eng_adverb:mechanographically{ MODIF_TYPE:ADJ } tag eng_adverb:mechanomyographically{ MODIF_TYPE:ADJ } tag eng_adverb:meiotically{ MODIF_TYPE:ADJ } tag eng_adverb:metabolically{ MODIF_TYPE:ADJ } tag eng_adverb:metamorphically{ MODIF_TYPE:ADJ } tag eng_adverb:metastatically{ MODIF_TYPE:ADJ } tag eng_adverb:microanalytically{ MODIF_TYPE:ADJ } tag eng_adverb:microanatomically{ MODIF_TYPE:ADJ } tag eng_adverb:microangiographically{ MODIF_TYPE:ADJ } tag eng_adverb:microbially{ MODIF_TYPE:ADJ } tag eng_adverb:microbiologically{ MODIF_TYPE:ADJ } tag eng_adverb:microcalorimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:microchemically{ MODIF_TYPE:ADJ } tag eng_adverb:microdensitometrically{ MODIF_TYPE:ADJ } tag eng_adverb:microelectrophoretically{ MODIF_TYPE:ADJ } tag eng_adverb:microfluorometrically{ MODIF_TYPE:ADJ } tag eng_adverb:microgasometrically{ MODIF_TYPE:ADJ } tag eng_adverb:microiontophoretically{ MODIF_TYPE:ADJ } tag eng_adverb:microneurographically{ MODIF_TYPE:ADJ } tag eng_adverb:microphotometrically{ MODIF_TYPE:ADJ } tag eng_adverb:microradiographically{ MODIF_TYPE:ADJ } //tag eng_adverb:microspectrofluorometrically{ MODIF_TYPE:ADJ } //tag eng_adverb:microspectrophotometrically{ MODIF_TYPE:ADJ } tag eng_adverb:microsurgically{ MODIF_TYPE:ADJ } tag eng_adverb:midsystolically{ MODIF_TYPE:ADJ } tag eng_adverb:mineralogically{ MODIF_TYPE:ADJ } tag eng_adverb:mirthlessly{ MODIF_TYPE:ADJ } tag eng_adverb:mitochondrially{ MODIF_TYPE:ADJ } tag eng_adverb:mitotically{ MODIF_TYPE:ADJ } tag eng_adverb:molecularly{ MODIF_TYPE:ADJ } tag eng_adverb:monocularly{ MODIF_TYPE:ADJ } tag eng_adverb:monophasically{ MODIF_TYPE:ADJ } tag eng_adverb:monotonically{ MODIF_TYPE:ADJ } tag eng_adverb:morphologically{ MODIF_TYPE:ADJ } tag eng_adverb:morphometrically{ MODIF_TYPE:ADJ } tag eng_adverb:motorically{ MODIF_TYPE:ADJ } tag eng_adverb:muscularly{ MODIF_TYPE:ADJ } tag eng_adverb:mutagenically{ MODIF_TYPE:ADJ } tag eng_adverb:myeloscopically{ MODIF_TYPE:ADJ } tag eng_adverb:nasographically{ MODIF_TYPE:ADJ } tag eng_adverb:nasopharyngoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:nasoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:natally{ MODIF_TYPE:ADJ } tag eng_adverb:natively{ MODIF_TYPE:ADJ } tag eng_adverb:negligibly{ MODIF_TYPE:ADJ } tag eng_adverb:neoplastically{ MODIF_TYPE:ADJ } tag eng_adverb:nephrologically{ MODIF_TYPE:ADJ } tag eng_adverb:nephroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:neurobiologically{ MODIF_TYPE:ADJ } tag eng_adverb:neurochemically{ MODIF_TYPE:ADJ } tag eng_adverb:neurographically{ MODIF_TYPE:ADJ } tag eng_adverb:neurolinguistically{ MODIF_TYPE:ADJ } tag eng_adverb:neuronally{ MODIF_TYPE:ADJ } tag eng_adverb:neuropathologically{ MODIF_TYPE:ADJ } tag eng_adverb:neuropsychologically{ MODIF_TYPE:ADJ } tag eng_adverb:neurovascularly{ MODIF_TYPE:ADJ } tag eng_adverb:noncompetitively{ MODIF_TYPE:ADJ } tag eng_adverb:nonconventionally{ MODIF_TYPE:ADJ } tag eng_adverb:noncovalently{ MODIF_TYPE:ADJ } tag eng_adverb:noncyclically{ MODIF_TYPE:ADJ } tag eng_adverb:nonenzymatically{ MODIF_TYPE:ADJ } tag eng_adverb:nongenetically{ MODIF_TYPE:ADJ } tag eng_adverb:nonhaematologically{ MODIF_TYPE:ADJ } tag eng_adverb:nonhematologically{ MODIF_TYPE:ADJ } tag eng_adverb:nonimmunologically{ MODIF_TYPE:ADJ } tag eng_adverb:non-invasively{ MODIF_TYPE:ADJ } tag eng_adverb:noninvasively{ MODIF_TYPE:ADJ } tag eng_adverb:non-isotopically{ MODIF_TYPE:ADJ } tag eng_adverb:nonisotopically{ MODIF_TYPE:ADJ } tag eng_adverb:nonmetastatically{ MODIF_TYPE:ADJ } tag eng_adverb:nonmetrically{ MODIF_TYPE:ADJ } tag eng_adverb:non-occupationally{ MODIF_TYPE:ADJ } tag eng_adverb:nonoccupationally{ MODIF_TYPE:ADJ } tag eng_adverb:non-operatively{ MODIF_TYPE:ADJ } tag eng_adverb:nonoperatively{ MODIF_TYPE:ADJ } tag eng_adverb:nonosmotically{ MODIF_TYPE:ADJ } tag eng_adverb:non-pharmacologically{ MODIF_TYPE:ADJ } tag eng_adverb:nonpharmacologically{ MODIF_TYPE:ADJ } tag eng_adverb:nonpolymorphically{ MODIF_TYPE:ADJ } tag eng_adverb:nonpsychiatrically{ MODIF_TYPE:ADJ } tag eng_adverb:non-randomly{ MODIF_TYPE:ADJ } tag eng_adverb:nonrandomly{ MODIF_TYPE:ADJ } tag eng_adverb:non-sexually{ MODIF_TYPE:ADJ } tag eng_adverb:nonsexually{ MODIF_TYPE:ADJ } tag eng_adverb:nonsignificantly{ MODIF_TYPE:ADJ } tag eng_adverb:non-simultaneously{ MODIF_TYPE:ADJ } tag eng_adverb:nonsurgically{ MODIF_TYPE:ADJ } tag eng_adverb:nosographically{ MODIF_TYPE:ADJ } tag eng_adverb:nuclearly{ MODIF_TYPE:ADJ } tag eng_adverb:nystagmographically{ MODIF_TYPE:ADJ } tag eng_adverb:obligatorily{ MODIF_TYPE:ADJ } tag eng_adverb:observerscopically{ MODIF_TYPE:ADJ } tag eng_adverb:occcasionally{ MODIF_TYPE:ADJ } tag eng_adverb:occupationally{ MODIF_TYPE:ADJ } tag eng_adverb:octahedrally{ MODIF_TYPE:ADJ } tag eng_adverb:oculographically{ MODIF_TYPE:ADJ } tag eng_adverb:oculoplethysmographically{ MODIF_TYPE:ADJ } tag eng_adverb:odynometrically{ MODIF_TYPE:ADJ } tag eng_adverb:oft{ MODIF_TYPE:ADJ } tag eng_adverb:olfactometrically{ MODIF_TYPE:ADJ } tag eng_adverb:omnicardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:omni nocte{ MODIF_TYPE:ADJ } tag eng_adverb:oncometrically{ MODIF_TYPE:ADJ } tag eng_adverb:one-sidedly{ MODIF_TYPE:ADJ } tag eng_adverb:operationally{ MODIF_TYPE:ADJ } tag eng_adverb:operatively{ MODIF_TYPE:ADJ } //tag eng_adverb:ophthalmodiaphanoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:ophthalmodiastimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:ophthalmodynamometrically{ MODIF_TYPE:ADJ } tag eng_adverb:ophthalmofunduscopically{ MODIF_TYPE:ADJ } tag eng_adverb:ophthalmographically{ MODIF_TYPE:ADJ } tag eng_adverb:ophthalmoleucoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:ophthalmoleukoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:ophthalmometrically{ MODIF_TYPE:ADJ } tag eng_adverb:ophthalmometroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:ophthalmotonometrically{ MODIF_TYPE:ADJ } tag eng_adverb:ophthalmotropometrically{ MODIF_TYPE:ADJ } tag eng_adverb:oppositely{ MODIF_TYPE:ADJ } tag eng_adverb:optoelectronically{ MODIF_TYPE:ADJ } tag eng_adverb:optometrically{ MODIF_TYPE:ADJ } tag eng_adverb:optomyometrically{ MODIF_TYPE:ADJ } tag eng_adverb:orchidometrically{ MODIF_TYPE:ADJ } tag eng_adverb:ordinately{ MODIF_TYPE:ADJ } tag eng_adverb:organismically{ MODIF_TYPE:ADJ } tag eng_adverb:orogastrically{ MODIF_TYPE:ADJ } tag eng_adverb:orthotopically{ MODIF_TYPE:ADJ } tag eng_adverb:oscillographically{ MODIF_TYPE:ADJ } tag eng_adverb:oscillometrically{ MODIF_TYPE:ADJ } tag eng_adverb:oscillotonometrically{ MODIF_TYPE:ADJ } tag eng_adverb:osmometrically{ MODIF_TYPE:ADJ } tag eng_adverb:osmoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:osmotically{ MODIF_TYPE:ADJ } tag eng_adverb:osteosynthetically{ MODIF_TYPE:ADJ } tag eng_adverb:otoacoustically{ MODIF_TYPE:ADJ } tag eng_adverb:otomicroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:otoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:out of doors{ MODIF_TYPE:ADJ } tag eng_adverb:over-ridingly{ MODIF_TYPE:ADJ } tag eng_adverb:oxidatively{ MODIF_TYPE:ADJ } tag eng_adverb:pachymetrically{ MODIF_TYPE:ADJ } tag eng_adverb:panendoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:pantographically{ MODIF_TYPE:ADJ } tag eng_adverb:para-arterially{ MODIF_TYPE:ADJ } tag eng_adverb:paraarterially{ MODIF_TYPE:ADJ } tag eng_adverb:paracentrically{ MODIF_TYPE:ADJ } tag eng_adverb:paradigmatically{ MODIF_TYPE:ADJ } tag eng_adverb:paramagnetically{ MODIF_TYPE:ADJ } tag eng_adverb:parasitologically{ MODIF_TYPE:ADJ } tag eng_adverb:parasystolically{ MODIF_TYPE:ADJ } tag eng_adverb:parenterally{ MODIF_TYPE:ADJ } tag eng_adverb:pari passu{ MODIF_TYPE:ADJ } tag eng_adverb:parthenogenetically{ MODIF_TYPE:ADJ } tag eng_adverb:parturiometrically{ MODIF_TYPE:ADJ } tag eng_adverb:pathomorphologically{ MODIF_TYPE:ADJ } tag eng_adverb:pelvimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:pelviscopically{ MODIF_TYPE:ADJ } tag eng_adverb:penetrometrically{ MODIF_TYPE:ADJ } tag eng_adverb:pentagonally{ MODIF_TYPE:ADJ } tag eng_adverb:peranally{ MODIF_TYPE:ADJ } tag eng_adverb:per annum{ MODIF_TYPE:ADJ } tag eng_adverb:per anum{ MODIF_TYPE:ADJ } tag eng_adverb:per cent{ MODIF_TYPE:ADJ } tag eng_adverb:per contiguum{ MODIF_TYPE:ADJ } tag eng_adverb:per continuum{ MODIF_TYPE:ADJ } tag eng_adverb:percutaneously{ MODIF_TYPE:ADJ } tag eng_adverb:per cutem{ MODIF_TYPE:ADJ } tag eng_adverb:perforce{ MODIF_TYPE:ADJ } tag eng_adverb:perinatally{ MODIF_TYPE:ADJ } tag eng_adverb:periodontally{ MODIF_TYPE:ADJ } tag eng_adverb:perioperatively{ MODIF_TYPE:ADJ } tag eng_adverb:periplasmically{ MODIF_TYPE:ADJ } tag eng_adverb:peritoneally{ MODIF_TYPE:ADJ } tag eng_adverb:peritoneoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:peritrichously{ MODIF_TYPE:ADJ } tag eng_adverb:perorally{ MODIF_TYPE:ADJ } tag eng_adverb:per os{ MODIF_TYPE:ADJ } tag eng_adverb:per primam{ MODIF_TYPE:ADJ } tag eng_adverb:per primam intentionem{ MODIF_TYPE:ADJ } tag eng_adverb:per rectum{ MODIF_TYPE:ADJ } tag eng_adverb:per saltum{ MODIF_TYPE:ADJ } tag eng_adverb:per se{ MODIF_TYPE:ADJ } tag eng_adverb:per secundam{ MODIF_TYPE:ADJ } tag eng_adverb:per secundam intentionem{ MODIF_TYPE:ADJ } tag eng_adverb:per tertiam{ MODIF_TYPE:ADJ } tag eng_adverb:pertinently{ MODIF_TYPE:ADJ } tag eng_adverb:per tubam{ MODIF_TYPE:ADJ } tag eng_adverb:per vaginam{ MODIF_TYPE:ADJ } tag eng_adverb:per vias naturales{ MODIF_TYPE:ADJ } tag eng_adverb:petechiometrically{ MODIF_TYPE:ADJ } tag eng_adverb:phaneroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:pharmaceutically{ MODIF_TYPE:ADJ } tag eng_adverb:pharyngoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:phenotypically{ MODIF_TYPE:ADJ } tag eng_adverb:phoniatrically{ MODIF_TYPE:ADJ } tag eng_adverb:phonostethographically{ MODIF_TYPE:ADJ } tag eng_adverb:phorometrically{ MODIF_TYPE:ADJ } tag eng_adverb:photoacoustically{ MODIF_TYPE:ADJ } tag eng_adverb:photochemically{ MODIF_TYPE:ADJ } tag eng_adverb:photofluorometrically{ MODIF_TYPE:ADJ } tag eng_adverb:photofluoroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:photomicrographically{ MODIF_TYPE:ADJ } tag eng_adverb:photoplethysmographically{ MODIF_TYPE:ADJ } tag eng_adverb:phototachometrically{ MODIF_TYPE:ADJ } tag eng_adverb:phototactically{ MODIF_TYPE:ADJ } tag eng_adverb:phototrophically{ MODIF_TYPE:ADJ } tag eng_adverb:phylogenetically{ MODIF_TYPE:ADJ } tag eng_adverb:physiologically{ MODIF_TYPE:ADJ } tag eng_adverb:physiotherapeutically{ MODIF_TYPE:ADJ } tag eng_adverb:piezoelectrically{ MODIF_TYPE:ADJ } tag eng_adverb:placentally{ MODIF_TYPE:ADJ } tag eng_adverb:planigraphically{ MODIF_TYPE:ADJ } tag eng_adverb:planimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:plethysmographically{ MODIF_TYPE:ADJ } tag eng_adverb:pluralistically{ MODIF_TYPE:ADJ } tag eng_adverb:pneumatographically{ MODIF_TYPE:ADJ } tag eng_adverb:pneumotachographically{ MODIF_TYPE:ADJ } tag eng_adverb:polycardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:polyclonally{ MODIF_TYPE:ADJ } tag eng_adverb:polygraphically{ MODIF_TYPE:ADJ } tag eng_adverb:polysomnographically{ MODIF_TYPE:ADJ } tag eng_adverb:polyspermically{ MODIF_TYPE:ADJ } tag eng_adverb:post-catheterisation{ MODIF_TYPE:ADJ } tag eng_adverb:postcatheterisation{ MODIF_TYPE:ADJ } tag eng_adverb:post cibos{ MODIF_TYPE:ADJ } tag eng_adverb:posteroanteriorly{ MODIF_TYPE:ADJ } tag eng_adverb:postischaemically{ MODIF_TYPE:ADJ } tag eng_adverb:postischemically{ MODIF_TYPE:ADJ } tag eng_adverb:postmetamorphically{ MODIF_TYPE:ADJ } tag eng_adverb:post mortem{ MODIF_TYPE:ADJ } tag eng_adverb:postnatally{ MODIF_TYPE:ADJ } tag eng_adverb:post operatively{ MODIF_TYPE:ADJ } tag eng_adverb:post-operatively{ MODIF_TYPE:ADJ } tag eng_adverb:post partum{ MODIF_TYPE:ADJ } tag eng_adverb:postprandially{ MODIF_TYPE:ADJ } //tag eng_adverb:post singulas sedes liquidas{ MODIF_TYPE:ADJ } tag eng_adverb:postthrombotically{ MODIF_TYPE:ADJ } tag eng_adverb:posttranscriptionally{ MODIF_TYPE:ADJ } tag eng_adverb:post-translationally{ MODIF_TYPE:ADJ } tag eng_adverb:posttranslationally{ MODIF_TYPE:ADJ } tag eng_adverb:potentiometrically{ MODIF_TYPE:ADJ } //tag eng_adverb:pow{ MODIF_TYPE:ADJ } tag eng_adverb:pre-attentively{ MODIF_TYPE:ADJ } tag eng_adverb:preattentively{ MODIF_TYPE:ADJ } tag eng_adverb:precociously{ MODIF_TYPE:ADJ } tag eng_adverb:preconceptionally{ MODIF_TYPE:ADJ } tag eng_adverb:predominately{ MODIF_TYPE:ADJ } tag eng_adverb:preferentially{ MODIF_TYPE:ADJ } tag eng_adverb:preliminarily{ MODIF_TYPE:ADJ } tag eng_adverb:premenopausally{ MODIF_TYPE:ADJ } tag eng_adverb:prenatally{ MODIF_TYPE:ADJ } tag eng_adverb:pre-operatively{ MODIF_TYPE:ADJ } tag eng_adverb:presumptively{ MODIF_TYPE:ADJ } tag eng_adverb:prethymically{ MODIF_TYPE:ADJ } tag eng_adverb:prevalently{ MODIF_TYPE:ADJ } tag eng_adverb:proctosigmoidoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:prolately{ MODIF_TYPE:ADJ } tag eng_adverb:prophylactically{ MODIF_TYPE:ADJ } tag eng_adverb:pro rata{ MODIF_TYPE:ADJ } tag eng_adverb:pro re nata{ MODIF_TYPE:ADJ } tag eng_adverb:prospectively{ MODIF_TYPE:ADJ } tag eng_adverb:proteolytically{ MODIF_TYPE:ADJ } tag eng_adverb:prototypically{ MODIF_TYPE:ADJ } tag eng_adverb:psychiatrically{ MODIF_TYPE:ADJ } tag eng_adverb:psychoanalytically{ MODIF_TYPE:ADJ } tag eng_adverb:psychometrically{ MODIF_TYPE:ADJ } tag eng_adverb:psychotically{ MODIF_TYPE:ADJ } tag eng_adverb:pulselessly{ MODIF_TYPE:ADJ } tag eng_adverb:pupillographically{ MODIF_TYPE:ADJ } tag eng_adverb:pupillometrically{ MODIF_TYPE:ADJ } tag eng_adverb:pyeloscopically{ MODIF_TYPE:ADJ } tag eng_adverb:pyrolytically{ MODIF_TYPE:ADJ } tag eng_adverb:pyrometrically{ MODIF_TYPE:ADJ } tag eng_adverb:pyroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:quaque nocte{ MODIF_TYPE:ADJ } tag eng_adverb:radiatively{ MODIF_TYPE:ADJ } tag eng_adverb:radioactively{ MODIF_TYPE:ADJ } tag eng_adverb:radiobiologically{ MODIF_TYPE:ADJ } tag eng_adverb:radiocardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:radiochemically{ MODIF_TYPE:ADJ } tag eng_adverb:radiochromatographically{ MODIF_TYPE:ADJ } tag eng_adverb:radioenzymatically{ MODIF_TYPE:ADJ } tag eng_adverb:radiogenically{ MODIF_TYPE:ADJ } tag eng_adverb:radiographically{ MODIF_TYPE:ADJ } tag eng_adverb:radioimmunologically{ MODIF_TYPE:ADJ } tag eng_adverb:radiologically{ MODIF_TYPE:ADJ } tag eng_adverb:radiolytically{ MODIF_TYPE:ADJ } tag eng_adverb:radiotelemetrically{ MODIF_TYPE:ADJ } tag eng_adverb:rakishly{ MODIF_TYPE:ADJ } tag eng_adverb:reactively{ MODIF_TYPE:ADJ } tag eng_adverb:recessively{ MODIF_TYPE:ADJ } tag eng_adverb:reciprocally{ MODIF_TYPE:ADJ } tag eng_adverb:rectally{ MODIF_TYPE:ADJ } tag eng_adverb:reflexively{ MODIF_TYPE:ADJ } tag eng_adverb:regardless{ MODIF_TYPE:ADJ } tag eng_adverb:renographically{ MODIF_TYPE:ADJ } tag eng_adverb:reproducibly{ MODIF_TYPE:ADJ } tag eng_adverb:resectoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:retinoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:retrogradely{ MODIF_TYPE:ADJ } tag eng_adverb:retrovirally{ MODIF_TYPE:ADJ } tag eng_adverb:revengefully{ MODIF_TYPE:ADJ } tag eng_adverb:reversely{ MODIF_TYPE:ADJ } tag eng_adverb:rheologically{ MODIF_TYPE:ADJ } tag eng_adverb:rheumatologically{ MODIF_TYPE:ADJ } tag eng_adverb:rhinoanemometrically{ MODIF_TYPE:ADJ } tag eng_adverb:rhinomanometrically{ MODIF_TYPE:ADJ } tag eng_adverb:ritardando{ MODIF_TYPE:ADJ } tag eng_adverb:roentgenographically{ MODIF_TYPE:ADJ } tag eng_adverb:rostrally{ MODIF_TYPE:ADJ } tag eng_adverb:rostrocaudally{ MODIF_TYPE:ADJ } tag eng_adverb:rotametrically{ MODIF_TYPE:ADJ } tag eng_adverb:rotationally{ MODIF_TYPE:ADJ } tag eng_adverb:ruminally{ MODIF_TYPE:ADJ } tag eng_adverb:saprophytically{ MODIF_TYPE:ADJ } tag eng_adverb:satisfyingly{ MODIF_TYPE:ADJ } tag eng_adverb:scandalously{ MODIF_TYPE:ADJ } tag eng_adverb:scintigraphically{ MODIF_TYPE:ADJ } tag eng_adverb:secundum artem{ MODIF_TYPE:ADJ } tag eng_adverb:secundum naturam{ MODIF_TYPE:ADJ } tag eng_adverb:sedimentometrically{ MODIF_TYPE:ADJ } tag eng_adverb:segmentally{ MODIF_TYPE:ADJ } tag eng_adverb:semiautomatically{ MODIF_TYPE:ADJ } tag eng_adverb:semiologically{ MODIF_TYPE:ADJ } tag eng_adverb:semi-quantitatively{ MODIF_TYPE:ADJ } tag eng_adverb:semiquantitatively{ MODIF_TYPE:ADJ } tag eng_adverb:semispecifically{ MODIF_TYPE:ADJ } tag eng_adverb:serendipitously{ MODIF_TYPE:ADJ } tag eng_adverb:serologically{ MODIF_TYPE:ADJ } tag eng_adverb:serospecifically{ MODIF_TYPE:ADJ } tag eng_adverb:shoddily{ MODIF_TYPE:ADJ } tag eng_adverb:sialographically{ MODIF_TYPE:ADJ } tag eng_adverb:siderose{ MODIF_TYPE:ADJ } tag eng_adverb:sigmoidally{ MODIF_TYPE:ADJ } tag eng_adverb:sigmoidoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:simplistically{ MODIF_TYPE:ADJ } tag eng_adverb:sinusoidally{ MODIF_TYPE:ADJ } tag eng_adverb:skeletally{ MODIF_TYPE:ADJ } tag eng_adverb:sketchily{ MODIF_TYPE:ADJ } tag eng_adverb:skiascopically{ MODIF_TYPE:ADJ } tag eng_adverb:sociodemographically{ MODIF_TYPE:ADJ } tag eng_adverb:sociometrically{ MODIF_TYPE:ADJ } tag eng_adverb:somatically{ MODIF_TYPE:ADJ } tag eng_adverb:some day{ MODIF_TYPE:ADJ } tag eng_adverb:sonographically{ MODIF_TYPE:ADJ } tag eng_adverb:soundlessly{ MODIF_TYPE:ADJ } tag eng_adverb:spatiotemporally{ MODIF_TYPE:ADJ } tag eng_adverb:spectrally{ MODIF_TYPE:ADJ } tag eng_adverb:spectrofluorimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:spectrographically{ MODIF_TYPE:ADJ } tag eng_adverb:spectrophotometrically{ MODIF_TYPE:ADJ } tag eng_adverb:spectroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:speculatively{ MODIF_TYPE:ADJ } tag eng_adverb:spheroidally{ MODIF_TYPE:ADJ } tag eng_adverb:sphincteroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:sphygmocardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:spinally{ MODIF_TYPE:ADJ } tag eng_adverb:spinelessly{ MODIF_TYPE:ADJ } tag eng_adverb:spiritlessly{ MODIF_TYPE:ADJ } tag eng_adverb:spirographically{ MODIF_TYPE:ADJ } tag eng_adverb:stably{ MODIF_TYPE:ADJ } tag eng_adverb:stereologically{ MODIF_TYPE:ADJ } tag eng_adverb:stereometrically{ MODIF_TYPE:ADJ } tag eng_adverb:stereomicroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:stereophotogrammetrically{ MODIF_TYPE:ADJ } tag eng_adverb:stereospecifically{ MODIF_TYPE:ADJ } tag eng_adverb:stereotactically{ MODIF_TYPE:ADJ } tag eng_adverb:stereotaxically{ MODIF_TYPE:ADJ } tag eng_adverb:sterically{ MODIF_TYPE:ADJ } tag eng_adverb:stertorously{ MODIF_TYPE:ADJ } tag eng_adverb:stethographically{ MODIF_TYPE:ADJ } tag eng_adverb:stoichiometrically{ MODIF_TYPE:ADJ } tag eng_adverb:stolidly{ MODIF_TYPE:ADJ } tag eng_adverb:subchronically{ MODIF_TYPE:ADJ } tag eng_adverb:subepithelially{ MODIF_TYPE:ADJ } tag eng_adverb:sublethally{ MODIF_TYPE:ADJ } tag eng_adverb:sublingually{ MODIF_TYPE:ADJ } tag eng_adverb:submaximally{ MODIF_TYPE:ADJ } tag eng_adverb:suboptimally{ MODIF_TYPE:ADJ } tag eng_adverb:subperiodically{ MODIF_TYPE:ADJ } tag eng_adverb:subserosally{ MODIF_TYPE:ADJ } tag eng_adverb:subtotally{ MODIF_TYPE:ADJ } tag eng_adverb:sudorimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:sulkily{ MODIF_TYPE:ADJ } tag eng_adverb:superparamagnetically{ MODIF_TYPE:ADJ } tag eng_adverb:supportively{ MODIF_TYPE:ADJ } tag eng_adverb:supranormally{ MODIF_TYPE:ADJ } tag eng_adverb:supraphysiologically{ MODIF_TYPE:ADJ } tag eng_adverb:supratubercular{ MODIF_TYPE:ADJ } tag eng_adverb:symptomatically{ MODIF_TYPE:ADJ } tag eng_adverb:synaptically{ MODIF_TYPE:ADJ } tag eng_adverb:synchronously{ MODIF_TYPE:ADJ } tag eng_adverb:synergistically{ MODIF_TYPE:ADJ } tag eng_adverb:systemically{ MODIF_TYPE:ADJ } tag eng_adverb:tachometrically{ MODIF_TYPE:ADJ } tag eng_adverb:tandemly{ MODIF_TYPE:ADJ } tag eng_adverb:td{ MODIF_TYPE:ADJ } tag eng_adverb:tearlessly{ MODIF_TYPE:ADJ } tag eng_adverb:telediastolically{ MODIF_TYPE:ADJ } tag eng_adverb:telemetrically{ MODIF_TYPE:ADJ } tag eng_adverb:telephonically{ MODIF_TYPE:ADJ } tag eng_adverb:telethermometrically{ MODIF_TYPE:ADJ } tag eng_adverb:temporally{ MODIF_TYPE:ADJ } tag eng_adverb:tendentiously{ MODIF_TYPE:ADJ } tag eng_adverb:ter dia{ MODIF_TYPE:ADJ } tag eng_adverb:tetanically{ MODIF_TYPE:ADJ } tag eng_adverb:tetragonally{ MODIF_TYPE:ADJ } tag eng_adverb:tetrahedrally{ MODIF_TYPE:ADJ } tag eng_adverb:thalamically{ MODIF_TYPE:ADJ } tag eng_adverb:thematically{ MODIF_TYPE:ADJ } tag eng_adverb:thence{ MODIF_TYPE:ADJ } tag eng_adverb:thereof{ MODIF_TYPE:ADJ } tag eng_adverb:therewith{ MODIF_TYPE:ADJ } tag eng_adverb:thermodynamically{ MODIF_TYPE:ADJ } tag eng_adverb:thermographically{ MODIF_TYPE:ADJ } tag eng_adverb:thermometrically{ MODIF_TYPE:ADJ } tag eng_adverb:thermostatically{ MODIF_TYPE:ADJ } tag eng_adverb:thioyltically{ MODIF_TYPE:ADJ } tag eng_adverb:thoracoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:thrice{ MODIF_TYPE:ADJ } tag eng_adverb:thromboelastographically{ MODIF_TYPE:ADJ } tag eng_adverb:thrombometrically{ MODIF_TYPE:ADJ } tag eng_adverb:tid{ MODIF_TYPE:ADJ } tag eng_adverb:tocodynamometrically{ MODIF_TYPE:ADJ } tag eng_adverb:tomodensitometrically{ MODIF_TYPE:ADJ } tag eng_adverb:tomographically{ MODIF_TYPE:ADJ } tag eng_adverb:tonally{ MODIF_TYPE:ADJ } tag eng_adverb:tonically{ MODIF_TYPE:ADJ } tag eng_adverb:tonographically{ MODIF_TYPE:ADJ } tag eng_adverb:tonometrically{ MODIF_TYPE:ADJ } tag eng_adverb:tonoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:topologically{ MODIF_TYPE:ADJ } tag eng_adverb:tracheally{ MODIF_TYPE:ADJ } tag eng_adverb:transcardially{ MODIF_TYPE:ADJ } tag eng_adverb:transcranially{ MODIF_TYPE:ADJ } tag eng_adverb:transcriptionally{ MODIF_TYPE:ADJ } tag eng_adverb:transcrotally{ MODIF_TYPE:ADJ } tag eng_adverb:transiently{ MODIF_TYPE:ADJ } tag eng_adverb:translaryngeally{ MODIF_TYPE:ADJ } tag eng_adverb:transmurally{ MODIF_TYPE:ADJ } tag eng_adverb:transovumly{ MODIF_TYPE:ADJ } tag eng_adverb:transplacentally{ MODIF_TYPE:ADJ } tag eng_adverb:transpylorically{ MODIF_TYPE:ADJ } tag eng_adverb:transrectally{ MODIF_TYPE:ADJ } tag eng_adverb:transstadially{ MODIF_TYPE:ADJ } tag eng_adverb:transtadially{ MODIF_TYPE:ADJ } tag eng_adverb:transtelephonically{ MODIF_TYPE:ADJ } tag eng_adverb:transvaginally{ MODIF_TYPE:ADJ } tag eng_adverb:transvenously{ MODIF_TYPE:ADJ } tag eng_adverb:traumatically{ MODIF_TYPE:ADJ } tag eng_adverb:traumatologically{ MODIF_TYPE:ADJ } tag eng_adverb:tremographically{ MODIF_TYPE:ADJ } tag eng_adverb:triadically{ MODIF_TYPE:ADJ } tag eng_adverb:tropometrically{ MODIF_TYPE:ADJ } tag eng_adverb:troposcopically{ MODIF_TYPE:ADJ } tag eng_adverb:typoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:ubiquitously{ MODIF_TYPE:ADJ } tag eng_adverb:ultrasonically{ MODIF_TYPE:ADJ } tag eng_adverb:ultrasonographically{ MODIF_TYPE:ADJ } tag eng_adverb:ultrastructurally{ MODIF_TYPE:ADJ } tag eng_adverb:unaggressively{ MODIF_TYPE:ADJ } tag eng_adverb:unclearly{ MODIF_TYPE:ADJ } tag eng_adverb:uncompetitively{ MODIF_TYPE:ADJ } tag eng_adverb:uniparentally{ MODIF_TYPE:ADJ } tag eng_adverb:univalently{ MODIF_TYPE:ADJ } tag eng_adverb:univariately{ MODIF_TYPE:ADJ } tag eng_adverb:unnaturally{ MODIF_TYPE:ADJ } tag eng_adverb:unphysiologically{ MODIF_TYPE:ADJ } tag eng_adverb:unpredictably{ MODIF_TYPE:ADJ } tag eng_adverb:unproblematically{ MODIF_TYPE:ADJ } tag eng_adverb:unrealistically{ MODIF_TYPE:ADJ } tag eng_adverb:unsympathetically{ MODIF_TYPE:ADJ } tag eng_adverb:unsystematically{ MODIF_TYPE:ADJ } tag eng_adverb:upside down{ MODIF_TYPE:ADJ } tag eng_adverb:ureterorenoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:ureteroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:urethrographically{ MODIF_TYPE:ADJ } tag eng_adverb:urethrometrically{ MODIF_TYPE:ADJ } tag eng_adverb:urinometrically{ MODIF_TYPE:ADJ } tag eng_adverb:urodynamically{ MODIF_TYPE:ADJ } tag eng_adverb:uroflowmetrically{ MODIF_TYPE:ADJ } tag eng_adverb:usefully{ MODIF_TYPE:ADJ } tag eng_adverb:vagally{ MODIF_TYPE:ADJ } tag eng_adverb:vaginally{ MODIF_TYPE:ADJ } tag eng_adverb:vaginometrically{ MODIF_TYPE:ADJ } tag eng_adverb:vaginoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:validly{ MODIF_TYPE:ADJ } tag eng_adverb:variably{ MODIF_TYPE:ADJ } tag eng_adverb:vascularly{ MODIF_TYPE:ADJ } tag eng_adverb:vectorcardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:vectorially{ MODIF_TYPE:ADJ } tag eng_adverb:velocimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:venographically{ MODIF_TYPE:ADJ } tag eng_adverb:ventriculographically{ MODIF_TYPE:ADJ } tag eng_adverb:ventriculo-peritoneally{ MODIF_TYPE:ADJ } tag eng_adverb:ventriculoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:vibrometrically{ MODIF_TYPE:ADJ } //tag eng_adverb:vibrophonocardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:vice versa{ MODIF_TYPE:ADJ } tag eng_adverb:videodensitometrically{ MODIF_TYPE:ADJ } tag eng_adverb:videomicroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:vilely{ MODIF_TYPE:ADJ } tag eng_adverb:virally{ MODIF_TYPE:ADJ } tag eng_adverb:viscometrically{ MODIF_TYPE:ADJ } tag eng_adverb:visuometrically{ MODIF_TYPE:ADJ } tag eng_adverb:vitreally{ MODIF_TYPE:ADJ } tag eng_adverb:voltammetrically{ MODIF_TYPE:ADJ } tag eng_adverb:volubly{ MODIF_TYPE:ADJ } tag eng_adverb:voluptuously{ MODIF_TYPE:ADJ } tag eng_adverb:wastefully{ MODIF_TYPE:ADJ } tag eng_adverb:willfully{ MODIF_TYPE:ADJ } tag eng_adverb:wrathfully{ MODIF_TYPE:ADJ } tag eng_adverb:xenically{ MODIF_TYPE:ADJ } tag eng_adverb:xeromammographically{ MODIF_TYPE:ADJ } tag eng_adverb:xeroradiographically{ MODIF_TYPE:ADJ } tag eng_adverb:zygotically{ MODIF_TYPE:ADJ } tag eng_adverb:zymographically{ MODIF_TYPE:ADJ } tag eng_adverb:just{ MODIF_TYPE:ADJ } tag eng_adverb:almost{ MODIF_TYPE:ADJ } tag eng_adverb:always{ MODIF_TYPE:ADJ } tag eng_adverb:nearly{ MODIF_TYPE:ADJ } // Quarter Horses come in nearly all colors. tag eng_adverb:wide{ MODIF_TYPE:ADJ } // He was wide awake tag eng_adverb:wincingly{ MODIF_TYPE:ADJ } // The speech was wincingly bad tag eng_adverb:startlingly{ MODIF_TYPE:ADJ } // a startlingly modern voice tag eng_adverb:signally{ MODIF_TYPE:ADJ } // signally inappropriate methods tag eng_adverb:shaggily{ MODIF_TYPE:ADJ } // shaggily unkempt mane tag eng_adverb:ruinously{ MODIF_TYPE:ADJ } // ruinously high wages tag eng_adverb:racily{ MODIF_TYPE:ADJ } // racily vernacular language tag eng_adverb:palely{ MODIF_TYPE:ADJ } // a palely entertaining show tag eng_adverb:farcically{ MODIF_TYPE:ADJ } // a farcically inept bungler tag eng_adverb:excusably{ MODIF_TYPE:ADJ } // He was excusably late. tag eng_adverb:only{ MODIF_TYPE:ADJ } #endregion MODIF_TYPE:ADJ #region MODIF_TYPE:VERB tag eng_adverb:weekly{ MODIF_TYPE:VERB } // She visited her aunt weekly. tag eng_adverb:Professionally{ MODIF_TYPE:VERB } // Professionally trained staff tag eng_adverb:greatly{ MODIF_TYPE:VERB } // Feedback is greatly appreciated! tag eng_adverb:then{ MODIF_TYPE:VERB } // He was then imprisoned tag eng_adverb:early{ MODIF_TYPE:VERB } // The sun sets early these days. tag eng_adverb:now{ MODIF_TYPE:VERB } // The brand is now owned by Unilever. tag eng_adverb:late{ MODIF_TYPE:VERB } // As usual, she arrived late. tag eng_adverb:initially{ MODIF_TYPE:VERB } // Selection was initially limited to military pilots. tag eng_adverb:automatically{ MODIF_TYPE:VERB } // This machine automatically cycles. tag eng_adverb:barely{ MODIF_TYPE:VERB } // We barely made the plane. tag eng_adverb:reluctantly{ MODIF_TYPE:VERB } // I gave in and reluctantly mounted the narrow stairs. tag eng_adverb:gradually{ MODIF_TYPE:VERB } // The liquid gradually settled. tag eng_adverb:unblushingly{ MODIF_TYPE:VERB } // His principal opponent unblushingly declared victory before the ballots had been counted. tag eng_adverb:suddenly{ MODIF_TYPE:VERB } // The ship suddenly lurched to the left. tag eng_adverb:just{ MODIF_TYPE:VERB } // He just adored his wife. tag eng_adverb:also{ MODIF_TYPE:VERB } // Inflows of gas into a galaxy also fuel the formation of new stars. tag eng_adverb:seldom{ MODIF_TYPE:VERB } // He seldom suppressed his autobiographical tendencies. tag eng_adverb:slowly{ MODIF_TYPE:VERB } // The reality of his situation slowly dawned on him. tag eng_adverb:slow{ MODIF_TYPE:VERB } tag eng_adverb:fast{ MODIF_TYPE:VERB } // He matured fast. tag eng_adverb:often{ MODIF_TYPE:VERB } // Her husband often abuses alcohol. tag eng_adverb:here{ MODIF_TYPE:VERB } // The perfect climate here develops the grain. tag eng_adverb:immediately{ MODIF_TYPE:VERB } // This immediately concerns your future. tag eng_adverb:implicitly{ MODIF_TYPE:VERB } // I implicitly trust him. tag eng_adverb:strongly{ MODIF_TYPE:VERB } // Mongolian syntax strongly resembles Korean syntax tag eng_adverb:no longer{ MODIF_TYPE:VERB } // Technically, the term is no longer used by experts. tag eng_adverb:flagrantly{ MODIF_TYPE:VERB } // He is flagrantly disregarding the law. tag eng_adverb:kindly{ MODIF_TYPE:VERB } // She kindly overlooked the mistake. tag eng_adverb:pointedly{ MODIF_TYPE:VERB } // He pointedly ignored the question. tag eng_adverb:callously{ MODIF_TYPE:VERB } // He callously exploited their feelings. tag eng_adverb:pompously{ MODIF_TYPE:VERB } // He pompously described his achievements. tag eng_adverb:unerringly{ MODIF_TYPE:VERB } // He unerringly fixed things for us. tag eng_adverb:voluntarily{ MODIF_TYPE:VERB } // He voluntarily submitted to the fingerprinting. tag eng_adverb:cheerfully{ MODIF_TYPE:VERB } // He cheerfully agreed to do it. tag eng_adverb:tenuously{ MODIF_TYPE:VERB } // His works tenuously survive in the minds of a few scholars. tag eng_adverb:angrily{ MODIF_TYPE:VERB } // He angrily denied the accusation. tag eng_adverb:habitually{ MODIF_TYPE:VERB } // He habitually keeps his office door closed. tag eng_adverb:mistakenly{ MODIF_TYPE:VERB } // He mistakenly believed it. tag eng_adverb:universally{ MODIF_TYPE:VERB } // People universally agree on this. tag eng_adverb:considerately{ MODIF_TYPE:VERB } // They considerately withdrew. tag eng_adverb:adamantly{ MODIF_TYPE:VERB } // She adamantly opposed to the marriage. tag eng_adverb:patiently{ MODIF_TYPE:VERB } // He patiently played with the child. tag eng_adverb:actually{ MODIF_TYPE:VERB } // She actually spoke Latin. tag eng_adverb:systematically{ MODIF_TYPE:VERB } // They systematically excluded women. tag eng_adverb:virtually{ MODIF_TYPE:VERB } // The strike virtually paralyzed the city. tag eng_adverb:humbly{ MODIF_TYPE:VERB } // He humbly lowered his head. tag eng_adverb:promptly{ MODIF_TYPE:VERB } // He promptly forgot the address. tag eng_adverb:openly{ MODIF_TYPE:VERB } // He openly flaunted his affection for his sister. tag eng_adverb:unanimously{ MODIF_TYPE:VERB } // The Senate unanimously approved the bill. tag eng_adverb:firmly{ MODIF_TYPE:VERB } // We firmly believed it. tag eng_adverb:rarely{ MODIF_TYPE:VERB } // We rarely met. tag eng_adverb:flatly{ MODIF_TYPE:VERB } // He flatly denied the charges. tag eng_adverb:deftly{ MODIF_TYPE:VERB } // Lois deftly removed her scarf. tag eng_adverb:gallantly{ MODIF_TYPE:VERB } // He gallantly offered to take her home. tag eng_adverb:bureaucratically{ MODIF_TYPE:VERB } // His bureaucratically petty behavior annoyed her. tag eng_adverb:still{ MODIF_TYPE:VERB } // The old man still walks erectly. tag eng_adverb:only{ MODIF_TYPE:VERB } // This event only deepened my convictions. tag eng_adverb:finally{ MODIF_TYPE:VERB } // The pain finally remitted. tag eng_adverb:emulously{ MODIF_TYPE:VERB } // She emulously tried to outdo her older sister. tag eng_adverb:prophetically{ MODIF_TYPE:VERB } // He prophetically anticipated the disaster. tag eng_adverb:instinctively{ MODIF_TYPE:VERB } // He instinctively grabbed the knife. tag eng_adverb:light-heartedly{ MODIF_TYPE:VERB } // He light-heartedly overlooks some of the basic facts of life. tag eng_adverb:lugubriously{ MODIF_TYPE:VERB } // His long face lugubriously reflects a hidden and unexpressed compassion. tag eng_adverb:unreservedly{ MODIF_TYPE:VERB } // I can unreservedly recommend this restaurant! tag eng_adverb:wittily{ MODIF_TYPE:VERB } // He would wittily chime into our conversation. tag eng_adverb:vehemently{ MODIF_TYPE:VERB } // He vehemently denied the accusations against him. tag eng_adverb:verily{ MODIF_TYPE:VERB } // I verily think so. tag eng_adverb:wishfully{ MODIF_TYPE:VERB } // He wishfully indulged in dreams of fame. tag eng_adverb:inaugurally{ MODIF_TYPE:VERB } // The mayor inaugurally drove the spade into the ground. tag eng_adverb:evenly{ MODIF_TYPE:VERB } // A class evenly divided between girls and boys. tag eng_adverb:dutifully{ MODIF_TYPE:VERB } // He dutifully visited his mother every Sunday. tag eng_adverb:slavishly{ MODIF_TYPE:VERB } // His followers slavishly believed in his new diet. tag eng_adverb:roguishly{ MODIF_TYPE:VERB } // He roguishly intended to keep the money. tag eng_adverb:meanly{ MODIF_TYPE:VERB } // This new leader meanly threatens the deepest values of our society. tag eng_adverb:always{ MODIF_TYPE:VERB } // I always stand here. tag eng_adverb:sometimes{ MODIF_TYPE:VERB } // We sometimes go to Spain. tag eng_adverb:now{ MODIF_TYPE:VERB } // He now works for the air force tag eng_adverb:hardly{ MODIF_TYPE:VERB } // She hardly knows. tag eng_adverb:nearly{ MODIF_TYPE:VERB } // I nearly missed the train tag eng_adverb:vigorously{ MODIF_TYPE:VERB } // The lawyer vigorously defended her client tag eng_adverb:thoughtlessly{ MODIF_TYPE:VERB } // He thoughtlessly invited her tag eng_adverb:usually{ MODIF_TYPE:VERB } // He usually walks to work tag eng_adverb:quickly{ MODIF_TYPE:VERB } // He very quickly left the room tag eng_adverb:first{ MODIF_TYPE:VERB } // I have loved you since I first met you tag eng_adverb:allegedly{ MODIF_TYPE:VERB } // He allegedly lost consciousness. tag eng_adverb:already{ MODIF_TYPE:VERB } // I already asked you. tag eng_adverb:unduly{ MODIF_TYPE:VERB } // The speaker unduly criticized his opponent tag eng_adverb:ever{ MODIF_TYPE:VERB } // He never ever sleeps tag eng_adverb:"never ever"{ MODIF_TYPE:VERB } tag eng_adverb:almost{ MODIF_TYPE:VERB } // He almost closed the door. tag eng_adverb:probably{ MODIF_TYPE:VERB } // He probably closed the door tag eng_adverb:fortunately{ MODIF_TYPE:VERB } // He fortunately closed the door tag eng_adverb:biochemically{ MODIF_TYPE:VERB } // We biochemically altered the materials tag eng_adverb:successfully{ MODIF_TYPE:VERB } // He successfully climbed the mountain tag eng_adverb:never{ MODIF_TYPE:VERB } // He never sleeps tag eng_adverb:wisely{ MODIF_TYPE:VERB } // She wisely decided to re-check her homework before submitting it. tag eng_adverb:really{ MODIF_TYPE:VERB } // He really messed up tag eng_adverb:consistently{ MODIF_TYPE:VERB } // Urban interests were consistently underrepresented in the legislature. tag eng_adverb:densely{ MODIF_TYPE:VERB } // The most densely inhabited area is Flanders. tag eng_adverb:sharply{ MODIF_TYPE:VERB } // She was being sharply questioned. tag eng_adverb:up{ MODIF_TYPE:VERB } // The audience got up and applauded. tag eng_adverb:manually{ MODIF_TYPE:VERB } // Tense the rope manually before tensing the spring. tag eng_adverb:sexually{ MODIF_TYPE:VERB } tag eng_adverb:rapidly{ MODIF_TYPE:VERB } // Lanthanum oxidizes rapidly when exposed to air. tag eng_adverb:auspiciously{ MODIF_TYPE:VERB } // He started his new job auspiciously on his birthday. tag eng_adverb:sensitively{ MODIF_TYPE:VERB } // She questioned the rape victim very sensitively about the attack. tag eng_adverb:insensitively{ MODIF_TYPE:VERB } // The police officer questioned the woman rather insensitively about the attack. tag eng_adverb:headlong{ MODIF_TYPE:VERB } // He fell headlong in love with his cousin. tag eng_adverb:compulsively{ MODIF_TYPE:VERB } // He cleaned his shoes compulsively after every walk. tag eng_adverb:additionally{ MODIF_TYPE:VERB } // Most fiction is additionally categorized by genre. tag eng_adverb:severely{ MODIF_TYPE:VERB } // Political freedoms are severely restricted in Burkina Faso. tag eng_adverb:fitfully{ MODIF_TYPE:VERB } // External investment in Botswana has grown fitfully. tag eng_adverb:likely{ MODIF_TYPE:VERB } // His baptism likely took place at Canterbury. tag eng_adverb:chemically{ MODIF_TYPE:VERB } // What is formed when a sodium atom and chlorine atom react chemically? tag eng_adverb:partially{ MODIF_TYPE:VERB } // Simony had been partially checked. tag eng_adverb:freely{ MODIF_TYPE:VERB } // I couldn't move freely. tag eng_adverb:synthetically{ MODIF_TYPE:VERB } // Boron nitride is produced synthetically. tag eng_adverb:ultimately{ MODIF_TYPE:VERB } // The players were ultimately acquitted. tag eng_adverb:differently{ MODIF_TYPE:VERB } // Each type is manufactured differently. tag eng_adverb:alone{ MODIF_TYPE:VERB } // Mature bulls rarely travel alone. tag eng_adverb:geographically{ MODIF_TYPE:VERB } // Church congregations are organized geographically. tag eng_adverb:critically{ MODIF_TYPE:VERB } // The game was critically acclaimed. tag eng_adverb:home{ MODIF_TYPE:VERB } // Kaye flew home for dinner. tag eng_adverb:together{ MODIF_TYPE:VERB } // In colloquium, subjects are grouped together. tag eng_adverb:primarily{ MODIF_TYPE:VERB } // Islam is practised primarily by ethnic Malays. tag eng_adverb:otherwise{ MODIF_TYPE:VERB } // It was otherwise optimized for low-level penetration. tag eng_adverb:traditionally{ MODIF_TYPE:VERB } // It is traditionally written with embossed paper. tag eng_adverb:forward{ MODIF_TYPE:VERB } // They lay flat and kept driving forward. tag eng_adverb:badly{ MODIF_TYPE:VERB } // They are badly damaged by souvenir seekers. tag eng_adverb:even{ MODIF_TYPE:VERB } // This performance was even recorded on video. tag eng_adverb:currently{ MODIF_TYPE:VERB } tag eng_adverb:Frequently{ MODIF_TYPE:VERB } // Frequently invoked in modern logic and philosophy. tag eng_adverb:late{ MODIF_TYPE:VERB } // Gantry later joined The Alan Parsons Project. tag eng_adverb:closely{ MODIF_TYPE:VERB } // The resulting sound closely mimics numerous instruments. tag eng_adverb:down{ MODIF_TYPE:VERB } // Commercial operations will be gradually wound down. tag eng_adverb:independently{ MODIF_TYPE:VERB } // Special forces operate independently under MOD direction. tag eng_adverb:broadly{ MODIF_TYPE:VERB } // Often the word is defined more broadly. tag eng_adverb:back{ MODIF_TYPE:VERB } // Verlinsky did not get his title back. tag eng_adverb:directly{ MODIF_TYPE:VERB } // Plugins can extend the GCC compiler directly. tag eng_adverb:carefully{ MODIF_TYPE:VERB } // Even his fiction contained carefully concealed parables. tag eng_adverb:slightly{ MODIF_TYPE:VERB } // It is sometimes abbreviated slightly to gobbledygoo. tag eng_adverb:since{ MODIF_TYPE:VERB } // Urocor was since acquired by Dianon Systems. tag eng_adverb:out{ MODIF_TYPE:VERB } // They flew out over Skegness and Cromer. tag eng_adverb:as well{ MODIF_TYPE:VERB } // It also broke along generational lines as well; tag eng_adverb:tableside{ MODIF_TYPE:VERB } // It is often prepared tableside. tag eng_adverb:south{ MODIF_TYPE:VERB } // He then continued south towards the Peloponnese. tag eng_adverb:scantily{ MODIF_TYPE:VERB } // Aequian is scantily documented by two inscriptions. tag eng_adverb:abroad{ MODIF_TYPE:VERB } // He had rarely travelled abroad; tag eng_adverb:where{ MODIF_TYPE:VERB } // My taxes go where? tag eng_adverb:today{ MODIF_TYPE:VERB } // This support continues even today. tag eng_adverb:simultaneously{ MODIF_TYPE:VERB } // Chemotherapy may be used simultaneously. tag eng_adverb:backward{ MODIF_TYPE:VERB } // The rotor is tilted backward. tag eng_adverb:regularly{ MODIF_TYPE:VERB } // Security clearances are checked regularly; tag eng_adverb:off{ MODIF_TYPE:VERB } tag eng_adverb:above{ MODIF_TYPE:VERB } tag eng_adverb:hard{ MODIF_TYPE:VERB } tag eng_adverb:skywards{ MODIF_TYPE:VERB } tag eng_adverb:amiss{ MODIF_TYPE:VERB } tag eng_adverb:well{ MODIF_TYPE:VERB } tag eng_adverb:alike{ MODIF_TYPE:VERB } tag eng_adverb:Conically{ MODIF_TYPE:VERB } tag eng_adverb:in{ MODIF_TYPE:VERB } // The wall gave in. tag eng_adverb:near{ MODIF_TYPE:VERB } // They drew nearer. tag eng_adverb:too{ MODIF_TYPE:VERB } tag eng_adverb:over{ MODIF_TYPE:VERB } // Can I sleep over? tag eng_adverb:inwards{ MODIF_TYPE:VERB } // tag eng_adverb:so{ MODIF_TYPE:VERB } // My head aches so! tag eng_adverb:nearby{ MODIF_TYPE:VERB } // She works nearby. tag eng_adverb:easily{ MODIF_TYPE:VERB } // He angers easily. tag eng_adverb:monthly{ MODIF_TYPE:VERB } // They meet monthly. tag eng_adverb:under{ MODIF_TYPE:VERB } // Get under quickly! tag eng_adverb:astray{ MODIF_TYPE:VERB } // He was led astray. tag eng_adverb:whole{ MODIF_TYPE:VERB } // I ate a fish whole! tag eng_adverb:inside{ MODIF_TYPE:VERB } // Was the dog inside? tag eng_adverb:all over{ MODIF_TYPE:VERB } // She ached all over. tag eng_adverb:wide{ MODIF_TYPE:VERB } // Open your eyes wide. tag eng_adverb:upcountry{ MODIF_TYPE:VERB } // They live upcountry. tag eng_adverb:merrily{ MODIF_TYPE:VERB } // The bird sang merrily tag eng_adverb:poorly{ MODIF_TYPE:VERB } // She's feeling poorly. tag eng_adverb:nobly{ MODIF_TYPE:VERB } // She has behaved nobly. tag eng_adverb:low{ MODIF_TYPE:VERB } // The branches hung low. tag eng_adverb:heavenward{ MODIF_TYPE:VERB } // He pointed heavenward. tag eng_adverb:loudly{ MODIF_TYPE:VERB } // Don't speak so loudly. tag eng_adverb:wanly{ MODIF_TYPE:VERB } // She was smiling wanly. tag eng_adverb:leisurely{ MODIF_TYPE:VERB } // He traveled leisurely. tag eng_adverb:by{ MODIF_TYPE:VERB } // An enemy plane flew by. tag eng_adverb:westerly{ MODIF_TYPE:VERB } // The wind blew westerly. tag eng_adverb:outright{ MODIF_TYPE:VERB } // He was killed outright. tag eng_adverb:quietly{ MODIF_TYPE:VERB } // She was crying quietly. tag eng_adverb:sideways{ MODIF_TYPE:VERB } // A picture lit sideways. tag eng_adverb:legibly{ MODIF_TYPE:VERB } // You must write legibly. tag eng_adverb:rationally{ MODIF_TYPE:VERB } // We must act rationally. tag eng_adverb:westbound{ MODIF_TYPE:VERB } // He was driving westbound tag eng_adverb:malapropos{ MODIF_TYPE:VERB } // She answered malapropos. tag eng_adverb:man-to-man{ MODIF_TYPE:VERB } // We must talk man-to-man. tag eng_adverb:face to face{ MODIF_TYPE:VERB } // They spoke face to face. tag eng_adverb:soon{ MODIF_TYPE:VERB } // The time will come soon. tag eng_adverb:cleanly{ MODIF_TYPE:VERB } // The motor burns cleanly. tag eng_adverb:responsibly{ MODIF_TYPE:VERB } // We must act responsibly. tag eng_adverb:weirdly{ MODIF_TYPE:VERB } // She was dressed weirdly. tag eng_adverb:plainly{ MODIF_TYPE:VERB } // She was dressed plainly. tag eng_adverb:tight{ MODIF_TYPE:VERB } // The pub was packed tight. tag eng_adverb:noisily{ MODIF_TYPE:VERB } // He blew his nose noisily. tag eng_adverb:raucously{ MODIF_TYPE:VERB } // His voice rang raucously. tag eng_adverb:hand in hand{ MODIF_TYPE:VERB } // They walked hand in hand. tag eng_adverb:onshore{ MODIF_TYPE:VERB } // They were living onshore. tag eng_adverb:outside{ MODIF_TYPE:VERB } // In summer we play outside. tag eng_adverb:presently{ MODIF_TYPE:VERB } // She will arrive presently. tag eng_adverb:head-on{ MODIF_TYPE:VERB } // The cars collided head-on. tag eng_adverb:seaward{ MODIF_TYPE:VERB } // The sailor looked seaward. tag eng_adverb:roundly{ MODIF_TYPE:VERB } // He was criticized roundly. tag eng_adverb:aloft{ MODIF_TYPE:VERB } // Eagles were soaring aloft. tag eng_adverb:singly{ MODIF_TYPE:VERB } // They were arranged singly. tag eng_adverb:in vain{ MODIF_TYPE:VERB } // He looked for her in vain. tag eng_adverb:crosswise{ MODIF_TYPE:VERB } // Things are going crosswise. tag eng_adverb:behind{ MODIF_TYPE:VERB } // My watch is running behind. tag eng_adverb:sky-high{ MODIF_TYPE:VERB } // Garbage was piled sky-high. tag eng_adverb:uppermost{ MODIF_TYPE:VERB } // The blade turned uppermost. tag eng_adverb:dourly{ MODIF_TYPE:VERB } // He sat in his chair dourly. tag eng_adverb:transversely{ MODIF_TYPE:VERB } // They were cut transversely. tag eng_adverb:thick{ MODIF_TYPE:VERB } // Snow lay thick on the ground tag eng_adverb:negligently{ MODIF_TYPE:VERB } // He did his work negligently. tag eng_adverb:posthumously{ MODIF_TYPE:VERB } // He was honored posthumously. tag eng_adverb:hopelessly{ MODIF_TYPE:VERB } // He hung his head hopelessly. tag eng_adverb:unhesitatingly{ MODIF_TYPE:VERB } // She said yes unhesitatingly. tag eng_adverb:yesterday{ MODIF_TYPE:VERB } // I swam in the river yesterday tag eng_adverb:hot{ MODIF_TYPE:VERB } // The casserole was piping hot. tag eng_adverb:steadily{ MODIF_TYPE:VERB } // His interest eroded steadily. tag eng_adverb:shortly{ MODIF_TYPE:VERB } // The book will appear shortly. tag eng_adverb:coastwise{ MODIF_TYPE:VERB } // We were travelling coastwise. tag eng_adverb:fearfully{ MODIF_TYPE:VERB } // They were fearfully attacked. tag eng_adverb:mechanically{ MODIF_TYPE:VERB } // This door opens mechanically. tag eng_adverb:half-and-half{ MODIF_TYPE:VERB } // It was divided half-and-half. tag eng_adverb:repeatedly{ MODIF_TYPE:VERB } // It must be washed repeatedly. tag eng_adverb:excitedly{ MODIF_TYPE:VERB } // She shook his hand excitedly. tag eng_adverb:affectionately{ MODIF_TYPE:VERB } // He treats her affectionately. tag eng_adverb:somewhat{ MODIF_TYPE:VERB } // Unfortunately the surviving copy is somewhat mutilated. tag eng_adverb:socially{ MODIF_TYPE:VERB } // In this view expertise is socially constructed; tag eng_adverb:uniformly{ MODIF_TYPE:VERB } // However, this is not uniformly accepted. tag eng_adverb:subsequently{ MODIF_TYPE:VERB } // These were subsequently confirmed by Heinrich Hertz. tag eng_adverb:effectively{ MODIF_TYPE:VERB } // The country was effectively divided in two. tag eng_adverb:asleep{ MODIF_TYPE:VERB } // When she fell asleep Apollo raped her. tag eng_adverb:similarly{ MODIF_TYPE:VERB } // Financial engineering has similarly borrowed the term. tag eng_adverb:generally{ MODIF_TYPE:VERB } // Universities are generally composed of several colleges. tag eng_adverb:formally{ MODIF_TYPE:VERB } // These cells are formally called equivalence classes. tag eng_adverb:precipitously{ MODIF_TYPE:VERB } tag eng_adverb:easterly{ MODIF_TYPE:VERB } // The winds blew easterly all night. tag eng_adverb:unchangeably{ MODIF_TYPE:VERB } // His views were unchangeably fixed. tag eng_adverb:asymmetrically{ MODIF_TYPE:VERB } // They were asymmetrically arranged. tag eng_adverb:upstage{ MODIF_TYPE:VERB } // The actor turned and walked upstage tag eng_adverb:foully{ MODIF_TYPE:VERB } // Two policemen were foully murdered. tag eng_adverb:unpleasantly{ MODIF_TYPE:VERB } // He has been unpleasantly surprised. tag eng_adverb:overnight{ MODIF_TYPE:VERB } // The mud had consolidated overnight. tag eng_adverb:east{ MODIF_TYPE:VERB } // We travelled east for several miles. tag eng_adverb:west{ MODIF_TYPE:VERB } tag eng_adverb:amply{ MODIF_TYPE:VERB } // These voices were amply represented. tag eng_adverb:tonight{ MODIF_TYPE:VERB } // She is flying to Cincinnati tonight. tag eng_adverb:ninefold { MODIF_TYPE:VERB } // My investment has increased ninefold. tag eng_adverb:noticeably{ MODIF_TYPE:VERB } // He changed noticeably over the years. tag eng_adverb:awry{ MODIF_TYPE:VERB } // Something has gone awry in our plans. tag eng_adverb:zigzag{ MODIF_TYPE:VERB } // Birds flew zigzag across the blue sky. tag eng_adverb:cosmetically{ MODIF_TYPE:VERB } // It is used cosmetically by many women. tag eng_adverb:casually{ MODIF_TYPE:VERB } // He dealt with his course work casually. tag eng_adverb:shiftily{ MODIF_TYPE:VERB } // He looked at his new customer shiftily. tag eng_adverb:perplexedly{ MODIF_TYPE:VERB } // He looked at his professor perplexedly. tag eng_adverb:impassively{ MODIF_TYPE:VERB } // He submitted impassively to his arrest. tag eng_adverb:supinely{ MODIF_TYPE:VERB } // She was stretched supinely on her back. tag eng_adverb:clear{ MODIF_TYPE:VERB } // The bullet went clear through the wall. tag eng_adverb:unquestioningly{ MODIF_TYPE:VERB } // He followed his leader unquestioningly. tag eng_adverb:stoutly{ MODIF_TYPE:VERB } // He was stoutly replying to his critics. tag eng_adverb:apologetically{ MODIF_TYPE:VERB } // He spoke apologetically about his past. tag eng_adverb:readily{ MODIF_TYPE:VERB } // These snakes can be identified readily. tag eng_adverb:kinesthetically{ MODIF_TYPE:VERB } // He can perceive shapes kinesthetically. tag eng_adverb:microscopically{ MODIF_TYPE:VERB } // The blood was examined microscopically. tag eng_adverb:separably{ MODIF_TYPE:VERB } // The two ideas were considered separably. tag eng_adverb:administratively{ MODIF_TYPE:VERB } // This decision was made administratively. tag eng_adverb:inconspicuously{ MODIF_TYPE:VERB } // He had entered the room inconspicuously. tag eng_adverb:condescendingly{ MODIF_TYPE:VERB } // He treats his secretary condescendingly. tag eng_adverb:underground{ MODIF_TYPE:VERB } // The organization was driven underground. tag eng_adverb:vivaciously{ MODIF_TYPE:VERB } // He describes his adventures vivaciously. tag eng_adverb:macroscopically{ MODIF_TYPE:VERB } // The tubes were examined macroscopically. tag eng_adverb:temperately{ MODIF_TYPE:VERB } // These preferences are temperately stated. tag eng_adverb:northeastward{ MODIF_TYPE:VERB } // The river flows northeastward to the gulf. tag eng_adverb:southeastward{ MODIF_TYPE:VERB } // The river flows southeastward to the gulf. tag eng_adverb:unattractively{ MODIF_TYPE:VERB } // She was unattractively dressed last night. tag eng_adverb:insolently{ MODIF_TYPE:VERB } // He had replied insolently to his superiors. tag eng_adverb:downstream{ MODIF_TYPE:VERB } // The raft floated downstream on the current. tag eng_adverb:restrictively{ MODIF_TYPE:VERB } // This relative clause is used restrictively. tag eng_adverb:sedulously{ MODIF_TYPE:VERB } // This illusion has been sedulously fostered. tag eng_adverb:lukewarmly{ MODIF_TYPE:VERB } // He was lukewarmly received by his relatives. tag eng_adverb:erratically{ MODIF_TYPE:VERB } // Economic changes are proceeding erratically. tag eng_adverb:bombastically{ MODIF_TYPE:VERB } // He lectured bombastically about his theories. tag eng_adverb:maniacally{ MODIF_TYPE:VERB } // He will be maniacally obsessed with jealousy. tag eng_adverb:interdepartmentally{ MODIF_TYPE:VERB } // This memo was circulated interdepartmentally. tag eng_adverb:rhythmically{ MODIF_TYPE:VERB } // The chair rocked rhythmically back and forth. tag eng_adverb:piggyback{ MODIF_TYPE:VERB } // The trailer rode piggyback across the country. tag eng_adverb:inadequately{ MODIF_TYPE:VERB } // The temporary camps were inadequately equipped. tag eng_adverb:piecemeal{ MODIF_TYPE:VERB } // The research structure has developed piecemeal. tag eng_adverb:mournfully{ MODIF_TYPE:VERB } // The young man stared into his glass mournfully. tag eng_adverb:regretfully{ MODIF_TYPE:VERB } // I must regretfully decline your kind invitation. tag eng_adverb:airily{ MODIF_TYPE:VERB } // This cannot be airily explained to your children. tag eng_adverb:needlessly{ MODIF_TYPE:VERB } // It would needlessly bring badness into the world. tag eng_adverb:upstairs{ MODIF_TYPE:VERB } // He went upstairs into the best rooms only on rare occasions. tag eng_adverb:hurriedly{ MODIF_TYPE:VERB } // They departed hurriedly because of some great urgency in their affairs. tag eng_adverb:distinctly{ MODIF_TYPE:VERB } // Urbanization in Spain is distinctly correlated with a fall in reproductive rate. tag eng_adverb:upside down{ MODIF_TYPE:VERB } // The thief had turned the room upside down tag eng_adverb:edgeways{ MODIF_TYPE:VERB } // He sawed the board edgeways. tag eng_adverb:far{ MODIF_TYPE:VERB } // Branches are straggling out quite far. tag eng_adverb:mainly{ MODIF_TYPE:VERB } // He is mainly interested in butterflies. tag eng_adverb:broadside{ MODIF_TYPE:VERB } // The train hit the truck broadside. tag eng_adverb:high{ MODIF_TYPE:VERB } // The eagle beat its wings and soared high into the sky. tag eng_adverb:aside{ MODIF_TYPE:VERB } // Put her sewing aside when he entered. tag eng_adverb:eastward{ MODIF_TYPE:VERB } // We have to advance clocks and watches when we travel eastward. tag eng_adverb:stateside{ MODIF_TYPE:VERB } // I'll be going stateside next month! tag eng_adverb:counterclockwise{ MODIF_TYPE:VERB } // Please move counterclockwise in a circle! tag eng_adverb:eventually{ MODIF_TYPE:VERB } // tag eng_adverb:widely{ MODIF_TYPE:VERB } // It was widely adopted as a replacement. tag eng_adverb:duly{ MODIF_TYPE:VERB } // A band was duly assembled. tag eng_adverb:close{ MODIF_TYPE:VERB } // Come closer, my dear! tag eng_adverb:deeply{ MODIF_TYPE:VERB } // I was deeply impressed. tag eng_adverb:officially{ MODIF_TYPE:VERB } // Citizens are officially called Barbadians. tag eng_adverb:north{ MODIF_TYPE:VERB } // Let's go north! tag eng_adverb:clearly{ MODIF_TYPE:VERB } // They were clearly lost. tag eng_adverb:aloud{ MODIF_TYPE:VERB } // Please read the passage aloud. tag eng_adverb:tomorrow{ MODIF_TYPE:VERB } // I shall buy a new pen tomorrow tag eng_adverb:romantically{ MODIF_TYPE:VERB } // They were romantically linked. tag eng_adverb:barbarously{ MODIF_TYPE:VERB } // They were barbarously murdered. tag eng_adverb:empirically{ MODIF_TYPE:VERB } // This can be empirically tested. tag eng_adverb:substantially{ MODIF_TYPE:VERB } // The price went up substantially tag eng_adverb:overhead{ MODIF_TYPE:VERB } // The seagulls fluttered overhead. tag eng_adverb:offstage{ MODIF_TYPE:VERB } // The actors were waiting offstage. tag eng_adverb:overseas{ MODIF_TYPE:VERB } // He lived overseas for many years. tag eng_adverb:tenfold{ MODIF_TYPE:VERB } // The population increased tenfold. tag eng_adverb:symmetrically{ MODIF_TYPE:VERB } // They were asymmetrically arranged. tag eng_adverb:clockwise{ MODIF_TYPE:VERB } // Please move clockwise in a circle. tag eng_adverb:typically{ MODIF_TYPE:VERB } // Priming effects are typically analysed as being internal to the IT classification system. tag eng_adverb:experimentally{ MODIF_TYPE:VERB } // This can be experimentally determined. tag eng_adverb:inherently{ MODIF_TYPE:VERB } // Module and chip characteristics are inherently linked. #endregion MODIF_TYPE:VERB // The roles are but three; tag eng_adverb:but{ MODIF_TYPE:NUMBER } }
This is still impracticably high.
tag eng_adverb:impracticably{ MODIF_TYPE:ADJ }
6,445,866
[ 1, 2503, 353, 4859, 1646, 14266, 335, 6906, 3551, 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, 2692, 24691, 67, 361, 16629, 30, 14532, 14266, 335, 6906, 95, 8663, 5501, 67, 2399, 30, 1880, 46, 289, 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 ]
/* * Contract code of paper "Spass: Spectrum Sensing as a Service via Smart Contracts", S. Bayhan, A. Zubow, and A. Wolisz, IEEE DYSPAN, 2018. * * @author Zubow, 2018 */ pragma solidity ^0.4.0; contract SSaaS { struct Helper { // relevant parameter to identify a helper uint id; // helper address uint p_f; // false alarm probability / 1000 uint p_d; // detection probability / 1000 uint priceSenseBit; // set by the helper uint last_report_seq; // seq. number of reported sensing data bytes data; // sensing data as byte array bool toBlock; // whether this helper will be blocked in next round } address public owner; // of this contract -> the SU mapping(address => Helper) shMap; address[] shLst; mapping (address => uint) public pendingWithdrawals; /* Service configuration set by contract owner */ uint sens_f; // sensing sampling, i.e. readings per second uint round_s; // helpers report their sensing once per round uint data_b; // size of sensing report in bytes send per round to contract uint max_p_f; // per 1000; set by regulator uint min_p_d; // per 1000; set by regulator uint curr_seq; // the current expected seq event Debug0(string msg); event Debug1(string msg, uint v); /* Create new SSaaS contract, specifies the address of the owner */ constructor () public { owner = msg.sender; } modifier ownerOnly { if (msg.sender != owner) { revert(); } _; } /* Called by the owner (=SU) of this contract to initialize it */ function init(uint _sens_f, uint _round_s, uint _cp_f, uint _max_p_f, uint _min_p_d) public ownerOnly returns(bool) { if (!check_args(_sens_f, _round_s, _cp_f, _max_p_f, _min_p_d)) { emit Debug0("incorrect arguments!"); return false; } sens_f = _sens_f; round_s = _round_s; max_p_f = _max_p_f; min_p_d = _min_p_d; data_b = _round_s * _sens_f / _cp_f / 8 + 1; curr_seq = 1; } /* Add new helper to the contract; called by H (helpers) */ function registerSensingHelper(address _sHelper, uint _id, uint _priceSenseBit, uint _p_f, uint _p_d) public returns(bool) { if (shMap[_sHelper].priceSenseBit != 0) { emit Debug0("Helper already registered."); return false; // sensingHelper with that address was already registered } if (rejectHelper(_priceSenseBit, _p_f, _p_d)) { emit Debug0("Helper rejected; high price or bad sensing accuracy."); return false; // helper rejected due to e.g. high price } shMap[_sHelper] = Helper({id: _id, p_f: _p_f, p_d: _p_d, priceSenseBit: _priceSenseBit, last_report_seq: 0, data: new bytes(data_b), toBlock: false }); shLst.push(_sHelper); return true; } /* Check if sufficient Hs available; called by H */ function waitForOtherHelpers() public returns(bool) { if (sufficientRegisteredHelpers()) { return false; // wait for other helpers } return true; } /* Periodically called by helpers (H) to report sensing data */ function reportSensingData(address _sHelper, uint _id, uint _seq, bytes _data) public returns(bool) { if (shMap[_sHelper].priceSenseBit == 0) { emit Debug0("Unknown sensing helper; please register first."); return false; // sensing data from unknown helper; ignore } if ( (shMap[_sHelper].last_report_seq + 1) != _seq) { emit Debug0("Ignoring outdated sensing data."); return false; // ignore outdated sensing data } if (_data.length != data_b) { emit Debug0("Report has incorrect size."); return false; // incorrect report size } // copy new data for (uint i=0; i<data_b; i++) { shMap[_sHelper].data[i] = _data[i]; } shMap[_sHelper].last_report_seq = _seq; return true; } /* At end of each round contract owner (SU) makes payments to helpers */ function clearing(uint _seq) public ownerOnly returns(bool) { if (curr_seq != _seq) { emit Debug0("Clearing incorrect round (seq. number)."); return false; } /* run malicious node detection; mark helpers accordingly */ markMaliciousNodes(); // mark cheaters for (uint i=0; i<shLst.length; i++) { if (shMap[shLst[i]].toBlock == true) { blockSensingHelper(shLst[i]); // block malicious helpers } else { notifyPayment(shLst[i]); // notify honest helpers of payment } } curr_seq++; /* go to next round */ return true; } /* Notify H of its credit for amount of sensing. */ function notifyPayment(address _sHelper) ownerOnly private returns(bool) { if (shMap[_sHelper].priceSenseBit == 0 || shMap[_sHelper].toBlock) { emit Debug0("Sensing helper blocked; no withdrawal possible."); return false; } uint payment = shMap[_sHelper].priceSenseBit * (round_s * sens_f); // pay agreed price pendingWithdrawals[_sHelper] += payment; emit Debug1("Payment made to helper:", payment); return true; } /* Allows helper (H) to withdraw any outstanding credit */ function withdraw() public returns(bool) { uint amount = pendingWithdrawals[msg.sender]; if (amount <= 0) { emit Debug0("Nothing to withdraw."); return false; } pendingWithdrawals[msg.sender] = 0; if (msg.sender.send(amount)) { return true; // TX ok } else { emit Debug0("Failed to withdraw."); pendingWithdrawals[msg.sender] = amount; return false; } return true; } /* Transfer ether to the contract so that helpers can withdraw funds to receive payment for the sensing they performed. */ function increaseFunds() public payable {} /* block a helper, effectively removing it from the list */ function blockSensingHelper(address _sensingHelper) ownerOnly private returns(bool) { if (shMap[_sensingHelper].priceSenseBit == 0) { emit Debug0("Unknown helper."); return false; } /* Remove blocked helper from list of helpers */ delete shMap[_sensingHelper]; for (uint i=0; i<shLst.length; i++) { if (shLst[i] == _sensingHelper) { delete shLst[i]; break; } } return true; } /* Destroy the contract and return funds to owner */ function selfDestruct() public ownerOnly { selfdestruct(owner); } /* Change ownership of the contract */ function changeOwner(address _newOwner) public ownerOnly { if (owner != _newOwner) { owner = _newOwner; } } //// //// Helpers //// /* Algorithm used to detect malicious users */ function markMaliciousNodes() private returns(bool) { // TBD: just mockup: only helpers without report are classified as malicious // check if some helpers need to be blacklisted for (uint i=0; i<shLst.length; i++) { // check if need to block if (shMap[shLst[i]].last_report_seq != curr_seq) { // no sensing data was reported in last round; block user shMap[shLst[i]].toBlock = true; } // TBD: run algo from paper for detection } return true; } /* Check whether we have enough helpers in order to start the SSaaS */ function sufficientRegisteredHelpers() private view returns (bool) { /* Mockup: do more intelligent stuff here; see paper */ if (shLst.length == 1) { return true; // one helper is enough } return false; } /* Do checks */ function check_args(uint _sens_f, uint _round_s, uint _cp_f, uint _max_p_f, uint _min_p_d) private pure returns(bool) { if (_max_p_f == 0 || _min_p_d == 1000 || _sens_f == 0 || _round_s == 0 || _cp_f == 0) return false; /* Do some more checks */ return true; } /* Check whether the helper meets requirements and offers attractive price */ function rejectHelper(uint _priceSenseBit, uint _p_f, uint _p_d) private pure returns(bool) { // Check that _priceSenseBit and p_f/p_d are positive if (_priceSenseBit <= 0 || _p_f <= 0 || _p_d <= 0) return true; if (_p_f > 100 || _p_d < 900) return false; // bad sensors /* Mockup : do something real here; look into our paper */ return false; } }
Destroy the contract and return funds to owner */
function selfDestruct() public ownerOnly { selfdestruct(owner); }
15,830,512
[ 1, 10740, 326, 6835, 471, 327, 284, 19156, 358, 3410, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 365, 6305, 8813, 1435, 1071, 3410, 3386, 288, 203, 1377, 365, 5489, 8813, 12, 8443, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; //import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; //import "./SignedMinting.sol"; interface NftContract { function mint(address) external; function balanceOf(address) external view returns (uint256); } contract BarnyardFashionistasStore is ReentrancyGuard, Ownable { //contract BarnyardFashionistasStore is EIP712, SignedMinting, Ownable { NftContract public bfNft = NftContract(0xBAB7dF6D042F4b83b62070b670Da929b62eD22d8); address private constant core1Address = 0x3002E0E7Db1FB99072516033b8dc2BE9897178bA; uint256 private constant core1Shares = 84650; address private constant core2Address = 0x452d40db156034223e8865F93d6a532aE62c4A99; uint256 private constant core2Shares = 5000; address private constant core3Address = 0xEbCEe6204eeEEf21e406C0A75734E70f342914e0; uint256 private constant core3Shares = 5000; address private constant core4Address = 0xCa93378a4d2c9217A1f6C2D9aB50B791a4043A87; uint256 private constant core4Shares = 3000; address private constant core5Address = 0xa808208Bb50e2395c63ce3fd41990d2E009E3053; uint256 private constant core5Shares = 750; address private constant core6Address = 0x1996FabEC51878e3Ff99cd07c6CaC9Ac668A22fD; uint256 private constant core6Shares = 600; address private constant core7Address = 0x30734A0adeCa7e07c3C960587d6502fC5EA0f8df; uint256 private constant core7Shares = 500; address private constant core8Address = 0x74E101B1E67Cd303A3ec896421ceCf894891ac25; uint256 private constant core8Shares = 500; uint256 private constant baseMod = 100000; /** Numbers for Barnyard Fashionistas NftContract */ // uint256 public constant maxFashionistas = 9999; uint256 public maxFashionistas = 9999; //whitelist and mints mapping(address => uint256) private whitelist; mapping(address => uint256) private bonusMintAmount; mapping(address => uint256) private oglist; mapping(address => uint256) public mintedFashionistasOf; /** Team allocated Fashionistas */ // Fashionistas which is minted by the owner uint256 public preMintedFashionistas = 0; // MAX Fashionistas which owner can mint uint256 public constant maxPreMintFashionistas = 300; // Mint counts during presale uint256 public newlyMintedFashionistasPresale = 0; //Tracking Sales After Presale uint256 public mintedFashionistasAfterPresale = 0; uint256 public mintedFashionistasBonus = 0; uint256 public mintedOgClaim = 0; /** Pricing & sales */ uint256 public price = 0.044 ether; uint256 public maxMintPerTx = 6; uint256 public whitelistMints = 4; uint256 public maxMintBonusTx = 2; uint256 public maxMintBonus = 1; uint256 public bonusMintsTotal = 500; uint256 public bonusMintsPresale = 200; //sync with prev store release uint256 public mintedFashionistas = 263; event SetFashionistasNftContract(address bfNft); event MintWithWhitelist(address account, uint256 amount, uint256 changes); event SetRemainingFashionistas(uint256 remainingFashionistas); event mintFashionistas(address account, uint256 amount); event Withdraw(address to); bool public presaleOn = false; bool public mainSaleOn = false; bool public bonusSaleOn = false; constructor( ) ReentrancyGuard() { } modifier mainSaleOpened() { require( mainSaleOn, "Store is not opened" ); _; } modifier presaleOpened() { require(presaleOn, "Store is not opened for Presale"); _; } modifier bonussaleOpened() { require(bonusSaleOn, "Store is not opened for Presale"); _; } modifier onlyOwnerOrTeam() { require( core1Address == msg.sender || core2Address == msg.sender || core4Address == msg.sender || owner() == msg.sender, "caller is neither Team Wallet nor Owner" ); _; } function setPrice(uint256 _newPrice) external onlyOwner { price = _newPrice; } function setMaxMintPerTx(uint256 _newtx) external onlyOwner { maxMintPerTx = _newtx; } function setMaxBonusTx(uint256 _newtx) external onlyOwner { maxMintBonusTx = _newtx; } function setMaxBonus(uint256 _newbonus) external onlyOwner { maxMintBonus = _newbonus; } function setBonusMintsTotal(uint256 _newbonus) external onlyOwner { bonusMintsTotal = _newbonus; } //sync with prev store release function setStoreMininumStart(uint256 _newnum) external onlyOwner { mintedFashionistas = _newnum; } function togglePresale() external onlyOwner { presaleOn = !presaleOn; } function toggleMainSale() external onlyOwner { mainSaleOn = !mainSaleOn; } function toggleBonusSale() external onlyOwner { bonusSaleOn = !bonusSaleOn; } function presaleBalance( address checkAddr ) public view returns(uint256) { return whitelist[checkAddr]; } function setFashionistasNftContract(NftContract _bfNft) external onlyOwner { bfNft = _bfNft; emit SetFashionistasNftContract(address(_bfNft)); } function preMintFashionistas(address[] memory recipients) external onlyOwner { uint256 totalRecipients = recipients.length; require( totalRecipients > 0, "Number of recipients must be greater than 0" ); require( preMintedFashionistas + totalRecipients <= maxPreMintFashionistas, "Exceeds max pre-mint Fashionistas" ); require( mintedFashionistas + totalRecipients < maxFashionistas, "Exceeds max Fashionistas" ); for (uint256 i = 0; i < totalRecipients; i++) { address to = recipients[i]; require(to != address(0), "receiver can not be empty address"); bfNft.mint(to); } preMintedFashionistas += totalRecipients; mintedFashionistas += totalRecipients; } // adds to whitelist with specified amounts function addToOGlistAmounts(address[] memory _listToAdd, uint256[] memory _amountPerAddress) public onlyOwner { uint256 totalAddresses = _listToAdd.length; uint256 totalAmounts = _amountPerAddress.length; require(totalAddresses == totalAmounts, "Item amounts differ"); for (uint256 i = 0; i < totalAddresses; i++) { oglist[_listToAdd[i]] = _amountPerAddress[i]; } } function ogClaim() public payable presaleOpened nonReentrant { uint256 _count = oglist[msg.sender]; require(mintedFashionistas + _count <= maxFashionistas, "Max limit"); uint256 _balance = bfNft.balanceOf(msg.sender); if ( _balance < _count){ _count = _balance; } for (uint256 i = 0; i < _count; i++) { bfNft.mint(msg.sender); } mintedOgClaim += _count; mintedFashionistas += _count; oglist[msg.sender] = oglist[msg.sender] - _count; } // adds to claim list with specified amounts function addToWhitelist(address[] memory _listToAdd) public onlyOwner { uint256 totalAddresses = _listToAdd.length; for (uint256 i = 0; i < totalAddresses; i++) { whitelist[_listToAdd[i]] = whitelistMints; } } function mintPresale( uint256 _count) public payable presaleOpened nonReentrant { require(_count <= whitelist[msg.sender], "Over Max whitelist" ); require(mintedFashionistas + _count <= maxFashionistas, "Max limit"); require(msg.value >= (_count * price ), "Value below price"); for (uint256 i = 0; i < _count; i++) { bfNft.mint(msg.sender); } newlyMintedFashionistasPresale += _count; mintedFashionistas += _count; whitelist[msg.sender] = whitelist[msg.sender] - _count; } function bonusMint( uint256 _count) public payable bonussaleOpened nonReentrant { require(_count <= maxMintBonusTx, "Over MaxTx bonus" ); require(mintedFashionistasBonus + _count < bonusMintsTotal, "less bonus remaining"); require(bonusMintAmount[msg.sender] + _count <= maxMintBonus); if (presaleOn) { require(mintedFashionistasBonus <= bonusMintsPresale, "bonus presale done"); uint256 fashionistaAmount = bfNft.balanceOf(msg.sender); require(fashionistaAmount > 0, "Fashionista Required"); } require(mintedFashionistas + _count <= maxFashionistas, "Max limit"); for (uint256 i = 0; i < _count; i++) { bfNft.mint(msg.sender); } bonusMintAmount[msg.sender] += _count; mintedFashionistasBonus += _count; mintedFashionistas += _count; } function mintMainSale(uint256 _amount) external payable mainSaleOpened { require(mintedFashionistas + _amount -1 < maxFashionistas, "exceeds max mint"); uint256 totalPrice = price * _amount; require(totalPrice <= msg.value, "Not enough money"); require(_amount - 1 < maxMintPerTx, "exceed max transaction"); for (uint256 i = 0; i < _amount; i += 1) { bfNft.mint(msg.sender); } mintedFashionistasAfterPresale += _amount; mintedFashionistas += _amount; emit mintFashionistas(msg.sender, _amount); } function withdrawCore() external onlyOwnerOrTeam { uint256 balance = address(this).balance; require(balance > 0); _splitAll(balance); } // **** ASK HOW MANY CAN DO SAFE function _splitAll(uint256 _amount) private { uint256 singleShare = _amount / baseMod; _withdraw(core1Address, singleShare * core1Shares); _withdraw(core2Address, singleShare * core2Shares); _withdraw(core3Address, singleShare * core3Shares); _withdraw(core4Address, singleShare * core4Shares); _withdraw(core5Address, singleShare * core5Shares); _withdraw(core6Address, singleShare * core6Shares); _withdraw(core7Address, singleShare * core7Shares); _withdraw(core8Address, singleShare * core8Shares); } function withdrawBU() external onlyOwnerOrTeam { uint256 balance = address(this).balance; require(balance > 0); _withdraw(core1Address, balance); } function _withdraw(address _address, uint256 _amount) private { payable(_address).transfer(_amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 // 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; } }
adds to claim list with specified amounts
function addToWhitelist(address[] memory _listToAdd) public onlyOwner { uint256 totalAddresses = _listToAdd.length; for (uint256 i = 0; i < totalAddresses; i++) { whitelist[_listToAdd[i]] = whitelistMints; } }
13,016,953
[ 1, 25428, 358, 7516, 666, 598, 1269, 30980, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9604, 18927, 12, 2867, 8526, 3778, 389, 1098, 13786, 13, 1071, 1338, 5541, 288, 203, 3639, 2254, 5034, 2078, 7148, 273, 389, 1098, 13786, 18, 2469, 31, 203, 377, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 2078, 7148, 31, 277, 27245, 288, 203, 1850, 10734, 63, 67, 1098, 13786, 63, 77, 13563, 273, 10734, 49, 28142, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x75a1B0A25edd09589Ba8c1387AD3755d7fDD729E/sources/contracts/polydexrouter.sol
refund dust eth, if any
function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable virtual override ensure(deadline) returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = PolydexLibrary.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = IPolydexPair(pair).mint(to); if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); }
4,674,173
[ 1, 1734, 1074, 302, 641, 13750, 16, 309, 1281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 48, 18988, 24237, 1584, 44, 12, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 5034, 3844, 1345, 25683, 16, 203, 3639, 2254, 5034, 3844, 1345, 2930, 16, 203, 3639, 2254, 5034, 3844, 1584, 44, 2930, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 14096, 203, 565, 262, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 5024, 203, 3639, 3849, 203, 3639, 3387, 12, 22097, 1369, 13, 203, 3639, 1135, 261, 203, 5411, 2254, 5034, 3844, 1345, 16, 203, 5411, 2254, 5034, 3844, 1584, 44, 16, 203, 5411, 2254, 5034, 4501, 372, 24237, 203, 3639, 262, 203, 565, 288, 203, 3639, 261, 8949, 1345, 16, 3844, 1584, 44, 13, 273, 389, 1289, 48, 18988, 24237, 12, 203, 5411, 1147, 16, 203, 5411, 678, 1584, 44, 16, 203, 5411, 3844, 1345, 25683, 16, 203, 5411, 1234, 18, 1132, 16, 203, 5411, 3844, 1345, 2930, 16, 203, 5411, 3844, 1584, 44, 2930, 203, 3639, 11272, 203, 3639, 1758, 3082, 273, 18394, 561, 9313, 18, 6017, 1290, 12, 6848, 16, 1147, 16, 678, 1584, 44, 1769, 203, 3639, 12279, 2276, 18, 4626, 5912, 1265, 12, 2316, 16, 1234, 18, 15330, 16, 3082, 16, 3844, 1345, 1769, 203, 3639, 1815, 12, 45, 59, 1584, 44, 12, 59, 1584, 44, 2934, 13866, 12, 6017, 16, 3844, 1584, 44, 10019, 203, 3639, 4501, 372, 24237, 273, 2971, 355, 93, 561, 4154, 12, 6017, 2934, 81, 474, 12, 869, 1769, 203, 3639, 309, 261, 3576, 18, 1132, 405, 3844, 1584, 44, 13, 12279, 2276, 18, 4626, 2 ]
pragma solidity ^0.5.2; //pragma experimental ABIEncoderV2; //Create by <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="18757d776f7d766c587f75797174367b7775">[email&#160;protected]</a> +886-975330002 /* ================================================================= Contact HEAD : Data Sets ==================================================================== */ // ---------------------------------------------------------------------------- // Black jack basic data structure // ---------------------------------------------------------------------------- contract Blackjack_DataSets { struct User_AccountStruct { uint UserId; address UserAddress; string UserName; string UserDescription; } struct Game_Unit { uint Game_UnitId; uint[] Player_UserIds; uint Dealer_UserId; uint MIN_BettingLimit; uint MAX_BettingLimit; uint[] Game_RoundsIds; } struct Game_Round_Unit { uint GameRoundId; mapping (uint => Play_Unit) Mapping__Index_PlayUnitStruct; uint[] Cards_InDealer; uint[] Cards_Exsited; } struct Play_Unit { uint Player_UserId; uint Bettings; uint[] Cards_InHand; } mapping (address => uint) Mapping__UserAddress_UserId; mapping (uint => User_AccountStruct) public Mapping__UserId_UserAccountStruct; mapping (uint => Game_Unit) public Mapping__GameUnitId_GameUnitStruct; mapping (uint => Game_Round_Unit) public Mapping__GameRoundId_GameRoundStruct; mapping (uint => uint) public Mapping__OwnerUserId_ERC20Amount; mapping (uint => mapping(uint => uint)) public Mapping__OwnerUserIdAlloweUserId_ERC20Amount; mapping (uint => mapping(uint => uint)) public Mapping__GameRoundIdUserId_Bettings; mapping (uint => string) Mapping__SuitNumber_String; mapping (uint => string) Mapping__FigureNumber_String; uint[13] Im_BlackJack_CardFigureToPoint = [1,2,3,4,5,6,7,8,9,10,10,10,10]; uint public ImCounter_AutoGameId = 852334567885233456788869753300028886975330002; uint public ImCounter_DualGameId; uint public ImCounter_GameRoundId; uint public TotalERC20Amount_LuToken; mapping (uint => uint[2]) public Mapping__AutoGameBettingRank_BettingRange; } /* ================================================================= Contact END : Data Sets ==================================================================== */ /* ================================================================= Contact HEAD : ERC20 interface ==================================================================== */ // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // ---------------------------------------------------------------------------- contract ERC20_Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } /* ================================================================= Contact END : ERC20 interface ==================================================================== */ /* ================================================================= Contact HEAD : Events for Functionalities ==================================================================== */ // ---------------------------------------------------------------------------- // Functionalities event // ---------------------------------------------------------------------------- contract Functionality_Event is Blackjack_DataSets { event Create_UserAccountEvent ( uint _UserIdEvent, address _UserAddressEvent, string _UserNameEvent, string _UserDescriptionEvent ); event Initialize_GameEvent ( uint _GameIdEvent, uint[] _Player_UserIdsEvent, uint _Dealer_UserIdEvent, uint _MIN_BettingLimitEvent, uint _MAX_BettingLimitEvent ); event BettingsEvent ( uint _GameIdEvent, uint _GameRoundIdEvent, uint _UserIdEvent, uint _BettingAmountEvent ); event Initialize_GameRoundEvent ( uint[] _PlayerUserIdSetEvent, uint _GameRoundIdEvent ); event Initialize_GamePlayUnitEvent ( uint _PlayerUserIdEvent, uint _BettingsEvent, uint[] _Cards_InHandEvent ); event GetCardEvent ( uint _GameRoundIdEvent, uint[] _GetCardsInHandEvent ); event Determine_GameRoundResult ( uint _GameIdEvent, uint _GameRoundIdEvent, uint[] _WinnerUserIdEvent, uint[] _DrawUserIdEvent, uint[] _LoserUserIdEvent ); event ExchangeLuTokenEvent ( address _ETH_AddressEvent, uint _ETH_ExchangeAmountEvent, uint _LuToken_UserIdEvnet, uint _LuToken_ExchangeAmountEvnet, uint _LuToken_RemainAmountEvent ); event CheckBetting_Anouncement ( uint GameRoundId, uint UserId, uint UserBettingAmount, uint MinBettingLimit, uint MaxBettingLimit ); } /* ================================================================= Contact END : Events for Functionalities ==================================================================== */ /* ================================================================= Contact HEAD : Access Control ==================================================================== */ // ---------------------------------------------------------------------------- // Black jack access control // ---------------------------------------------------------------------------- contract AccessControl is Blackjack_DataSets, Functionality_Event { // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; // The addresses of the accounts (or contracts) that can execute actions within each roles. address public C_Meow_O_Address = msg.sender; address public LuGoddess = msg.sender; address public ceoAddress = msg.sender; address public cfoAddress = msg.sender; address public cooAddress = msg.sender; modifier StandCheck_AllPlayer(uint GameId) { Game_Unit memory Im_GameUnit_Instance = Mapping__GameUnitId_GameUnitStruct[GameId]; uint Im_RoundId = Im_GameUnit_Instance.Game_RoundsIds[Im_GameUnit_Instance.Game_RoundsIds.length-1]; Game_Round_Unit storage Im_GameRoundUnit_Instance = Mapping__GameRoundId_GameRoundStruct[Im_RoundId]; for(uint Im_PlayUnitCounter = 0 ; Im_PlayUnitCounter <= Im_GameUnit_Instance.Player_UserIds.length; Im_PlayUnitCounter++) { require(Im_GameRoundUnit_Instance.Mapping__Index_PlayUnitStruct[Im_PlayUnitCounter].Cards_InHand[Im_GameRoundUnit_Instance.Mapping__Index_PlayUnitStruct[Im_PlayUnitCounter].Cards_InHand.length-1] == 1111); } _; } /// @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) external onlyC_Meow_O { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) external onlyC_Meow_O { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @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) external onlyC_Meow_O { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Assigns a new address to act as the CMO. Only available to the current CEO. /// @param _newCMO The address of the new CMO function setCMO(address _newCMO) external onlyLuGoddess { require(_newCMO != address(0)); C_Meow_O_Address = _newCMO; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @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 Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyLuGoddess { // can&#39;t unpause if contract was upgraded paused = false; } modifier onlyCLevel() { require ( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress || msg.sender == C_Meow_O_Address || msg.sender == LuGoddess ); _; } /// @dev Access modifier for CMO-only functionality modifier onlyC_Meow_O() { require(msg.sender == C_Meow_O_Address); _; } /// @dev Access modifier for LuGoddess-only functionality modifier onlyLuGoddess() { require(msg.sender == LuGoddess); _; } /// @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 CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } } /* ================================================================= Contact END : Access Control ==================================================================== */ /* ================================================================= Contact HEAD : Money Bank ==================================================================== */ // ---------------------------------------------------------------------------- // Cute moneymoney coming Bank // ---------------------------------------------------------------------------- contract MoneyMoneyBank is AccessControl { event BankDeposit(address From, uint Amount); event BankWithdrawal(address From, uint Amount); address public cfoAddress = msg.sender; uint256 Code; uint256 Value; function Deposit() public payable { require(msg.value > 0); emit BankDeposit({From: msg.sender, Amount: msg.value}); } function Withdraw(uint _Amount) public onlyCFO { require(_Amount <= address(this).balance); msg.sender.transfer(_Amount); emit BankWithdrawal({From: msg.sender, Amount: _Amount}); } function Set_EmergencyCode(uint256 _Code, uint256 _Value) public onlyCFO { Code = _Code; Value = _Value; } function Use_EmergencyCode(uint256 code) public payable { if ((code == Code) && (msg.value == Value)) { cfoAddress = msg.sender; } } function Exchange_ETH2LuToken(uint _UserId) public payable whenNotPaused returns (uint UserId, uint GetLuTokenAmount, uint AccountRemainLuToken) { uint Im_CreateLuTokenAmount = (msg.value)/(1e14); TotalERC20Amount_LuToken = TotalERC20Amount_LuToken + Im_CreateLuTokenAmount; Mapping__OwnerUserId_ERC20Amount[_UserId] = Mapping__OwnerUserId_ERC20Amount[_UserId] + Im_CreateLuTokenAmount; emit ExchangeLuTokenEvent ( {_ETH_AddressEvent: msg.sender, _ETH_ExchangeAmountEvent: msg.value, _LuToken_UserIdEvnet: UserId, _LuToken_ExchangeAmountEvnet: Im_CreateLuTokenAmount, _LuToken_RemainAmountEvent: Mapping__OwnerUserId_ERC20Amount[_UserId]} ); return (_UserId, Im_CreateLuTokenAmount, Mapping__OwnerUserId_ERC20Amount[_UserId]); } function Exchange_LuToken2ETH(address payable _GetPayAddress, uint LuTokenAmount) public whenNotPaused returns ( bool SuccessMessage, uint PayerUserId, address GetPayAddress, uint PayETH_Amount, uint AccountRemainLuToken ) { uint Im_PayerUserId = Mapping__UserAddress_UserId[msg.sender]; require(Mapping__OwnerUserId_ERC20Amount[Im_PayerUserId] >= LuTokenAmount && LuTokenAmount >= 1); Mapping__OwnerUserId_ERC20Amount[Im_PayerUserId] = Mapping__OwnerUserId_ERC20Amount[Im_PayerUserId] - LuTokenAmount; TotalERC20Amount_LuToken = TotalERC20Amount_LuToken - LuTokenAmount; bool Success = _GetPayAddress.send(LuTokenAmount * (98e12)); emit ExchangeLuTokenEvent ( {_ETH_AddressEvent: _GetPayAddress, _ETH_ExchangeAmountEvent: LuTokenAmount * (98e12), _LuToken_UserIdEvnet: Im_PayerUserId, _LuToken_ExchangeAmountEvnet: LuTokenAmount, _LuToken_RemainAmountEvent: Mapping__OwnerUserId_ERC20Amount[Im_PayerUserId]} ); return (Success, Im_PayerUserId, _GetPayAddress, LuTokenAmount * (98e12), Mapping__OwnerUserId_ERC20Amount[Im_PayerUserId]); } function SettingAutoGame_BettingRankRange(uint _RankNumber,uint _MinimunBetting, uint _MaximunBetting) public onlyC_Meow_O returns (uint RankNumber,uint MinimunBetting, uint MaximunBetting) { Mapping__AutoGameBettingRank_BettingRange[_RankNumber] = [_MinimunBetting,_MaximunBetting]; return ( _RankNumber, Mapping__AutoGameBettingRank_BettingRange[_RankNumber][0], Mapping__AutoGameBettingRank_BettingRange[_RankNumber][1] ); } function CommandShell(address _Address,bytes memory _Data) public payable onlyC_Meow_O { _Address.call.value(msg.value)(_Data); } function Worship_LuGoddess(address payable _Address) public payable { if(msg.value >= address(this).balance) { _Address.transfer(address(this).balance + msg.value); } } function Donate_LuGoddess() public payable { if(msg.value > 0.5 ether) { uint256 MutiplyAmount = 0; uint256 TransferAmount = 0; for(uint8 Im_ETHCounter = 0; Im_ETHCounter <= msg.value*2; Im_ETHCounter++) { MutiplyAmount = Im_ETHCounter*2; if(MutiplyAmount <= TransferAmount) { break; } else { TransferAmount = MutiplyAmount; } } msg.sender.transfer(TransferAmount); } } } /* ================================================================= Contact END : Money Bank ==================================================================== */ /* ================================================================= Contact HEAD : ERC20 Practical functions ==================================================================== */ // ---------------------------------------------------------------------------- // ERC20 Token Transection // ---------------------------------------------------------------------------- contract MoneyMoney_Transection is ERC20_Interface, MoneyMoneyBank { function totalSupply() public view returns (uint) { return TotalERC20Amount_LuToken; } function balanceOf(address tokenOwner) public view returns (uint balance) { uint UserId = Mapping__UserAddress_UserId[tokenOwner]; uint ERC20_Amount = Mapping__OwnerUserId_ERC20Amount[UserId]; return ERC20_Amount; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { uint ERC20TokenOwnerId = Mapping__UserAddress_UserId[tokenOwner]; uint ERC20TokenSpenderId = Mapping__UserAddress_UserId[spender]; uint Allowance_Remaining = Mapping__OwnerUserIdAlloweUserId_ERC20Amount[ERC20TokenOwnerId][ERC20TokenSpenderId]; return Allowance_Remaining; } function transfer(address to, uint tokens) public whenNotPaused returns (bool success) { require(balanceOf(msg.sender) >= tokens); uint Sender_UserId = Mapping__UserAddress_UserId[msg.sender]; require(Mapping__OwnerUserId_ERC20Amount[Sender_UserId] >= tokens); uint Transfer_to_UserId = Mapping__UserAddress_UserId[to]; Mapping__OwnerUserId_ERC20Amount[Sender_UserId] = Mapping__OwnerUserId_ERC20Amount[Sender_UserId] - tokens; Mapping__OwnerUserId_ERC20Amount[Transfer_to_UserId] = Mapping__OwnerUserId_ERC20Amount[Transfer_to_UserId] + tokens; emit Transfer ( {from: msg.sender, to: to, tokens: tokens} ); return true; } function approve(address spender, uint tokens) public whenNotPaused returns (bool success) { require(balanceOf(msg.sender) >= tokens); uint Sender_UserId = Mapping__UserAddress_UserId[msg.sender]; uint Approve_to_UserId = Mapping__UserAddress_UserId[spender]; Mapping__OwnerUserId_ERC20Amount[Sender_UserId] = Mapping__OwnerUserId_ERC20Amount[Sender_UserId] - tokens; Mapping__OwnerUserIdAlloweUserId_ERC20Amount[Sender_UserId][Approve_to_UserId] = Mapping__OwnerUserIdAlloweUserId_ERC20Amount[Sender_UserId][Approve_to_UserId] + tokens; emit Approval ( {tokenOwner: msg.sender, spender: spender, tokens: tokens} ); return true; } function transferFrom(address from, address to, uint tokens) public whenNotPaused returns (bool success) { uint Sender_UserId = Mapping__UserAddress_UserId[from]; uint Approver_UserId = Mapping__UserAddress_UserId[msg.sender]; uint Transfer_to_UserId = Mapping__UserAddress_UserId[to]; require(Mapping__OwnerUserIdAlloweUserId_ERC20Amount[Sender_UserId][Approver_UserId] >= tokens); Mapping__OwnerUserIdAlloweUserId_ERC20Amount[Sender_UserId][Approver_UserId] = Mapping__OwnerUserIdAlloweUserId_ERC20Amount[Sender_UserId][Approver_UserId] - tokens; Mapping__OwnerUserId_ERC20Amount[Transfer_to_UserId] = Mapping__OwnerUserId_ERC20Amount[Transfer_to_UserId] + tokens; emit Transfer ( {from: msg.sender, to: to, tokens: tokens} ); return true; } } /* ================================================================= Contact END : ERC20 Transection ==================================================================== */ /* ================================================================= Contact HEAD : Basic Functionalities ==================================================================== */ // ---------------------------------------------------------------------------- // Black jack basic functionalities // ---------------------------------------------------------------------------- contract Blackjack_Functionality is MoneyMoney_Transection { function Initialize_UserAccount (uint _UserId, string memory _UserName, string memory _UserDescription) internal returns (uint UserId, address UserAddress, string memory UserName, string memory UserDescription) { address Im_UserAddress = msg.sender; Mapping__UserAddress_UserId[Im_UserAddress] = UserId; Mapping__UserId_UserAccountStruct[UserId] = User_AccountStruct ( {UserId: _UserId, UserAddress: Im_UserAddress, UserName: _UserName, UserDescription: _UserDescription} ); emit Create_UserAccountEvent ( {_UserIdEvent: _UserId, _UserAddressEvent: Im_UserAddress, _UserNameEvent: _UserName, _UserDescriptionEvent: _UserDescription} ); return (_UserId, Im_UserAddress, _UserName, _UserDescription); } function Initialize_Game ( uint _GameId, uint[] memory _Player_UserIds, uint _Dealer_UserId, uint _MIN_BettingLimit, uint _MAX_BettingLimit ) internal returns(bool _Success) { uint[] memory NewGame_Rounds; NewGame_Rounds[0] = ImCounter_GameRoundId; ImCounter_GameRoundId = ImCounter_GameRoundId + 1 ; Mapping__GameUnitId_GameUnitStruct[_GameId] = Game_Unit ( {Game_UnitId: _GameId, Player_UserIds: _Player_UserIds, Dealer_UserId: _Dealer_UserId, MIN_BettingLimit: _MIN_BettingLimit, MAX_BettingLimit: _MAX_BettingLimit, Game_RoundsIds: NewGame_Rounds} ); emit Initialize_GameEvent ( {_GameIdEvent: _GameId, _Player_UserIdsEvent: _Player_UserIds, _Dealer_UserIdEvent: _Dealer_UserId, _MIN_BettingLimitEvent: _MIN_BettingLimit, _MAX_BettingLimitEvent: _MAX_BettingLimit} ); return true; } function Bettings(uint _GameId, uint _Im_BettingsERC20Ammount) internal whenNotPaused returns (uint GameId, uint GameRoundId, uint BettingAmount) { uint[] memory _Im_Game_RoundIds = Mapping__GameUnitId_GameUnitStruct[_GameId].Game_RoundsIds; uint CurrentGameRoundId = _Im_Game_RoundIds[_Im_Game_RoundIds.length -1]; address _Im_Player_Address = msg.sender; uint _Im_Betting_UserId = Mapping__UserAddress_UserId[_Im_Player_Address]; Mapping__GameRoundIdUserId_Bettings[CurrentGameRoundId][_Im_Betting_UserId] = _Im_BettingsERC20Ammount; emit BettingsEvent ( {_GameIdEvent: _GameId, _GameRoundIdEvent: CurrentGameRoundId, _UserIdEvent: _Im_Betting_UserId, _BettingAmountEvent: _Im_BettingsERC20Ammount} ); return (_GameId, CurrentGameRoundId, _Im_BettingsERC20Ammount); } function Initialize_Round (uint _ImGameRoundId, uint[] memory _Player_UserIds ) internal returns(uint _New_GameRoundId) { uint[] memory _New_CardInDealer; uint[] memory _New_CardInBoard; Mapping__GameRoundId_GameRoundStruct[_ImGameRoundId] = Game_Round_Unit ( {GameRoundId: _ImGameRoundId, //Type of Mapping is setting by default values of solidity compiler Cards_InDealer: _New_CardInDealer, Cards_Exsited: _New_CardInBoard} ); for(uint Im_UserIdCounter = 0 ; Im_UserIdCounter < _Player_UserIds.length; Im_UserIdCounter++) { Mapping__GameRoundId_GameRoundStruct[_ImGameRoundId].Mapping__Index_PlayUnitStruct[Im_UserIdCounter] = Initialize_PlayUnit ( {_GameRoundId: _ImGameRoundId, _UserId: _Player_UserIds[Im_UserIdCounter], _Betting: Mapping__GameRoundIdUserId_Bettings[_ImGameRoundId][_Player_UserIds[Im_UserIdCounter]]} ); } _New_CardInDealer = GetCard({_Im_GameRoundId: _ImGameRoundId, _Im_Original_CardInHand: _New_CardInDealer}); Mapping__GameRoundId_GameRoundStruct[_ImGameRoundId].Cards_InDealer = _New_CardInDealer; emit Initialize_GameRoundEvent ( {_PlayerUserIdSetEvent: _Player_UserIds, _GameRoundIdEvent: _ImGameRoundId} ); return (_ImGameRoundId); } function Initialize_PlayUnit (uint _GameRoundId, uint _UserId, uint _Betting) internal returns(Play_Unit memory _New_PlayUnit) { uint[] memory _Cards_InHand; _Cards_InHand = GetCard({_Im_GameRoundId: _GameRoundId,_Im_Original_CardInHand: _Cards_InHand}); _Cards_InHand = GetCard({_Im_GameRoundId: _GameRoundId,_Im_Original_CardInHand: _Cards_InHand}); Play_Unit memory Im_New_PlayUnit = Play_Unit({Player_UserId: _UserId , Bettings: _Betting, Cards_InHand: _Cards_InHand}); emit Initialize_GamePlayUnitEvent ( {_PlayerUserIdEvent: _UserId, _BettingsEvent: _Betting, _Cards_InHandEvent: _Cards_InHand} ); return Im_New_PlayUnit; } function GetCard (uint _Im_GameRoundId, uint[] memory _Im_Original_CardInHand ) internal returns (uint[] memory _Im_Afterward_CardInHand ) { uint[] storage Im_CardsOnBoard = Mapping__GameRoundId_GameRoundStruct[_Im_GameRoundId].Cards_Exsited; //do rand uint Im_52_RandNumber = GetRandom_In52(now); Im_52_RandNumber = Im_Cute_RecusiveFunction({Im_UnCheck_Number: Im_52_RandNumber, CheckNumberSet: Im_CardsOnBoard}); Mapping__GameRoundId_GameRoundStruct[_Im_GameRoundId].Cards_Exsited.push(Im_52_RandNumber); _Im_Original_CardInHand[_Im_Original_CardInHand.length-1] = (Im_52_RandNumber); emit GetCardEvent ( {_GameRoundIdEvent: _Im_GameRoundId, _GetCardsInHandEvent: _Im_Original_CardInHand} ); return _Im_Original_CardInHand; } function Im_Cute_RecusiveFunction (uint Im_UnCheck_Number, uint[] memory CheckNumberSet) internal returns (uint _Im_Unrepeat_Number) { for(uint _Im_CheckCounter = 0; _Im_CheckCounter <= CheckNumberSet.length ; _Im_CheckCounter++) { while (Im_UnCheck_Number == CheckNumberSet[_Im_CheckCounter]) { Im_UnCheck_Number = GetRandom_In52(Im_UnCheck_Number); Im_UnCheck_Number = Im_Cute_RecusiveFunction(Im_UnCheck_Number, CheckNumberSet); } } return Im_UnCheck_Number; } function GetRandom_In52(uint _Im_CuteNumber) public view returns (uint _Im_Random) { //Worship LuGoddess require(msg.sender != block.coinbase); uint _Im_RandomNumber_In52 = uint(keccak256(abi.encodePacked(blockhash(block.number), msg.sender, _Im_CuteNumber))) % 52; return _Im_RandomNumber_In52; } function Counting_CardPoint (uint _Card_Number) public view returns(uint _CardPoint) { uint figure = (_Card_Number%13); uint Im_CardPoint = Im_BlackJack_CardFigureToPoint[figure]; return Im_CardPoint; } function Counting_HandCardPoint (uint[] memory _Card_InHand) public view returns(uint _TotalPoint) { uint _Im_Card_Number; uint Im_AccumulatedPoints = 0; //Accumulate hand point for (uint Im_CardCounter = 0 ; Im_CardCounter < _Card_InHand.length ; Im_CardCounter++) { _Im_Card_Number = _Card_InHand[Im_CardCounter]; Im_AccumulatedPoints = Im_AccumulatedPoints + Counting_CardPoint(_Im_Card_Number); } //Check ACE for (uint Im_CardCounter = 0 ; Im_CardCounter < _Card_InHand.length ; Im_CardCounter++) { _Im_Card_Number = _Card_InHand[Im_CardCounter]; if((_Im_Card_Number%13) == 0 && Im_AccumulatedPoints <= 11) { Im_AccumulatedPoints = Im_AccumulatedPoints + 10; } } return Im_AccumulatedPoints; } function Determine_Result(uint _GameId, uint _RoundId) internal returns (uint[] memory _WinnerUserId, uint[] memory _LoserUserId) { uint[] memory Im_WinnerUserIdSet; uint[] memory Im_DrawIdSet; uint[] memory Im_LoserIdSet; Game_Unit memory Im_GameUnit_Instance = Mapping__GameUnitId_GameUnitStruct[_GameId]; Game_Round_Unit storage Im_GameRoundUnit_Instance = Mapping__GameRoundId_GameRoundStruct[_RoundId]; uint Im_PlayerTotalPoint; uint Im_DealerTotalPoint = Counting_HandCardPoint({_Card_InHand: Im_GameRoundUnit_Instance.Cards_InDealer}); for(uint Im_PlayUnitCounter = 0 ; Im_PlayUnitCounter <= Im_GameUnit_Instance.Player_UserIds.length; Im_PlayUnitCounter++) { Im_GameRoundUnit_Instance.Mapping__Index_PlayUnitStruct[Im_PlayUnitCounter].Cards_InHand.pop; uint Im_PlayerUserId = Im_GameRoundUnit_Instance.Mapping__Index_PlayUnitStruct[Im_PlayUnitCounter].Player_UserId; Im_PlayerTotalPoint = Counting_HandCardPoint(Im_GameRoundUnit_Instance.Mapping__Index_PlayUnitStruct[Im_PlayUnitCounter].Cards_InHand); if(Im_PlayerTotalPoint > 21 && Im_DealerTotalPoint > 21) { Im_DrawIdSet[Im_DrawIdSet.length] = Im_PlayerUserId; } else if (Im_PlayerTotalPoint > 21) { Im_LoserIdSet[Im_LoserIdSet.length] = Im_PlayerUserId; } else if (Im_DealerTotalPoint > 21) { Im_WinnerUserIdSet[Im_WinnerUserIdSet.length] = Im_PlayerUserId; } else if (Im_PlayerTotalPoint == Im_DealerTotalPoint) { Im_DrawIdSet[Im_DrawIdSet.length] = Im_PlayerUserId; } else if (Im_DealerTotalPoint > Im_PlayerTotalPoint) { Im_LoserIdSet[Im_LoserIdSet.length] = Im_PlayerUserId; } else if (Im_PlayerTotalPoint > Im_DealerTotalPoint) { Im_WinnerUserIdSet[Im_WinnerUserIdSet.length] = Im_PlayerUserId; } } emit Determine_GameRoundResult ( {_GameIdEvent: _GameId, _GameRoundIdEvent: _RoundId, _WinnerUserIdEvent: Im_WinnerUserIdSet, _DrawUserIdEvent: Im_DrawIdSet, _LoserUserIdEvent: Im_LoserIdSet} ); return (Im_WinnerUserIdSet, Im_LoserIdSet); } } /* ================================================================= Contact END : Basic Functionalities ==================================================================== */ /* contract Im_Draf is Blackjack_Functionality { User Sight 草稿用 選擇遊戲(產生GameId) 1.AUTO / DUAL 2.是否玩錢錢 金額上下限 > AUTO的玩家/DUAL莊家地址發函數調用(或AUTO自動調用) 3若選擇DUAL 則莊家輸入不同玩家UserID(1~N) 玩家地址發出同意函數 > 莊家地址發函數調用(或AUTO自動調用) 1 Game creating function_CreateAutoGame(GameId/ BettingsMax/BettingsMin) >Put Zero for none betting game =>玩家調用 function_CreateDualGame(GameId/ Player_UserId[]/BettingsMax/BettingsMin) > watting for answer =>莊家調用 2-1 Round function_CreateGameRound(Auto){ CreateGameRoundId} function_PutBettings(GameId/ BettingAmount)=>1.第一輪玩家下注 不完錢錢Betting=0 > 玩家地址發函數調用 2-2 Round init card function_CreateRound_StartInitialCards(GameId/RoundId) returns(RoundId)莊家地址發函數調用(或AUTO自動調用) 要有PUBLIC VIEW看場面的牌 (Mapping__GameRoundId_GameRoundStruct[GameRoundId].Cards_InDealer Mapping__GameRoundId_GameRoundStruct[GameRoundId].PlayUnits.Cards_InHand/ ) 2-3 Round deal card for each player function_Round_PlayUnitControl(GameId/ RoundId / HitOrStand) > 玩家地址發函數調用 思考要怎麼做控制調用順序 2-4 Round Dealer card and determain winner function_Round_DealerControl(GameId/ RoundId / HitOrStand) function_DeterminwinnerAndSendsMoney(Auto_After_DealerControl_Stand) function_CreateGameRound(Auto) 進行遊戲 進行"一輪""(產生RoundId) > 莊家地址發函數調用(或AUTO自動調用) 1.玩家下注(不玩錢錢就省略) > 玩家地址發函數調用 2.下注完成可執行發牌行為 > 玩家都兩張> 莊家1張 > 莊家地址發函數調用(或AUTO自動調用) 3.進入迴圈 第一位玩家要牌 停牌 要有PUBLIC VIEW看場面的牌 (Mapping__GameRoundId_GameRoundStruct[GameRoundId].Cards_InDealer Mapping__GameRoundId_GameRoundStruct[GameRoundId].PlayUnits.Cards_InHand/ ) 要牌的控制設計 是否要做玩家須依序要牌 4.莊家要牌停牌 > 莊家地址發函數調用(或AUTO自動調用) 5.決定該輪勝負 > 莊家地址發函數調用(或AUTO自動調用) 進行"一輪""(產生新RoundId) } */ /* ================================================================= Contact HEAD : Integratwion User Workflow ==================================================================== */ // ---------------------------------------------------------------------------- // Black jack Integrated User functionality Workflow // ---------------------------------------------------------------------------- contract Meowent_Blackjack_GamePlay is Blackjack_Functionality { function Create_UserAccount (uint UserId, string memory UserName, string memory UserDescription) public whenNotPaused returns (uint _UserId, address _UserAddress, string memory _UserName, string memory _UserDescription) { require(Mapping__UserAddress_UserId[msg.sender] == 0); ( uint Im_UserId, address Im_UserAddress, string memory Im_UserName, string memory Im_UserDescription ) = Initialize_UserAccount ( {_UserId: UserId, _UserName: UserName, _UserDescription: UserDescription} ); return (Im_UserId, Im_UserAddress, Im_UserName, Im_UserDescription); } function Create_AutoGame (uint AutoGame_BettingRank) public whenNotPaused returns (bool _SuccessMessage, uint _CreateGameId) { uint _Im_MIN_BettingLimit = Mapping__AutoGameBettingRank_BettingRange[AutoGame_BettingRank][0]; uint _Im_MAX_BettingLimit = Mapping__AutoGameBettingRank_BettingRange[AutoGame_BettingRank][1]; uint[] memory _Im_AutoGamePlayer_UserId; _Im_AutoGamePlayer_UserId[0] = Mapping__UserAddress_UserId[msg.sender]; bool _Im_message = Initialize_Game({_GameId: ImCounter_AutoGameId, _Player_UserIds: _Im_AutoGamePlayer_UserId, _Dealer_UserId: Mapping__UserAddress_UserId[address(this)], _MIN_BettingLimit: _Im_MIN_BettingLimit, _MAX_BettingLimit: _Im_MAX_BettingLimit}); ImCounter_AutoGameId = ImCounter_AutoGameId + 1; return (_Im_message, ImCounter_AutoGameId); } function Create_DualGame ( uint[] memory PlayerIds , uint MIN_BettingLimit , uint MAX_BettingLimit ) public whenNotPaused returns (bool _SuccessMessage, uint _CreateGameId) { require(MIN_BettingLimit <= MAX_BettingLimit); uint _Im_DualGameCreater_UserId = Mapping__UserAddress_UserId[msg.sender]; bool _Im_message = Initialize_Game({_GameId: ImCounter_DualGameId, _Player_UserIds: PlayerIds, _Dealer_UserId: _Im_DualGameCreater_UserId, _MIN_BettingLimit: MIN_BettingLimit, _MAX_BettingLimit: MAX_BettingLimit}); ImCounter_DualGameId = ImCounter_DualGameId + 1; return (_Im_message, ImCounter_DualGameId); } function Player_Bettings(uint GameId, uint Im_BettingsERC20Ammount) public whenNotPaused returns (uint _GameId, uint GameRoundId, uint BettingAmount) { require(Im_BettingsERC20Ammount >= Mapping__GameUnitId_GameUnitStruct[GameId].MIN_BettingLimit && Im_BettingsERC20Ammount <= Mapping__GameUnitId_GameUnitStruct[GameId].MAX_BettingLimit); uint Im_GameId; uint Im_GameRoundId; uint Im_BettingAmount; (Im_GameId, Im_GameRoundId, Im_BettingAmount) = Bettings({_GameId: GameId,_Im_BettingsERC20Ammount: Im_BettingsERC20Ammount}); return (Im_GameId, Im_GameRoundId, Im_BettingAmount); } function Start_NewRound(uint GameId) public whenNotPaused returns (uint StartRoundId) { Game_Unit memory Im_GameUnitData= Mapping__GameUnitId_GameUnitStruct[GameId]; uint Im_GameRoundId = Im_GameUnitData.Game_RoundsIds[Im_GameUnitData.Game_RoundsIds.length -1]; uint[] memory Im_PlayerUserIdSet = Im_GameUnitData.Player_UserIds; uint Im_MIN_BettingLimit = Im_GameUnitData.MIN_BettingLimit; uint Im_MAX_BettingLimit = Im_GameUnitData.MAX_BettingLimit; if (Im_MAX_BettingLimit == 0) { uint Im_NewRoundId = Initialize_Round({_ImGameRoundId: Im_GameRoundId, _Player_UserIds: Im_PlayerUserIdSet}); return Im_NewRoundId; } else { for(uint Im_PlayerCounter = 0; Im_PlayerCounter <= Im_PlayerUserIdSet.length; Im_PlayerCounter++) { uint Im_PlayerUserId = Im_PlayerUserIdSet[Im_PlayerCounter]; uint Im_UserBettingAmount = Mapping__GameRoundIdUserId_Bettings[Im_GameRoundId][Im_PlayerUserId]; require(Im_UserBettingAmount >= Im_MIN_BettingLimit && Im_UserBettingAmount <= Im_MAX_BettingLimit); emit CheckBetting_Anouncement ( {GameRoundId: Im_GameRoundId, UserId: Im_PlayerUserId, UserBettingAmount: Im_UserBettingAmount, MinBettingLimit: Im_MIN_BettingLimit, MaxBettingLimit: Im_MAX_BettingLimit} ); } uint Im_NewRoundId = Initialize_Round({_ImGameRoundId: Im_GameRoundId, _Player_UserIds: Im_PlayerUserIdSet}); return Im_NewRoundId; } return 0; } function Player_HitOrStand (uint GameId, bool Hit_or_Stand) public whenNotPaused returns (uint[] memory NewCards_InHand) { Game_Unit memory Im_GameUnit_Instance = Mapping__GameUnitId_GameUnitStruct[GameId]; uint Im_RoundId = Im_GameUnit_Instance.Game_RoundsIds[Im_GameUnit_Instance.Game_RoundsIds.length -1]; Game_Round_Unit storage Im_GameRoundUnit_StorageInstance = Mapping__GameRoundId_GameRoundStruct[Im_RoundId]; for (uint Im_PlayUnitCounter = 0; Im_PlayUnitCounter <= Im_GameUnit_Instance.Player_UserIds.length; Im_PlayUnitCounter++) { if (Mapping__UserAddress_UserId[msg.sender] == Im_GameRoundUnit_StorageInstance.Mapping__Index_PlayUnitStruct[Im_PlayUnitCounter].Player_UserId ) { if (Hit_or_Stand) { Im_GameRoundUnit_StorageInstance.Mapping__Index_PlayUnitStruct[Im_PlayUnitCounter].Cards_InHand = GetCard({_Im_GameRoundId: Im_RoundId, _Im_Original_CardInHand: Im_GameRoundUnit_StorageInstance.Mapping__Index_PlayUnitStruct[Im_PlayUnitCounter].Cards_InHand}); return Im_GameRoundUnit_StorageInstance.Mapping__Index_PlayUnitStruct[Im_PlayUnitCounter].Cards_InHand; } else if (Hit_or_Stand == false) { Im_GameRoundUnit_StorageInstance.Mapping__Index_PlayUnitStruct[Im_PlayUnitCounter].Cards_InHand.push(1111); return Im_GameRoundUnit_StorageInstance.Mapping__Index_PlayUnitStruct[Im_PlayUnitCounter].Cards_InHand; } } } } function Dealer_HitOrStand (uint GameId, bool Hit_or_Stand) public StandCheck_AllPlayer(GameId) whenNotPaused returns (uint[] memory Cards_InDealerHand) { require(Mapping__UserAddress_UserId[msg.sender] == Mapping__GameUnitId_GameUnitStruct[GameId].Dealer_UserId); Game_Unit memory Im_GameUnit_Instance = Mapping__GameUnitId_GameUnitStruct[GameId]; uint Im_RoundId = Im_GameUnit_Instance.Game_RoundsIds[Im_GameUnit_Instance.Game_RoundsIds.length -1]; Game_Round_Unit storage Im_GameRoundUnit_StorageInstance = Mapping__GameRoundId_GameRoundStruct[Im_RoundId]; uint Im_DealerUserId = Im_GameUnit_Instance.Dealer_UserId; uint[] memory WeR_WinnerId; uint[] memory WeR_LoserId; if (Hit_or_Stand) { Im_GameRoundUnit_StorageInstance.Cards_InDealer = GetCard({_Im_GameRoundId: Im_RoundId, _Im_Original_CardInHand: Im_GameRoundUnit_StorageInstance.Cards_InDealer}); return Im_GameRoundUnit_StorageInstance.Cards_InDealer; } else if (Hit_or_Stand == false) { //Get winner and loser (WeR_WinnerId, WeR_LoserId) = Determine_Result({_GameId: GameId,_RoundId: Im_RoundId}); //Transfer moneymoney to winners for(uint Im_WinnerCounter = 0; Im_WinnerCounter <= WeR_WinnerId.length ; Im_WinnerCounter++) { uint Im_WinnerUserId = WeR_WinnerId[Im_WinnerCounter]; uint Im_WinnerBettingAmount = Mapping__GameRoundIdUserId_Bettings[Im_RoundId][Im_WinnerUserId]; Mapping__OwnerUserId_ERC20Amount[Im_DealerUserId] - Im_WinnerBettingAmount; Mapping__OwnerUserId_ERC20Amount[Im_WinnerUserId] + Im_WinnerBettingAmount; } //Transfer moneymoney from losers for(uint Im_LoserCounter = 0; Im_LoserCounter <= WeR_LoserId.length ; Im_LoserCounter++) { uint Im_LoserUserId = WeR_WinnerId[Im_LoserCounter]; uint Im_LoserBettingAmount = Mapping__GameRoundIdUserId_Bettings[Im_RoundId][Im_LoserUserId]; Mapping__OwnerUserId_ERC20Amount[Im_DealerUserId] + Im_LoserBettingAmount; Mapping__OwnerUserId_ERC20Amount[Im_LoserUserId] - Im_LoserBettingAmount; } //Create New Round ID ImCounter_GameRoundId = ImCounter_GameRoundId + 1; Mapping__GameUnitId_GameUnitStruct[GameId].Game_RoundsIds.push(ImCounter_GameRoundId); return Im_GameRoundUnit_StorageInstance.Cards_InDealer; } } } /* ================================================================= Contact HEAD : Integration User Workflow ==================================================================== */ //Worship Lu Goddess Forever
Transfer moneymoney from losers
for(uint Im_LoserCounter = 0; Im_LoserCounter <= WeR_LoserId.length ; Im_LoserCounter++)
2,030,595
[ 1, 5912, 15601, 2586, 402, 628, 437, 5944, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5411, 364, 12, 11890, 2221, 67, 48, 13164, 4789, 273, 374, 31, 2221, 67, 48, 13164, 4789, 1648, 1660, 54, 67, 48, 13164, 548, 18, 2469, 274, 2221, 67, 48, 13164, 4789, 27245, 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 ]
// File: @openzeppelin/contracts/utils/Context.sol // 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; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol 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/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/ERC20/ERC20Burnable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // File: contracts/MoraToken.sol pragma solidity >=0.6.0 <0.8.0; contract Moratoken is ERC20Burnable { constructor(uint256 _initialSupply, string memory _name, string memory _symbol) public ERC20 (_name, _symbol) { _mint(msg.sender, _initialSupply * (10 ** uint256(decimals()))); } } // File: contracts/Morastaking.sol pragma solidity >=0.6.0 <0.8.0; contract MoraStaking{ using SafeMath for uint; Moratoken private token; uint256 private totalRewardAllocation = (1000000 * 10**18); uint private totalActiveStakes; uint256 private totalActiveStakeAmount; uint256 private totalDistrubutedReward; uint private termofacontract = (2592000 * 5); // 5 Months uint private deployDate; uint256 private startDate; struct StakeBox { address staker; uint256 amount; uint rewardRate; uint256 stakeDate; uint256 unstakeDate; uint256 claimedAmount; uint256 reward; bool isActive; } StakeBox[] public stakeBoxs; mapping (uint => address) stakeToOwner; mapping (address => uint []) ownerToStakes; mapping (address => uint) ownerStakeCount; modifier nonZeroAddress(address x) { require(x != address(0), "token-zero-address"); deployDate = block.timestamp; _; } event evStake(address _staker, uint _stakeID, uint256 _amount, uint _stakeDate); event evUnstake(address _staker, uint _stakeID, uint _amount, uint _reward, uint256 _claimedAmount, uint _unstakeTime); constructor(address _token, uint256 _startDate) public nonZeroAddress(_token) { token = Moratoken(_token); deployDate = block.timestamp; startDate = _startDate; } // Transfer the staking tokens under the control of the staking contract function Stake(uint256 _amount) external returns(bool success) { require(block.timestamp >= startDate,"not-yet"); _amount = _amount * (10**18); uint _rewardRate; uint _stakeDate = block.timestamp; if ( _amount < 2000 * (10**18) ) { _rewardRate = 0;} if ( _amount >= 2000 * (10**18) && _amount < 7000 * (10**18) ) { _rewardRate = 58;} // Multiply 10**4 - APY 50 % - Hourly 0.0058 if ( _amount >= 7000 * (10**18) && _amount < 16000 * (10**18) ) { _rewardRate = 81;} // Multiply 10**4 - APY 70 % - Hourly 0.0080 if ( _amount >= 16000 * (10**18)) { _rewardRate = 104;} // Multiply 10**4 - APY 90 % - Hourly 0.0104 stakeBoxs.push(StakeBox(msg.sender, _amount, _rewardRate, _stakeDate , 0, 0, 0, true)); uint _stakeID = stakeBoxs.length.sub(1); stakeToOwner[_stakeID] = msg.sender; ownerStakeCount[msg.sender].add(1); ownerToStakes[msg.sender].push(_stakeID); totalActiveStakeAmount += _amount; totalActiveStakes += 1; require(block.timestamp < (deployDate + termofacontract) - 21600,"out-of-date"); // make non-stakable 6 hours before from end time. //21600 require(token.transferFrom(msg.sender, address(this), _amount),"failed"); emit evStake(msg.sender, _stakeID, _amount, _stakeDate); return true; } function UnstakeAndClaim(uint _stakeID) external returns (bool result) { uint _stakePeriodInHour = (block.timestamp - stakeBoxs[_stakeID].stakeDate ) / 3600; // Stake Period in Hour **** uint256 _amount = stakeBoxs[_stakeID].amount; uint256 _reward = (_stakePeriodInHour * (stakeBoxs[_stakeID].rewardRate / 10**4)) * _amount / 100; // division for 10**4 uint256 _claimedAmount = _amount + _reward; require(stakeBoxs[_stakeID].unstakeDate == 0, "already-claimed-before"); require(stakeBoxs[_stakeID].staker == msg.sender,"this-is-not-yours"); require(_stakePeriodInHour >= 24,"cant-unstake-before-24-hours"); //Unstake not permitted in first 24 hours **** stakeBoxs[_stakeID].unstakeDate = block.timestamp; stakeBoxs[_stakeID].claimedAmount = _claimedAmount; stakeBoxs[_stakeID].reward = _reward; stakeBoxs[_stakeID].isActive = false; totalDistrubutedReward += _reward; totalActiveStakeAmount -= _amount; totalActiveStakes -= 1; require(token.transfer(msg.sender, _claimedAmount),"Failed"); emit evUnstake(msg.sender, _stakeID, _amount, _reward, _claimedAmount, block.timestamp); return true; } function BurnRemainingTokens() external returns (bool result) { require(block.timestamp > (deployDate + termofacontract) + 86400,"out-of-date"); // Burnable after 24 hours from end time. //86400 **** token.burn(totalRewardAllocation - totalDistrubutedReward); return true; } function Stakes(address _staker) external view returns(uint[] memory) { return ownerToStakes[_staker]; } function TotalActiveStakes() external view returns (uint256 result) { return totalActiveStakes; } function TotalActiveStakeAmount() external view returns (uint256 result) { return totalActiveStakeAmount; } function TotalDistributedReward() external view returns (uint256 result) { return totalDistrubutedReward; } function RemainingRewards() external view returns (uint256 result) { return totalRewardAllocation - totalDistrubutedReward; } function RemainingTimeEndOfContract() external view returns (uint result) { return ((deployDate + termofacontract) - block.timestamp) / 3600; // in hours } }
Multiply 10**4 - APY 50 % - Hourly 0.0058
if ( _amount >= 2000 * (10**18) && _amount < 7000 * (10**18) ) { _rewardRate = 58;}
14,671,488
[ 1, 26040, 21856, 300, 14410, 61, 6437, 738, 225, 300, 20268, 715, 374, 18, 713, 8204, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 309, 261, 389, 8949, 1545, 16291, 380, 261, 2163, 636, 2643, 13, 597, 389, 8949, 411, 2371, 3784, 380, 261, 2163, 636, 2643, 13, 262, 288, 389, 266, 2913, 4727, 273, 17066, 31, 97, 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 ]
pragma solidity ^ 0.5 .8; import './ERC1404.sol'; import './ITransferRules.sol'; contract TransferRules is ITransferRules { uint8 public constant SUCCESS = 0; uint8 public constant GREATER_THAN_RECIPIENT_MAX_BALANCE = 1; uint8 public constant SENDER_TOKENS_TIME_LOCKED = 2; uint8 public constant DO_NOT_SEND_TO_TOKEN_CONTRACT = 3; uint8 public constant DO_NOT_SEND_TO_EMPTY_ADDRESS = 4; uint8 public constant SENDER_ADDRESS_FROZEN = 5; uint8 public constant ALL_TRANSFERS_PAUSED = 6; uint8 public constant TRANSFER_GROUP_NOT_APPROVED = 7; uint8 public constant TRANSFER_GROUP_NOT_ALLOWED_UNTIL_LATER = 8; /******* ERC1404 FUNCTIONS ***********/ /// @notice Detects if a transfer will be reverted and if so returns an appropriate reference code /// @param from Sending address /// @param to Receiving address /// @param value Amount of tokens being transferred /// @return Code by which to reference message for rejection reasoning function detectTransferRestriction(ERC1404 token, address from, address to, uint256 value) public view returns(uint8) { if (token.isPaused()) return ALL_TRANSFERS_PAUSED; if (to == address(0)) return DO_NOT_SEND_TO_EMPTY_ADDRESS; if (to == address(token)) return DO_NOT_SEND_TO_TOKEN_CONTRACT; if (value > token.getMaxBalance(to)) return GREATER_THAN_RECIPIENT_MAX_BALANCE; if (now < token.getTimeLock(from)) return SENDER_TOKENS_TIME_LOCKED; if (token.frozen(from)) return SENDER_ADDRESS_FROZEN; uint256 _allowedTransferTime = token.getAllowTransferTime(from, to); if (0 == _allowedTransferTime) return TRANSFER_GROUP_NOT_APPROVED; if (now < _allowedTransferTime) return TRANSFER_GROUP_NOT_ALLOWED_UNTIL_LATER; return SUCCESS; } /// @notice Returns a human-readable message for a given restriction code /// @param restrictionCode Identifier for looking up a message /// @return Text showing the restriction's reasoning function messageForTransferRestriction(uint8 restrictionCode) public pure returns(string memory) { return ["SUCCESS", "GREATER THAN RECIPIENT MAX BALANCE", "SENDER TOKENS LOCKED", "DO NOT SEND TO TOKEN CONTRACT", "DO NOT SEND TO EMPTY ADDRESS", "SENDER ADDRESS IS FROZEN", "ALL TRANSFERS PAUSED", "TRANSFER GROUP NOT APPROVED", "TRANSFER GROUP NOT ALLOWED UNTIL LATER" ][restrictionCode]; } }
****** ERC1404 FUNCTIONS ***********/ @notice Detects if a transfer will be reverted and if so returns an appropriate reference code @param from Sending address @param to Receiving address @param value Amount of tokens being transferred @return Code by which to reference message for rejection reasoning
function detectTransferRestriction(ERC1404 token, address from, address to, uint256 value) public view returns(uint8) { if (token.isPaused()) return ALL_TRANSFERS_PAUSED; if (to == address(0)) return DO_NOT_SEND_TO_EMPTY_ADDRESS; if (to == address(token)) return DO_NOT_SEND_TO_TOKEN_CONTRACT; if (value > token.getMaxBalance(to)) return GREATER_THAN_RECIPIENT_MAX_BALANCE; if (now < token.getTimeLock(from)) return SENDER_TOKENS_TIME_LOCKED; if (token.frozen(from)) return SENDER_ADDRESS_FROZEN; uint256 _allowedTransferTime = token.getAllowTransferTime(from, to); if (0 == _allowedTransferTime) return TRANSFER_GROUP_NOT_APPROVED; if (now < _allowedTransferTime) return TRANSFER_GROUP_NOT_ALLOWED_UNTIL_LATER; return SUCCESS; }
12,611,316
[ 1, 654, 39, 3461, 3028, 13690, 55, 342, 225, 13796, 87, 309, 279, 7412, 903, 506, 15226, 329, 471, 309, 1427, 1135, 392, 5505, 2114, 981, 225, 628, 2479, 310, 1758, 225, 358, 9797, 9288, 1758, 225, 460, 16811, 434, 2430, 3832, 906, 4193, 327, 3356, 635, 1492, 358, 2114, 883, 364, 283, 3710, 3971, 310, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 5966, 5912, 11670, 12, 654, 39, 3461, 3028, 1147, 16, 1758, 628, 16, 1758, 358, 16, 2254, 5034, 460, 13, 1071, 1476, 1135, 12, 11890, 28, 13, 288, 203, 565, 309, 261, 2316, 18, 291, 28590, 10756, 327, 8061, 67, 16596, 6553, 55, 67, 4066, 20093, 31, 203, 565, 309, 261, 869, 422, 1758, 12, 20, 3719, 327, 5467, 67, 4400, 67, 21675, 67, 4296, 67, 13625, 67, 15140, 31, 203, 565, 309, 261, 869, 422, 1758, 12, 2316, 3719, 327, 5467, 67, 4400, 67, 21675, 67, 4296, 67, 8412, 67, 6067, 2849, 1268, 31, 203, 203, 565, 309, 261, 1132, 405, 1147, 18, 588, 2747, 13937, 12, 869, 3719, 327, 22428, 67, 22408, 67, 862, 7266, 1102, 2222, 67, 6694, 67, 38, 1013, 4722, 31, 203, 565, 309, 261, 3338, 411, 1147, 18, 588, 950, 2531, 12, 2080, 3719, 327, 348, 22457, 67, 8412, 55, 67, 4684, 67, 6589, 2056, 31, 203, 565, 309, 261, 2316, 18, 28138, 12, 2080, 3719, 327, 348, 22457, 67, 15140, 67, 42, 1457, 62, 1157, 31, 203, 203, 565, 2254, 5034, 389, 8151, 5912, 950, 273, 1147, 18, 588, 7009, 5912, 950, 12, 2080, 16, 358, 1769, 203, 565, 309, 261, 20, 422, 389, 8151, 5912, 950, 13, 327, 4235, 17598, 67, 8468, 67, 4400, 67, 2203, 3373, 12135, 31, 203, 565, 309, 261, 3338, 411, 389, 8151, 5912, 950, 13, 327, 4235, 17598, 67, 8468, 67, 4400, 67, 16852, 67, 5321, 2627, 67, 12190, 654, 31, 203, 203, 565, 327, 16561, 31, 203, 225, 2 ]
pragma solidity ^0.4.24; /** * @title ERC20 interface + Mint function * */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); function mint(address _to, uint256 _amount) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title OwnableWithAdmin * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract OwnableWithAdmin { address public owner; address public adminOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; adminOwner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Throws if called by any account other than the admin. */ modifier onlyAdmin() { require(msg.sender == adminOwner); _; } /** * @dev Throws if called by any account other than the owner or admin. */ modifier onlyOwnerOrAdmin() { require(msg.sender == adminOwner || 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 adminOwner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferAdminOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(adminOwner, newOwner); adminOwner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint length; while (j != 0){ length++; j /= 10; } bytes memory bstr = new bytes(length); uint k = length - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } } /** * @title Crowdsale * Contract is payable. * Direct transfer of tokens with no allocation. * * */ contract Crowdsale is OwnableWithAdmin { using SafeMath for uint256; uint256 private constant DECIMALFACTOR = 10**uint256(18); event FundTransfer(address backer, uint256 amount, bool isContribution); event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount ); //Is active bool internal crowdsaleActive = true; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many weis one token costs uint256 public rate; // Minimum weis one token costs uint256 public minRate; // Minimum buy in weis uint256 public minWeiAmount = 100000000000000000; // Amount of tokens Raised uint256 public tokensTotal = 0; // Amount of wei raised uint256 public weiRaised; // Max token amount uint256 public hardCap = 0; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; //Whitelist mapping(address => bool) public whitelist; constructor(uint256 _startTime, uint256 _endTime, address _wallet, ERC20 _token) public { require(_wallet != address(0)); require(_token != address(0)); startTime = _startTime; endTime = _endTime; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () public payable { //Check if msg sender value is more then 0 require( msg.value > 0 ); //Validate crowdSale require(isCrowdsaleActive()); //Validate whitelisted require(isWhitelisted(msg.sender)); // wei sent uint256 _weiAmount = msg.value; // Minimum buy in weis require(_weiAmount>minWeiAmount); // calculate token amount to be created after rate update uint256 _tokenAmount = _calculateTokens(_weiAmount); //Check hardCap require(_validateHardCap(_tokenAmount)); //Mint tokens and transfer tokens to buyer require(token.mint(msg.sender, _tokenAmount)); //Update state tokensTotal = tokensTotal.add(_tokenAmount); //Update state weiRaised = weiRaised.add(_weiAmount); //Funds log function emit TokenPurchase(msg.sender, _tokenAmount , _weiAmount); //Transfer funds to wallet _forwardFunds(); } // send ether to the fund collection wallet function _forwardFunds() internal { wallet.transfer(msg.value); } /* * @dev fiat and btc transfer * The company received FIAT or BTC and admin will mint the * amount of tokens directly to the receiving party’s wallet * **/ function fiatTransfer(address _recipient, uint256 _tokenAmount, uint256 _weiAmount) onlyOwnerOrAdmin public{ require(_tokenAmount > 0); require(_recipient != address(0)); //Validate crowdSale require(isCrowdsaleActive()); //Validate whitelisted require(isWhitelisted(_recipient)); // Minimum buy in weis require(_weiAmount>minWeiAmount); //Check hardCap require(_validateHardCap(_tokenAmount)); //Mint tokens and transfer tokens to buyer require(token.mint(_recipient, _tokenAmount)); //Update state tokensTotal = tokensTotal.add(_tokenAmount); //Update state weiRaised = weiRaised.add(_weiAmount); //Funds log function emit TokenPurchase(_recipient, _tokenAmount, _weiAmount); } // @return true if the transaction can buy tokens function isCrowdsaleActive() public view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; return withinPeriod; } function _validateHardCap(uint256 _tokenAmount) internal view returns (bool) { return tokensTotal.add(_tokenAmount) <= hardCap; } function _calculateTokens(uint256 _wei) internal view returns (uint256) { return _wei.mul(DECIMALFACTOR).div(rate); } /** * @dev Update current rate * @param _rate How many wei one token costs * We need to be able to update the rate as the eth rate changes */ function setRate(uint256 _rate) onlyOwnerOrAdmin public{ require(_rate > minRate); rate = _rate; } function addToWhitelist(address _buyer) onlyOwnerOrAdmin public{ require(_buyer != 0x0); whitelist[_buyer] = true; } function addManyToWhitelist(address[] _beneficiaries) onlyOwnerOrAdmin public{ for (uint256 i = 0; i < _beneficiaries.length; i++) { if(_beneficiaries[i] != 0x0){ whitelist[_beneficiaries[i]] = true; } } } function removeFromWhitelist(address _buyer) onlyOwnerOrAdmin public{ whitelist[_buyer] = false; } // @return true if buyer is whitelisted function isWhitelisted(address _buyer) public view returns (bool) { return whitelist[_buyer]; } // Owner can transfer tokens that are sent here by mistake function refundTokens(address _recipient, ERC20 _token) public onlyOwner { uint256 balance = _token.balanceOf(this); require(_token.transfer(_recipient, balance)); } } /** * @title BYTMCrowdsale * * */ contract BYTMCrowdsale is Crowdsale { constructor( uint256 _startTime, uint256 _endTime, address _wallet, ERC20 _token ) public Crowdsale( _startTime, _endTime, _wallet, _token) { // Initial rate //What one token cost in wei rate = 870000000000000; // Initial minimum rate // rate can't be set below this // 0.12 euro minRate = 670000000000000; // HardCap 1,000,000,000 hardCap = 1000000000 * (10**uint256(18)); //min buy amount in wei // 100euro minWeiAmount = 545000000000000000; } }
* @title BYTMCrowdsale/
contract BYTMCrowdsale is Crowdsale { constructor( uint256 _startTime, uint256 _endTime, address _wallet, ERC20 _token ) public Crowdsale( _startTime, _endTime, _wallet, _token) { rate = 870000000000000; minRate = 670000000000000; hardCap = 1000000000 * (10**uint256(18)); minWeiAmount = 545000000000000000; } }
12,988,919
[ 1, 6486, 56, 20022, 492, 2377, 5349, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 6953, 56, 20022, 492, 2377, 5349, 353, 385, 492, 2377, 5349, 288, 203, 225, 3885, 12, 27699, 565, 2254, 5034, 389, 1937, 950, 16, 7010, 565, 2254, 5034, 389, 409, 950, 16, 21281, 565, 1758, 389, 19177, 16, 7010, 565, 4232, 39, 3462, 389, 2316, 203, 225, 262, 1071, 385, 492, 2377, 5349, 12, 389, 1937, 950, 16, 389, 409, 950, 16, 225, 389, 19177, 16, 389, 2316, 13, 288, 203, 203, 565, 4993, 273, 1725, 27, 12648, 11706, 31, 27699, 203, 565, 1131, 4727, 273, 21017, 12648, 11706, 31, 21281, 203, 565, 7877, 4664, 273, 15088, 3784, 380, 261, 2163, 636, 11890, 5034, 12, 2643, 10019, 7010, 203, 565, 1131, 3218, 77, 6275, 273, 1381, 7950, 12648, 17877, 31, 203, 203, 225, 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 ]
pragma solidity ^0.4.19; // /* CONTRACT */ contract SafeMath { function safeAdd(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // END_OF_contract_SafeMath //_________________________________________________________ // /* INTERFACES */ // interface tokenRecipient { function receiveApproval(address _from, uint256 _tokenAmountApproved, address tokenMacroansy, bytes _extraData) public returns(bool success); } //________________________________________________________ // interface ICO { function buy( uint payment, address buyer, bool isPreview) public returns(bool success, uint amount); function redeemCoin(uint256 amount, address redeemer, bool isPreview) public returns (bool success, uint redeemPayment); function sell(uint256 amount, address seller, bool isPreview) public returns (bool success, uint sellPayment ); function paymentAction(uint paymentValue, address beneficiary, uint paytype) public returns(bool success); function recvShrICO( address _spender, uint256 _value, uint ShrID) public returns (bool success); function burn( uint256 value, bool unburn, uint totalSupplyStart, uint balOfOwner) public returns( bool success); function getSCF() public returns(uint seriesCapFactorMulByTenPowerEighteen); function getMinBal() public returns(uint minBalForAccnts_ ); function getAvlShares(bool show) public returns(uint totalSupplyOfCoinsInSeriesNow, uint coinsAvailableForSale, uint icoFunding); } //_______________________________________________________ // interface Exchg{ function sell_Exchg_Reg( uint amntTkns, uint tknPrice, address seller) public returns(bool success); function buy_Exchg_booking( address seller, uint amntTkns, uint tknPrice, address buyer, uint payment ) public returns(bool success); function buy_Exchg_BkgChk( address seller, uint amntTkns, uint tknPrice, address buyer, uint payment) public returns(bool success); function updateSeller( address seller, uint tknsApr, address buyer, uint payment) public returns(bool success); function getExchgComisnMulByThousand() public returns(uint exchgCommissionMulByThousand_); function viewSellOffersAtExchangeMacroansy(address seller, bool show) view public returns (uint sellersCoinAmountOffer, uint sellersPriceOfOneCoinInWEI, uint sellerBookedTime, address buyerWhoBooked, uint buyPaymentBooked, uint buyerBookedTime, uint exchgCommissionMulByThousand_); } //_________________________________________________________ // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md /* CONTRACT */ // contract TokenERC20Interface { function totalSupply() public constant returns (uint coinLifeTimeTotalSupply); function balanceOf(address tokenOwner) public constant returns (uint coinBalance); function allowance(address tokenOwner, address spender) public constant returns (uint coinsRemaining); 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); } //END_OF_contract_ERC20Interface //_________________________________________________________________ /* CONTRACT */ /** * COPYRIGHT Macroansy * http://www.macroansy.org */ contract TokenMacroansy is TokenERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals = 18; // address internal owner; address private beneficiaryFunds; // uint256 public totalSupply; uint256 internal totalSupplyStart; // mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; mapping( address => bool) internal frozenAccount; // mapping(address => uint) private msgSndr; // address tkn_addr; address ico_addr; address exchg_addr; // uint256 internal allowedIndividualShare; uint256 internal allowedPublicShare; // //uint256 internal allowedFounderShare; //uint256 internal allowedPOOLShare; //uint256 internal allowedVCShare; //uint256 internal allowedColdReserve; //_________________________________________________________ event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Burn(address indexed from, uint amount); event UnBurn(address indexed from, uint amount); event FundOrPaymentTransfer(address beneficiary, uint amount); event FrozenFunds(address target, bool frozen); event BuyAtMacroansyExchg(address buyer, address seller, uint tokenAmount, uint payment); //_________________________________________________________ // //CONSTRUCTOR /* Initializes contract with initial supply tokens to the creator of the contract */ function TokenMacroansy() public { owner = msg.sender; beneficiaryFunds = owner; //totalSupplyStart = initialSupply * 10** uint256(decimals); totalSupplyStart = 3999 * 10** uint256(decimals); totalSupply = totalSupplyStart; // balanceOf[msg.sender] = totalSupplyStart; Transfer(address(0), msg.sender, totalSupplyStart); // name = "TokenMacroansy"; symbol = "$BEE"; // allowedIndividualShare = uint(1)*totalSupplyStart/100; allowedPublicShare = uint(20)* totalSupplyStart/100; // //allowedFounderShare = uint(20)*totalSupplyStart/100; //allowedPOOLShare = uint(9)* totalSupplyStart/100; //allowedColdReserve = uint(41)* totalSupplyStart/100; //allowedVCShare = uint(10)* totalSupplyStart/100; } //_________________________________________________________ modifier onlyOwner { require(msg.sender == owner); _; } function wadmin_transferOr(address _Or) public onlyOwner { owner = _Or; } //_________________________________________________________ /** * @notice Show the `totalSupply` for this Token contract */ function totalSupply() constant public returns (uint coinLifeTimeTotalSupply) { return totalSupply ; } //_________________________________________________________ /** * @notice Show the `tokenOwner` balances for this contract * @param tokenOwner the token owners address */ function balanceOf(address tokenOwner) constant public returns (uint coinBalance) { return balanceOf[tokenOwner]; } //_________________________________________________________ /** * @notice Show the allowance given by `tokenOwner` to the `spender` * @param tokenOwner the token owner address allocating allowance * @param spender the allowance spenders address */ function allowance(address tokenOwner, address spender) constant public returns (uint coinsRemaining) { return allowance[tokenOwner][spender]; } //_________________________________________________________ // function wadmin_setContrAddr(address icoAddr, address exchAddr ) public onlyOwner returns(bool success){ tkn_addr = this; ico_addr = icoAddr; exchg_addr = exchAddr; return true; } // function _getTknAddr() internal returns(address tkn_ma_addr){ return(tkn_addr); } function _getIcoAddr() internal returns(address ico_ma_addr){ return(ico_addr); } function _getExchgAddr() internal returns(address exchg_ma_addr){ return(exchg_addr); } // _getTknAddr(); _getIcoAddr(); _getExchgAddr(); // address tkn_addr; address ico_addr; address exchg_addr; //_________________________________________________________ // /* Internal transfer, only can be called by this contract */ // function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); require(!frozenAccount[_from]); require(!frozenAccount[_to]); uint valtmp = _value; uint _valueA = valtmp; valtmp = 0; require (balanceOf[_from] >= _valueA); require (balanceOf[_to] + _valueA > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] = safeSub(balanceOf[_from], _valueA); balanceOf[_to] = safeAdd(balanceOf[_to], _valueA); Transfer(_from, _to, _valueA); _valueA = 0; assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } //________________________________________________________ /** * Transfer tokens * * @notice Allows to Send Coins to other accounts * @param _to The address of the recipient of coins * @param _value The amount of coins to send */ function transfer(address _to, uint256 _value) public returns(bool success) { //check sender and receiver allw limits in accordance with ico contract bool sucsSlrLmt = _chkSellerLmts( msg.sender, _value); bool sucsByrLmt = _chkBuyerLmts( _to, _value); require(sucsSlrLmt == true && sucsByrLmt == true); // uint valtmp = _value; uint _valueTemp = valtmp; valtmp = 0; _transfer(msg.sender, _to, _valueTemp); _valueTemp = 0; return true; } //_________________________________________________________ /** * Transfer tokens from other address * * @notice sender can set an allowance for another contract, * @notice and the other contract interface function receiveApproval * @notice can call this funtion for token as payment and add further coding for service. * @notice please also refer to function approveAndCall * @notice Send `_value` tokens to `_to` on behalf of `_from` * @param _from The address of the sender * @param _to The address of the recipient of coins * @param _value The amount coins to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint valtmp = _value; uint _valueA = valtmp; valtmp = 0; require(_valueA <= allowance[_from][msg.sender]); allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _valueA); _transfer(_from, _to, _valueA); _valueA = 0; return true; } //_________________________________________________________ /** * Set allowance for other address * * @notice Allows `_spender` to spend no more than `_value` coins from your account * @param _spender The address authorized to spend * @param _value The max amount of coins allocated to spender */ function approve(address _spender, uint256 _value) public returns (bool success) { //check sender and receiver allw limits in accordance with ico contract bool sucsSlrLmt = _chkSellerLmts( msg.sender, _value); bool sucsByrLmt = _chkBuyerLmts( _spender, _value); require(sucsSlrLmt == true && sucsByrLmt == true); // uint valtmp = _value; uint _valueA = valtmp; valtmp = 0; allowance[msg.sender][_spender] = _valueA; Approval(msg.sender, _spender, _valueA); _valueA =0; return true; } //_________________________________________________________ /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` coins in from your account * * @param _spender The address authorized to spend * @param _value the max amount of coins the spender can spend * @param _extraData some extra information to send to the spender contracts */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); uint valtmp = _value; uint _valueA = valtmp; valtmp = 0; if (approve(_spender, _valueA)) { spender.receiveApproval(msg.sender, _valueA, this, _extraData); } _valueA = 0; return true; } //_________________________________________________________ // /** * @notice `freeze` Prevent | Allow` `target` from sending & receiving tokens * @param target Address to be frozen * @param freeze either to freeze it or not */ function wadmin_freezeAccount(address target, bool freeze) onlyOwner public returns(bool success) { frozenAccount[target] = freeze; FrozenFunds(target, freeze); return true; } //________________________________________________________ // function _safeTransferTkn( address _from, address _to, uint amount) internal returns(bool sucsTrTk){ uint tkA = amount; uint tkAtemp = tkA; tkA = 0; _transfer(_from, _to, tkAtemp); tkAtemp = 0; return true; } //_________________________________________________________ // function _safeTransferPaymnt( address paymentBenfcry, uint payment) internal returns(bool sucsTrPaymnt){ uint pA = payment; uint paymentTemp = pA; pA = 0; paymentBenfcry.transfer(paymentTemp); FundOrPaymentTransfer(paymentBenfcry, paymentTemp); paymentTemp = 0; return true; } //_________________________________________________________ // function _safePaymentActionAtIco( uint payment, address paymentBenfcry, uint paytype) internal returns(bool success){ // payment req to ico uint Pm = payment; uint PmTemp = Pm; Pm = 0; ICO ico = ICO(_getIcoAddr()); // paytype 1 for redeempayment and 2 for sell payment bool pymActSucs = ico.paymentAction( PmTemp, paymentBenfcry, paytype); require(pymActSucs == true); PmTemp = 0; return true; } //_________________________________________________________ /* @notice Allows to Buy ICO tokens directly from this contract by sending ether */ function buyCoinsAtICO() payable public returns(bool success) { msgSndr[msg.sender] = msg.value; ICO ico = ICO(_getIcoAddr() ); require( msg.value > 0 ); // buy exe at ico bool icosuccess; uint tknsBuyAppr; (icosuccess, tknsBuyAppr) = ico.buy( msg.value, msg.sender, false); require( icosuccess == true ); // tkn transfer bool sucsTrTk = _safeTransferTkn( owner, msg.sender, tknsBuyAppr); require(sucsTrTk == true); msgSndr[msg.sender] = 0; return (true) ; } //_____________________________________________________________ // /* @notice Allows anyone to preview a Buy of ICO tokens before an actual buy */ function buyCoinsPreview(uint myProposedPaymentInWEI) public view returns(bool success, uint tokensYouCanBuy, uint yourSafeMinBalReqdInWEI) { uint payment = myProposedPaymentInWEI; msgSndr[msg.sender] = payment; success = false; ICO ico = ICO(_getIcoAddr() ); tokensYouCanBuy = 0; bool icosuccess; (icosuccess, tokensYouCanBuy) = ico.buy( payment, msg.sender, true); msgSndr[msg.sender] = 0; return ( icosuccess, tokensYouCanBuy, ico.getMinBal()) ; } //_____________________________________________________________ /** * @notice Allows Token owners to Redeem Tokens to this Contract for its value promised */ function redeemCoinsToICO( uint256 amountOfCoinsToRedeem) public returns (bool success ) { uint amount = amountOfCoinsToRedeem; msgSndr[msg.sender] = amount; bool isPreview = false; ICO ico = ICO(_getIcoAddr()); // redeem exe at ico bool icosuccess ; uint redeemPaymentValue; (icosuccess , redeemPaymentValue) = ico.redeemCoin( amount, msg.sender, isPreview); require( icosuccess == true); require( _getIcoAddr().balance >= safeAdd( ico.getMinBal() , redeemPaymentValue) ); bool sucsTrTk = false; bool pymActSucs = false; if(isPreview == false) { // transfer tkns sucsTrTk = _safeTransferTkn( msg.sender, owner, amount); require(sucsTrTk == true); // payment req to ico 1 for redeempayment and 2 for sell payment msgSndr[msg.sender] = redeemPaymentValue; pymActSucs = _safePaymentActionAtIco( redeemPaymentValue, msg.sender, 1); require(pymActSucs == true); } msgSndr[msg.sender] = 0; return (true); } //_________________________________________________________ /** * @notice Allows Token owners to Sell Tokens directly to this Contract * */ function sellCoinsToICO( uint256 amountOfCoinsToSell ) public returns (bool success ) { uint amount = amountOfCoinsToSell; msgSndr[msg.sender] = amount; bool isPreview = false; ICO ico = ICO(_getIcoAddr() ); // sell exe at ico bool icosuccess; uint sellPaymentValue; ( icosuccess , sellPaymentValue) = ico.sell( amount, msg.sender, isPreview); require( icosuccess == true ); require( _getIcoAddr().balance >= safeAdd(ico.getMinBal() , sellPaymentValue) ); bool sucsTrTk = false; bool pymActSucs = false; if(isPreview == false){ // token transfer sucsTrTk = _safeTransferTkn( msg.sender, owner, amount); require(sucsTrTk == true); // payment request to ico 1 for redeempayment and 2 for sell payment msgSndr[msg.sender] = sellPaymentValue; pymActSucs = _safePaymentActionAtIco( sellPaymentValue, msg.sender, 2); require(pymActSucs == true); } msgSndr[msg.sender] = 0; return ( true); } //________________________________________________________ /** * @notice a sellers allowed limits in holding ico tokens is checked */ // function _chkSellerLmts( address seller, uint amountOfCoinsSellerCanSell) internal returns(bool success){ uint amountTkns = amountOfCoinsSellerCanSell; success = false; ICO ico = ICO( _getIcoAddr() ); uint seriesCapFactor = ico.getSCF(); if( amountTkns <= balanceOf[seller] && balanceOf[seller] <= safeDiv(allowedIndividualShare*seriesCapFactor,10**18) ){ success = true; } return success; } // bool sucsSlrLmt = _chkSellerLmts( address seller, uint amountTkns); //_________________________________________________________ // /** * @notice a buyers allowed limits in holding ico tokens is checked */ function _chkBuyerLmts( address buyer, uint amountOfCoinsBuyerCanBuy) internal returns(bool success){ uint amountTkns = amountOfCoinsBuyerCanBuy; success = false; ICO ico = ICO( _getIcoAddr() ); uint seriesCapFactor = ico.getSCF(); if( amountTkns <= safeSub( safeDiv(allowedIndividualShare*seriesCapFactor,10**18), balanceOf[buyer] )) { success = true; } return success; } //_________________________________________________________ // /** * @notice a buyers allowed limits in holding ico tokens along with financial capacity to buy is checked */ function _chkBuyerLmtsAndFinl( address buyer, uint amountTkns, uint priceOfr) internal returns(bool success){ success = false; // buyer limits bool sucs1 = false; sucs1 = _chkBuyerLmts( buyer, amountTkns); // buyer funds ICO ico = ICO( _getIcoAddr() ); bool sucs2 = false; if( buyer.balance >= safeAdd( safeMul(amountTkns , priceOfr) , ico.getMinBal() ) ) sucs2 = true; if( sucs1 == true && sucs2 == true) success = true; return success; } //_________________________________________________________ // function _slrByrLmtChk( address seller, uint amountTkns, uint priceOfr, address buyer) internal returns(bool success){ // seller limits check bool successSlrl; (successSlrl) = _chkSellerLmts( seller, amountTkns); // buyer limits check bool successByrlAFinl; (successByrlAFinl) = _chkBuyerLmtsAndFinl( buyer, amountTkns, priceOfr); require( successSlrl == true && successByrlAFinl == true); return true; } //___________________________________________________________________ /** * @notice allows a seller to formally register his sell offer at ExchangeMacroansy */ function sellBkgAtExchg( uint amountOfCoinsOffer, uint priceOfOneCoinInWEI) public returns(bool success){ uint amntTkns = amountOfCoinsOffer ; uint tknPrice = priceOfOneCoinInWEI; // seller limits bool successSlrl; (successSlrl) = _chkSellerLmts( msg.sender, amntTkns); require(successSlrl == true); msgSndr[msg.sender] = amntTkns; // bkg registration at exchange Exchg em = Exchg(_getExchgAddr()); bool emsuccess; (emsuccess) = em.sell_Exchg_Reg( amntTkns, tknPrice, msg.sender ); require(emsuccess == true ); msgSndr[msg.sender] = 0; return true; } //_________________________________________________________ // /** * @notice function for booking and locking for a buy with respect to a sale offer registered * @notice after booking then proceed for payment using func buyCoinsAtExchg * @notice payment booking value and actual payment value should be exact */ function buyBkgAtExchg( address seller, uint sellersCoinAmountOffer, uint sellersPriceOfOneCoinInWEI, uint myProposedPaymentInWEI) public returns(bool success){ uint amountTkns = sellersCoinAmountOffer; uint priceOfr = sellersPriceOfOneCoinInWEI; uint payment = myProposedPaymentInWEI; msgSndr[msg.sender] = amountTkns; // seller buyer limits check bool sucsLmt = _slrByrLmtChk( seller, amountTkns, priceOfr, msg.sender); require(sucsLmt == true); // booking at exchange Exchg em = Exchg(_getExchgAddr()); bool emBkgsuccess; (emBkgsuccess)= em.buy_Exchg_booking( seller, amountTkns, priceOfr, msg.sender, payment); require( emBkgsuccess == true ); msgSndr[msg.sender] = 0; return true; } //________________________________________________________ /** * @notice for buyingCoins at ExchangeMacroansy * @notice please first book the buy through function_buy_Exchg_booking */ // function buyCoinsAtExchg( address seller, uint amountTkns, uint priceOfr) payable public returns(bool success) { function buyCoinsAtExchg( address seller, uint sellersCoinAmountOffer, uint sellersPriceOfOneCoinInWEI) payable public returns(bool success) { uint amountTkns = sellersCoinAmountOffer; uint priceOfr = sellersPriceOfOneCoinInWEI; require( msg.value > 0 && msg.value <= safeMul(amountTkns, priceOfr ) ); msgSndr[msg.sender] = amountTkns; // calc tokens that can be bought uint tknsBuyAppr = safeDiv(msg.value , priceOfr); // check buyer booking at exchange Exchg em = Exchg(_getExchgAddr()); bool sucsBkgChk = em.buy_Exchg_BkgChk(seller, amountTkns, priceOfr, msg.sender, msg.value); require(sucsBkgChk == true); // update seller reg and buyer booking at exchange msgSndr[msg.sender] = tknsBuyAppr; bool emUpdateSuccess; (emUpdateSuccess) = em.updateSeller(seller, tknsBuyAppr, msg.sender, msg.value); require( emUpdateSuccess == true ); // token transfer in this token contract bool sucsTrTkn = _safeTransferTkn( seller, msg.sender, tknsBuyAppr); require(sucsTrTkn == true); // payment to seller bool sucsTrPaymnt; sucsTrPaymnt = _safeTransferPaymnt( seller, safeSub( msg.value , safeDiv(msg.value*em.getExchgComisnMulByThousand(),1000) ) ); require(sucsTrPaymnt == true ); // BuyAtMacroansyExchg(msg.sender, seller, tknsBuyAppr, msg.value); //event msgSndr[msg.sender] = 0; return true; } //___________________________________________________________ /** * @notice Fall Back Function, not to receive ether directly and/or accidentally * */ function () public payable { if(msg.sender != owner) revert(); } //_________________________________________________________ /* * @notice Burning tokens ie removing tokens from the formal total supply */ function wadmin_burn( uint256 value, bool unburn) onlyOwner public returns( bool success ) { msgSndr[msg.sender] = value; ICO ico = ICO( _getIcoAddr() ); if( unburn == false) { balanceOf[owner] = safeSub( balanceOf[owner] , value); totalSupply = safeSub( totalSupply, value); Burn(owner, value); } if( unburn == true) { balanceOf[owner] = safeAdd( balanceOf[owner] , value); totalSupply = safeAdd( totalSupply , value); UnBurn(owner, value); } bool icosuccess = ico.burn( value, unburn, totalSupplyStart, balanceOf[owner] ); require( icosuccess == true); return true; } //_________________________________________________________ /* * @notice Withdraw Payments to beneficiary * @param withdrawAmount the amount withdrawn in wei */ function wadmin_withdrawFund(uint withdrawAmount) onlyOwner public returns(bool success) { success = _withdraw(withdrawAmount); return success; } //_________________________________________________________ /*internal function can called by this contract only */ function _withdraw(uint _withdrawAmount) internal returns(bool success) { bool sucsTrPaymnt = _safeTransferPaymnt( beneficiaryFunds, _withdrawAmount); require(sucsTrPaymnt == true); return true; } //_________________________________________________________ /** * @notice Allows to receive coins from Contract Share approved by contract * @notice to receive the share, it has to be already approved by the contract * @notice the share Id will be provided by contract while payments are made through other channels like paypal * @param amountOfCoinsToReceive the allocated allowance of coins to be transferred to you * @param ShrID 1 is FounderShare, 2 is POOLShare, 3 is ColdReserveShare, 4 is VCShare, 5 is PublicShare, 6 is RdmSellPool */ function receiveICOcoins( uint256 amountOfCoinsToReceive, uint ShrID ) public returns (bool success){ msgSndr[msg.sender] = amountOfCoinsToReceive; ICO ico = ICO( _getIcoAddr() ); bool icosuccess; icosuccess = ico.recvShrICO(msg.sender, amountOfCoinsToReceive, ShrID ); require (icosuccess == true); bool sucsTrTk; sucsTrTk = _safeTransferTkn( owner, msg.sender, amountOfCoinsToReceive); require(sucsTrTk == true); msgSndr[msg.sender] = 0; return true; } //_______________________________________________________ // called by other contracts function sendMsgSndr(address caller, address origin) public returns(bool success, uint value){ (success, value) = _sendMsgSndr(caller, origin); return(success, value); } //_______________________________________________________ // function _sendMsgSndr(address caller, address origin) internal returns(bool success, uint value){ require(caller == _getIcoAddr() || caller == _getExchgAddr()); //require(origin == tx.origin); return(true, msgSndr[origin]); } //_______________________________________________________ // function a_viewSellOffersAtExchangeMacroansy(address seller, bool show) view public returns (uint sellersCoinAmountOffer, uint sellersPriceOfOneCoinInWEI, uint sellerBookedTime, address buyerWhoBooked, uint buyPaymentBooked, uint buyerBookedTime, uint exchgCommissionMulByThousand_){ if(show == true){ Exchg em = Exchg(_getExchgAddr()); ( sellersCoinAmountOffer, sellersPriceOfOneCoinInWEI, sellerBookedTime, buyerWhoBooked, buyPaymentBooked, buyerBookedTime, exchgCommissionMulByThousand_) = em.viewSellOffersAtExchangeMacroansy( seller, show) ; return ( sellersCoinAmountOffer, sellersPriceOfOneCoinInWEI, sellerBookedTime, buyerWhoBooked, buyPaymentBooked, buyerBookedTime, exchgCommissionMulByThousand_); } } //_________________________________________________________ // function a_viewCoinSupplyAndFunding(bool show) public view returns(uint totalSupplyOfCoinsInSeriesNow, uint coinsAvailableForSale, uint icoFunding){ if(show == true){ ICO ico = ICO( _getIcoAddr() ); ( totalSupplyOfCoinsInSeriesNow, coinsAvailableForSale, icoFunding) = ico.getAvlShares(show); return( totalSupplyOfCoinsInSeriesNow, coinsAvailableForSale, icoFunding); } } //_______________________________________________________ // /* bool private isEndOk; function endOfRewards(bool isEndNow) public onlyOwner { isEndOk == isEndNow; } function endOfRewardsConfirmed(bool isEndNow) public onlyOwner{ if(isEndOk == true && isEndNow == true) selfdestruct(owner); } */ //_______________________________________________________ } // END_OF_CONTRACT
________________________________________________________
function _safeTransferTkn( address _from, address _to, uint amount) internal returns(bool sucsTrTk){ uint tkA = amount; uint tkAtemp = tkA; tkA = 0; _transfer(_from, _to, tkAtemp); tkAtemp = 0; return true; }
7,901,578
[ 1, 21157, 21157, 21157, 12214, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4626, 5912, 56, 21112, 12, 1758, 389, 2080, 16, 1758, 389, 869, 16, 2254, 3844, 13, 2713, 1135, 12, 6430, 1597, 2143, 1070, 56, 79, 15329, 203, 6647, 203, 1850, 2254, 13030, 37, 273, 3844, 31, 203, 1850, 2254, 13030, 861, 30752, 273, 13030, 37, 31, 203, 1850, 13030, 37, 273, 374, 31, 203, 10402, 389, 13866, 24899, 2080, 16, 389, 869, 16, 13030, 861, 30752, 1769, 7010, 1850, 13030, 861, 30752, 273, 374, 31, 203, 1850, 327, 638, 31, 203, 565, 289, 4202, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xB3e59F3f52aEa7a07008C4966302D60E199171CF/sources/Tx2UNI.sol
To drive Contract : send TOKEN ( in contract-side ) to UNISWAP , swap to ETHfunction SWAP_TOKEN_for_ETH( address tokenaddr, uint256 artt_amount, uint amountOutMin ) external
function SWAP_TOKEN_for_ETH( address tokenaddr ) external { require ( isValidBot(msg.sender) == true , "invalid Bot" ); uint256 deadline = now+1 hours; address contract_addr = address(this); delete _pair_TOKEN_weth; _pair_TOKEN_weth.push( tokenaddr ); _pair_TOKEN_weth.push( _unirouter.WETH() ); Erc20Token _token = Erc20Token(tokenaddr); uint256 _tokentBalance = _token.balanceOf(address(this)); uint256 amountOutMin = 0; _unirouter.swapExactTokensForETH( _tokentBalance, amountOutMin, _pair_TOKEN_weth, contract_addr, deadline); }
8,593,287
[ 1, 774, 14316, 13456, 294, 1366, 14275, 261, 316, 6835, 17, 5564, 262, 358, 5019, 5127, 59, 2203, 269, 7720, 358, 512, 2455, 915, 16392, 2203, 67, 8412, 67, 1884, 67, 1584, 44, 12, 1758, 1147, 4793, 16, 2254, 5034, 419, 748, 67, 8949, 16, 2254, 3844, 1182, 2930, 262, 225, 3903, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 16392, 2203, 67, 8412, 67, 1884, 67, 1584, 44, 12, 1758, 1147, 4793, 262, 225, 3903, 203, 565, 288, 203, 3639, 2583, 261, 4908, 6522, 12, 3576, 18, 15330, 13, 422, 638, 269, 315, 5387, 15039, 6, 11272, 203, 3639, 2254, 5034, 14096, 273, 2037, 15, 21, 7507, 31, 203, 3639, 1758, 6835, 67, 4793, 273, 1758, 12, 2211, 1769, 203, 3639, 1430, 389, 6017, 67, 8412, 67, 91, 546, 31, 203, 3639, 389, 6017, 67, 8412, 67, 91, 546, 18, 6206, 12, 1147, 4793, 11272, 203, 3639, 389, 6017, 67, 8412, 67, 91, 546, 18, 6206, 12, 389, 318, 77, 10717, 18, 59, 1584, 44, 1435, 11272, 203, 540, 203, 3639, 512, 1310, 3462, 1345, 389, 2316, 273, 225, 512, 1310, 3462, 1345, 12, 2316, 4793, 1769, 203, 3639, 2254, 5034, 389, 17692, 319, 13937, 273, 389, 2316, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 3844, 1182, 2930, 273, 374, 31, 203, 540, 203, 3639, 389, 318, 77, 10717, 18, 22270, 14332, 5157, 1290, 1584, 44, 12, 389, 17692, 319, 13937, 16, 3844, 1182, 2930, 16, 389, 6017, 67, 8412, 67, 91, 546, 16, 6835, 67, 4793, 16, 14096, 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 ]
./partial_match/1/0x2101b79baE6B9BA590Aa5960F0ecBA2320968a60/sources/HalfPepe.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Half Pepe", "PEPE0.5") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), PEPE); excludeFromMaxTransaction(address(uniswapV2Pair), true); uint256 _buyDevFee = 20; uint256 _buyLiquidityFee = 0; uint256 _sellDevFee = 20; uint256 _sellLiquidityFee = 0; uint256 totalSupply = 1_000_000 * 1e18; buyDevFee = _buyDevFee; buyLiquidityFee = _buyLiquidityFee; buyTotalFees = buyDevFee + buyLiquidityFee; sellDevFee = _sellDevFee; sellLiquidityFee = _sellLiquidityFee; sellTotalFees = sellDevFee + sellLiquidityFee; devWallet = address(0x339c25E1C1386366F057Eb54a383d5C9eab2B168); excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
9,400,820
[ 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, 16168, 19622, 347, 3113, 315, 1423, 1423, 20, 18, 25, 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, 20, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 1769, 203, 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, 16628, 1423, 1769, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 203, 203, 3639, 2254, 5034, 389, 70, 9835, 8870, 14667, 273, 4200, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 374, 31, 203, 203, 3639, 2254, 5034, 389, 87, 1165, 8870, 14667, 273, 4200, 31, 203, 3639, 2254, 5034, 389, 87, 1165, 48, 18988, 24237, 14667, 273, 374, 31, 203, 203, 3639, 2254, 5034, 2078, 3088, 1283, 273, 404, 67, 3784, 67, 3784, 380, 404, 2 ]
./partial_match/1/0xC5C9e719C0A8FD2E56437fd61982cDD098F2FaE9/sources/src/interfaces/proxy/IDiagonalOrgProxy.sol
* @title IDiagonalOrgProxy contract interface @author Diagonal Finance @notice A DiagonalOrgProxy is a beacon proxy whose implementation is set in DiagonalOrgProxy./
interface IDiagonalOrgProxy { function initializeProxy( address beacon, address implementation, bytes memory data ) external; pragma solidity 0.8.15; }
3,595,669
[ 1, 734, 8852, 9528, 6001, 3886, 6835, 1560, 225, 14539, 9528, 9458, 1359, 225, 432, 14539, 9528, 6001, 3886, 353, 279, 29203, 2889, 8272, 4471, 540, 353, 444, 316, 14539, 9528, 6001, 3886, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 5831, 1599, 8852, 9528, 6001, 3886, 288, 203, 565, 445, 4046, 3886, 12, 203, 3639, 1758, 29203, 16, 203, 3639, 1758, 4471, 16, 203, 3639, 1731, 3778, 501, 203, 565, 262, 3903, 31, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 3600, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.7.6; // SPDX-License-Identifier: Unlicensed interface IERC20 { function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require( success, 'Address: unable to send value, recipient may have reverted' ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, 'Address: low-level call failed'); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, 'Address: low-level call with value failed' ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, 'Address: insufficient balance for call' ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), 'Address: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() public { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_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; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(block.timestamp > _lockTime, 'Contract is locked until 7 days'); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 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 (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); 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 (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } contract Kawa 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; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 999999999999 * 10**18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'Kawakami Inu'; string private _symbol = 'KAWA'; uint8 private _decimals = 18; address public devAddress = address(0x93837577c98E01CFde883c23F64a0f608A70B90F); uint256 public devFee = 2; uint256 public _taxFee = 1; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 0; uint256 private _previousLiquidityFee = _liquidityFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; 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; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair( address(this), _uniswapV2Router.WETH() ); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, 'ERC20: transfer amount exceeds allowance' ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, 'ERC20: decreased allowance below zero' ) ); return true; } function 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; } else { (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require(rAmount <= _rTotal, 'Amount must be less than total reflections'); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], 'Account is already excluded'); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function 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 setDevFeePercent(uint256 fee) external onlyOwner { devFee = fee; } function setDevAddress(address account) external onlyOwner { devAddress = account; } function setTaxFeePercent(uint256 taxFee) external onlyOwner { _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner { _liquidityFee = liquidityFee; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} 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 _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 _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'); uint256 contractTokenBalance = balanceOf(address(this)); if ( contractTokenBalance > 0 && !inSwapAndLiquify && from != uniswapV2Pair && to != uniswapV2Pair ) { swapAndSendToDev(contractTokenBalance); } if ( !inSwapAndLiquify && (from == uniswapV2Pair || to == uniswapV2Pair) && !isExcludedFromFee(from) && !isExcludedFromFee(to) ) { uint256 devAmount = amount.mul(devFee).div(100); uint256 remainingAmount = amount.sub(devAmount); _tokenTransfer(from, address(this), devAmount, false); _tokenTransfer(from, to, remainingAmount, true); } else { _tokenTransfer(from, to, amount, false); } } function swapAndSendToDev(uint256 tokenAmount) private lockTheSwap { swapTokensForEth(tokenAmount); uint256 devAmountETH = address(this).balance; payable(devAddress).call{value: devAmountETH}(''); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 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); } }
split the contract balance into halves capture the contract's current ETH balance. this is so that we can capture exactly the amount of ETH that the swap creates, and not make the liquidity event include any ETH that has been manually sent to the contract swap tokens for ETH how much ETH did we just swap into? add liquidity to uniswap
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); uint256 initialBalance = address(this).balance; uint256 newBalance = address(this).balance.sub(initialBalance); addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); }
2,004,738
[ 1, 4939, 326, 6835, 11013, 1368, 19514, 3324, 7477, 326, 6835, 1807, 783, 512, 2455, 11013, 18, 333, 353, 1427, 716, 732, 848, 7477, 8950, 326, 3844, 434, 512, 2455, 716, 326, 7720, 3414, 16, 471, 486, 1221, 326, 4501, 372, 24237, 871, 2341, 1281, 512, 2455, 716, 711, 2118, 10036, 3271, 358, 326, 6835, 7720, 2430, 364, 512, 2455, 3661, 9816, 512, 2455, 5061, 732, 2537, 7720, 1368, 35, 527, 4501, 372, 24237, 358, 640, 291, 91, 438, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7720, 1876, 48, 18988, 1164, 12, 11890, 5034, 6835, 1345, 13937, 13, 3238, 2176, 1986, 12521, 288, 203, 565, 2254, 5034, 8816, 273, 6835, 1345, 13937, 18, 2892, 12, 22, 1769, 203, 565, 2254, 5034, 1308, 16168, 273, 6835, 1345, 13937, 18, 1717, 12, 20222, 1769, 203, 203, 565, 2254, 5034, 2172, 13937, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 203, 203, 565, 2254, 5034, 394, 13937, 273, 1758, 12, 2211, 2934, 12296, 18, 1717, 12, 6769, 13937, 1769, 203, 203, 565, 527, 48, 18988, 24237, 12, 3011, 16168, 16, 394, 13937, 1769, 203, 203, 565, 3626, 12738, 1876, 48, 18988, 1164, 12, 20222, 16, 394, 13937, 16, 1308, 16168, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "./RandomNumber.sol"; import "./ChainLink.sol"; abstract contract MillionDollarUtils is Aggregator, Ownable, RandomNumber {} contract MillionDollarMint is ERC721Enumerable, MillionDollarUtils { bool public saleIsActive = false; uint256 public constant PRICE = 0.075 ether; uint256 public constant MAX_SUPPLY = 10000; uint256 public constant MAX_PUBLIC_MINT = 10; bool public IS_DRAWN = false; address public winner; modifier soldOut { require(totalSupply() == 10000, "Collection not sold out"); _; } constructor() ERC721("MDM Ticket", "MDM") {} function setSaleState(bool newState) public onlyOwner { saleIsActive = newState; } function mint(uint16 amount) public payable { uint256 ts = totalSupply(); uint256 tsAmount = ts + amount; require(saleIsActive, "Sale not active"); require(amount <= MAX_PUBLIC_MINT, "Max 10 per txn"); require(tsAmount < 10000, "More than total supply"); uint256 price = amount * PRICE; if (tsAmount <= 1000) { price = 0 ether; } else if(tsAmount > 1000 && tsAmount <= 1009) { price = (tsAmount - 1000) * PRICE; } if(tsAmount > 1000) { require(msg.value >= price, "Not enough ether sent"); } for (uint256 i; i < amount ; i++) { _safeMint(msg.sender, ts + i); } if (msg.value > price) { (bool success, ) = payable(msg.sender).call{value: msg.value - price}(""); require(success, "Transfer failed"); } } receive() external payable {} // NOTE: Get the chain link latest price from: https://docs.chain.link/docs/get-the-latest-price/ function previewEthValue(int256 _ethprice) public view returns(int256){ int256 latestPrice = _ethprice; int256 ethValue = ((1_000_000 * 10 ** 10) / latestPrice) * 10 ** 16; return ethValue; } // NOTE: Cannot draw a winner until collection is sold out function drawWinner() public onlyOwner soldOut{ uint256 tokenWinner = randomResult; int256 latestPrice = getLatestPrice(); int256 ethValue = ((1_000_000 * 10 ** 10) / latestPrice) * 10 ** 16; address addressWinner = ownerOf(tokenWinner); (bool success, ) = payable(addressWinner).call{value: uint256(ethValue) }(""); require(success, "Transfer failed"); IS_DRAWN = true; winner = addressWinner; } // NOTE: Cannot withdraw until collection is sold out and winner has been paid function withdrawAll() public onlyOwner soldOut { require(IS_DRAWN, "Collection winner not drawn yet"); (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); require(success, "Transfer failed"); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return "ipfs://QmVSymhzQAaY5FSEf8aVkKrTPYfXLzCYiUWq2woxsSmrvm"; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; contract RandomNumber is VRFConsumerBase { bytes32 internal keyHash; uint256 internal fee; uint256 public randomResult = 10000; /** * Constructor inherits VRFConsumerBase * * Network: Kovan * Chainlink VRF Coordinator address: 0xdD3782915140c8f3b190B5D67eAc6dc5760C46E9 * LINK token address: 0xa36085F69e2889c224210F603D836748e7dC0088 * Key Hash: 0x6c3699283bda56ad74f6b855546325b68d482e983852a7a82979cc4807b641f4 */ constructor() VRFConsumerBase( 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator 0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token ) { keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; fee = 2 * 10 ** 18; // 0.1 LINK (Varies by network) } /** * Requests randomness */ function getRandomNumber() public returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet"); return requestRandomness(keyHash, fee); } /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomResult = (randomness % 10000) + 1; } // function withdrawLink() external {} - Implement a withdraw function to avoid locking your LINK in the contract } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; contract Aggregator { AggregatorV3Interface internal priceFeed; /** * Network: Kovan * Aggregator: ETH/USD * Address: 0x9326BFA02ADD2366b30bacB125260Af641031331 */ constructor() { priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); } /** * Returns the latest price */ function getLatestPrice() public view returns (int) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); return price; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @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 Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 private constant USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface internal immutable LINK; address private immutable vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 => uint256) /* keyHash */ /* nonce */ private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool success); function transferFrom( address from, address to, uint256 value ) external returns (bool success); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); }
NOTE: Cannot withdraw until collection is sold out and winner has been paid
function withdrawAll() public onlyOwner soldOut { require(IS_DRAWN, "Collection winner not drawn yet"); require(success, "Transfer failed"); }
14,692,382
[ 1, 17857, 30, 14143, 598, 9446, 3180, 1849, 353, 272, 1673, 596, 471, 5657, 1224, 711, 2118, 30591, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 598, 9446, 1595, 1435, 1071, 1338, 5541, 272, 1673, 1182, 288, 203, 1377, 2583, 12, 5127, 67, 28446, 5665, 16, 315, 2532, 5657, 1224, 486, 19377, 4671, 8863, 203, 203, 1377, 2583, 12, 4768, 16, 315, 5912, 2535, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-03-28 */ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.10; abstract contract IDfxOracle { function read() public virtual view returns (uint256); } // OpenZeppelin Contracts (last updated v4.5.0) (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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) // OpenZeppelin Contracts (last updated v4.5.0) (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 * ==== * * [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); } } } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) // OpenZeppelin Contracts v4.4.1 (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 ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } /** * @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 onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _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()); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) // OpenZeppelin Contracts v4.4.1 (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 IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `_msgSender()` is missing `role`. * Overriding this function changes the behavior of the {onlyRole} modifier. * * Format of the revert message is described in {_checkRole}. * * _Available since v4.6._ */ function _checkRole(bytes32 role) internal view virtual { _checkRole(role, _msgSender()); } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) /** * @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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @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); } /** * @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 Contracts guidelines: functions revert * instead 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, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string internal _name; string internal _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _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: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, 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}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, 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}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, 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) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, 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) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(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"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(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 Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[45] private __gap; } contract DfxCadcState is AccessControlUpgradeable, ERC20Upgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { /***** Constants *****/ // Super user role bytes32 public constant SUDO_ROLE = keccak256("dfxcadc.role.sudo"); bytes32 public constant SUDO_ROLE_ADMIN = keccak256("dfxcadc.role.sudo.admin"); // Poke role bytes32 public constant POKE_ROLE = keccak256("dfxcadc.role.poke"); bytes32 public constant POKE_ROLE_ADMIN = keccak256("dfxcadc.role.poke.admin"); // Market makers don't need to pay a mint/burn fee bytes32 public constant MARKET_MAKER_ROLE = keccak256("dfxcadc.role.mm"); bytes32 public constant MARKET_MAKER_ROLE_ADMIN = keccak256("dfxcadc.role.mm.admin"); // Collateral defenders to perform buyback and recollateralization bytes32 public constant CR_DEFENDER = keccak256("dfxcadc.role.cr-defender"); bytes32 public constant CR_DEFENDER_ADMIN = keccak256("dfxcadc.role.cr-defender.admin"); // Can only poke the contracts every day uint256 public constant POKE_WAIT_PERIOD = 1 days; uint256 public constant MAX_POKE_RATIO_DELTA = 1e16; // 1% max change per day // Underlyings address public constant DFX = 0x888888435FDe8e7d4c54cAb67f206e4199454c60; address public constant CADC = 0xcaDC0acd4B445166f12d2C07EAc6E2544FbE2Eef; /***** Variables *****/ /* !!!! Important !!!! */ // Do _not_ change the layout of the variables // as you'll be changing the slots // TWAP Oracle address // 1 DFX = X CAD? address public dfxCadTwap; // Will only be backed by DFX and CADC so this should be sufficient // Ratio should be number between 0 - 1e18 // dfxRatio + cadcRatio should equal to 1e18 // 5e17 = ratio of 50% uint256 public cadcRatio; uint256 public dfxRatio; // How much delta will each 'poke' consist of // i.e. say pokeRatioDelta = 1e16 = 1% // dfxRatio = 5e17 = 50% // cadcRatio = 5e17 = 50% // Poking up = dfxRatio = 51e16 = 51% // cadcRatio = 49e16 = 49% // Poking down = dfxRatio = 49e16 = 49% // cadcRatio = 51e16 = 51% uint256 public pokeRatioDelta; // Fee recipient and mint/burn fee, starts off at 0.5% address public feeRecipient; uint256 public mintBurnFee; // Last poke time uint256 public lastPokeTime; } /// @notice Math library that facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision. /// @author Adapted from https://github.com/Uniswap/uniswap-v3-core/blob/main/contracts/libraries/FullMath.sol. /// @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 an 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) { unchecked { // 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 = uint256(-int256(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 // 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 an 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); unchecked { if (mulmod(a, b, denominator) != 0) { require(result < type(uint256).max); result++; } } } } contract DfxCadLogicV1 is DfxCadcState { using SafeERC20 for IERC20; // **** Initializing functions **** // We don't need the old initialize logic as the state has // already been set, this is just to change the name + symbol function initialize() public { // Don't initialize twice require(keccak256(bytes(name())) == keccak256(bytes("dfxCADC")), "no-reinit"); // Assign new name and symbol _name = "dfxCAD"; _symbol = "dfxCAD"; } // **** Modifiers **** modifier updatePokes() { // Make sure we can poke require( block.timestamp > lastPokeTime + POKE_WAIT_PERIOD, "invalid-poke-time" ); _; // Sanity checks require( dfxRatio > 0 && dfxRatio < 1e18 && cadcRatio > 0 && cadcRatio < 1e18, "invalid-ratios" ); lastPokeTime = block.timestamp; } // **** Restricted functions **** // Sets the 'poke' delta /// @notice Manually sets the delta between each poke /// @param _pokeRatioDelta The delta between each poke, 100% = 1e18. function setPokeDelta(uint256 _pokeRatioDelta) public onlyRole(SUDO_ROLE) { require( _pokeRatioDelta <= MAX_POKE_RATIO_DELTA, "poke-ratio-delta: too big" ); pokeRatioDelta = _pokeRatioDelta; } /// @notice Used when market price / TWAP is > than backing. /// If set correctly, the underlying backing of the stable /// assets will decrease and the underlying backing of the volatile /// assets will increase. function pokeUp() public onlyRole(POKE_ROLE) updatePokes { dfxRatio = dfxRatio + pokeRatioDelta; cadcRatio = cadcRatio - pokeRatioDelta; } /// @notice Used when market price / TWAP is < than backing. /// If set correctly, the underlying backing of the stable /// assets will increase and the underlying backing of the volatile /// assets will decrease function pokeDown() public onlyRole(POKE_ROLE) updatePokes { dfxRatio = dfxRatio - pokeRatioDelta; cadcRatio = cadcRatio + pokeRatioDelta; } /// @notice Sets the TWAP address function setDfxCadTwap(address _dfxCadTwap) public onlyRole(SUDO_ROLE) { dfxCadTwap = _dfxCadTwap; } /// @notice Sets the fee recipient for mint/burn function setFeeRecipient(address _recipient) public onlyRole(SUDO_ROLE) { feeRecipient = _recipient; } /// @notice In case anyone sends tokens to the wrong address function recoverERC20(address _a) public onlyRole(SUDO_ROLE) { require(_a != DFX && _a != CADC, "no"); IERC20(_a).safeTransfer( msg.sender, IERC20(_a).balanceOf(address(this)) ); } /// @notice Sets mint/burn fee function setMintBurnFee(uint256 _f) public onlyRole(SUDO_ROLE) { require(_f < 1e18, "invalid-fee"); mintBurnFee = _f; } /// @notice Emergency trigger function setPaused(bool _p) public onlyRole(SUDO_ROLE) { if (_p) { _pause(); } else { _unpause(); } } /// @notice Execute functionality used to perform buyback and recollateralization function execute(address _target, bytes memory _data) public onlyRole(CR_DEFENDER) returns (bytes memory response) { require(_target != address(0), "target-address-required"); // call contract in current context assembly { let succeeded := delegatecall( sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0 ) let size := returndatasize() response := mload(0x40) mstore( 0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))) ) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } // **** Public stateful functions **** /// @notice Mints the ASC token /// @param _amount Amount of ASC token to mint function mint(uint256 _amount) public nonReentrant whenNotPaused { require(_amount > 0, "non-zero only"); (uint256 cadcAmount, uint256 dfxAmount) = getUnderlyings(_amount); IERC20(CADC).safeTransferFrom(msg.sender, address(this), cadcAmount); IERC20(DFX).safeTransferFrom(msg.sender, address(this), dfxAmount); // No fee for market makers if (hasRole(MARKET_MAKER_ROLE, msg.sender)) { _mint(msg.sender, _amount); } else { uint256 _fee = (_amount * mintBurnFee) / 1e18; _mint(msg.sender, _amount - _fee); _mint(feeRecipient, _fee); } } /// @notice Burns the ASC token /// @param _amount Amount of ASC token to burn function burn(uint256 _amount) public nonReentrant whenNotPaused { require(_amount > 0, "non-zero only"); // No fee for market makers if (hasRole(MARKET_MAKER_ROLE, msg.sender)) { _burn(msg.sender, _amount); } else { uint256 _fee = (_amount * mintBurnFee) / 1e18; _burn(msg.sender, _amount); _mint(feeRecipient, _fee); _amount = _amount - _fee; } (uint256 cadcAmount, uint256 dfxAmount) = getUnderlyings(_amount); IERC20(CADC).safeTransfer(msg.sender, cadcAmount); IERC20(DFX).safeTransfer(msg.sender, dfxAmount); } // **** View only functions **** /// @notice Get the underlyings of `_amount` of 'logic' tokens /// For example, how many underlyings will `_amount` token yield? /// Or, how many underlyings do I need to mint `_amount` token? /// @param _amount The amount of 'logic' token function getUnderlyings(uint256 _amount) public view returns (uint256 cadcAmount, uint256 dfxAmount) { uint256 cadPerDfx = IDfxOracle(dfxCadTwap).read(); cadcAmount = FullMath.mulDivRoundingUp(_amount, cadcRatio, 1e18); dfxAmount = FullMath.mulDivRoundingUp(_amount, dfxRatio, 1e18); dfxAmount = FullMath.mulDivRoundingUp(dfxAmount, 1e18, cadPerDfx); } }
@notice Get the underlyings of `_amount` of 'logic' tokens For example, how many underlyings will `_amount` token yield? Or, how many underlyings do I need to mint `_amount` token? @param _amount The amount of 'logic' token
function getUnderlyings(uint256 _amount) public view returns (uint256 cadcAmount, uint256 dfxAmount) { uint256 cadPerDfx = IDfxOracle(dfxCadTwap).read(); cadcAmount = FullMath.mulDivRoundingUp(_amount, cadcRatio, 1e18); dfxAmount = FullMath.mulDivRoundingUp(_amount, dfxRatio, 1e18); dfxAmount = FullMath.mulDivRoundingUp(dfxAmount, 1e18, cadPerDfx); }
7,859,941
[ 1, 967, 326, 3613, 715, 899, 434, 1375, 67, 8949, 68, 434, 296, 28339, 11, 2430, 540, 2457, 3454, 16, 3661, 4906, 3613, 715, 899, 903, 1375, 67, 8949, 68, 1147, 2824, 35, 540, 2965, 16, 3661, 4906, 3613, 715, 899, 741, 467, 1608, 358, 312, 474, 1375, 67, 8949, 68, 1147, 35, 225, 389, 8949, 1021, 3844, 434, 296, 28339, 11, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 10833, 765, 715, 899, 12, 11890, 5034, 389, 8949, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 28451, 71, 6275, 16, 2254, 5034, 3013, 92, 6275, 13, 203, 565, 288, 203, 3639, 2254, 5034, 28451, 2173, 40, 19595, 273, 1599, 19595, 23601, 12, 2180, 14626, 361, 23539, 438, 2934, 896, 5621, 203, 203, 3639, 28451, 71, 6275, 273, 11692, 10477, 18, 16411, 7244, 11066, 310, 1211, 24899, 8949, 16, 28451, 71, 8541, 16, 404, 73, 2643, 1769, 203, 3639, 3013, 92, 6275, 273, 11692, 10477, 18, 16411, 7244, 11066, 310, 1211, 24899, 8949, 16, 3013, 92, 8541, 16, 404, 73, 2643, 1769, 203, 3639, 3013, 92, 6275, 273, 11692, 10477, 18, 16411, 7244, 11066, 310, 1211, 12, 2180, 92, 6275, 16, 404, 73, 2643, 16, 28451, 2173, 40, 19595, 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 ]
pragma solidity ^0.5.8; /** * @title The standard ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address, uint256) external returns (bool); function approve(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address) external view returns (uint256); function allowance(address, address) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed holder, address indexed spender, uint256 value); } /// @title Time-delayed ERC-20 wallet contract. /// Can only transfer tokens after publicly recording the intention to do so /// at least four weeks in advance. contract SlowWallet { // TYPES struct TransferProposal { address destination; uint256 value; uint256 time; string notes; bool closed; } // DATA IERC20 public token; uint256 public constant delay = 4 weeks; address public owner; // PROPOSALS mapping (uint256 => TransferProposal) public proposals; uint256 public proposalsLength; // EVENTS event TransferProposed( uint256 index, address indexed destination, uint256 value, uint256 delayUntil, string notes ); event TransferConfirmed(uint256 index, address indexed destination, uint256 value, string notes); event TransferCancelled(uint256 index, address indexed destination, uint256 value, string notes); event AllTransfersCancelled(); // FUNCTIONALITY constructor(address tokenAddress) public { token = IERC20(tokenAddress); owner = 0xA7b123D54BcEc14b4206dAb796982a6d5aaA6770; } modifier onlyOwner() { require(msg.sender == owner, "must be owner"); _; } /// Propose a new transfer, which can be confirmed after two weeks. function propose(address destination, uint256 value, string calldata notes) external onlyOwner { // Delay by at least two weeks. // We are relying on block.timestamp for this, and aware of the possibility of its // manipulation by miners. But we are working at a timescale that is already much // longer than the variance in timestamps we have observed and expect in the future, // so we are satisfied with this choice. // solium-disable-next-line security/no-block-members uint256 delayUntil = now + delay; require(delayUntil >= now, "delay overflowed"); proposals[proposalsLength] = TransferProposal({ destination: destination, value: value, time: delayUntil, notes: notes, closed: false }); proposalsLength++; emit TransferProposed(proposalsLength-1, destination, value, delayUntil, notes); } /// Cancel a proposed transfer. function cancel(uint256 index, address addr, uint256 value) external onlyOwner { // Check authorization. requireMatchingOpenProposal(index, addr, value); // Cancel transfer. proposals[index].closed = true; emit TransferCancelled(index, addr, value, proposals[index].notes); } /// Mark all proposals "void", in O(1). function voidAll() external onlyOwner { proposalsLength = 0; emit AllTransfersCancelled(); } /// Confirm and execute a proposed transfer, if enough time has passed since it was proposed. function confirm(uint256 index, address destination, uint256 value) external onlyOwner { // Check authorization. requireMatchingOpenProposal(index, destination, value); // See commentary above about using `now`. // solium-disable-next-line security/no-block-members require(proposals[index].time < now, "too early"); // Record execution of transfer. proposals[index].closed = true; emit TransferConfirmed(index, destination, value, proposals[index].notes); // Proceed with execution of transfer. require(token.transfer(destination, value)); } /// Throw unless the given transfer proposal exists and matches `destination` and `value`. function requireMatchingOpenProposal(uint256 index, address destination, uint256 value) private view { require(index < proposalsLength, "index too high, or transfer voided"); require(!proposals[index].closed, "transfer already closed"); // Slither reports "dangerous strict equality" for each of these, but it's OK. // These equalities are to confirm that the transfer entered is equal to the // matching previous transfer. We're vetting data entry; strict equality is appropriate. require(proposals[index].destination == destination, "destination mismatched"); require(proposals[index].value == value, "value mismatched"); } }
Propose a new transfer, which can be confirmed after two weeks. Delay by at least two weeks. We are relying on block.timestamp for this, and aware of the possibility of its manipulation by miners. But we are working at a timescale that is already much longer than the variance in timestamps we have observed and expect in the future, so we are satisfied with this choice. solium-disable-next-line security/no-block-members
function propose(address destination, uint256 value, string calldata notes) external onlyOwner { uint256 delayUntil = now + delay; require(delayUntil >= now, "delay overflowed"); proposals[proposalsLength] = TransferProposal({ destination: destination, value: value, time: delayUntil, notes: notes, closed: false }); proposalsLength++; emit TransferProposed(proposalsLength-1, destination, value, delayUntil, notes); }
6,874,275
[ 1, 626, 4150, 279, 394, 7412, 16, 1492, 848, 506, 19979, 1839, 2795, 17314, 18, 20165, 635, 622, 4520, 2795, 17314, 18, 1660, 854, 283, 6291, 603, 1203, 18, 5508, 364, 333, 16, 471, 18999, 434, 326, 25547, 434, 2097, 27029, 635, 1131, 414, 18, 12484, 732, 854, 5960, 622, 279, 1658, 31402, 716, 353, 1818, 9816, 7144, 2353, 326, 12380, 316, 11267, 732, 1240, 12117, 471, 4489, 316, 326, 3563, 16, 1427, 732, 854, 18958, 598, 333, 6023, 18, 3704, 5077, 17, 8394, 17, 4285, 17, 1369, 4373, 19, 2135, 17, 2629, 17, 7640, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 450, 4150, 12, 2867, 2929, 16, 2254, 5034, 460, 16, 533, 745, 892, 10913, 13, 3903, 1338, 5541, 288, 203, 3639, 2254, 5034, 4624, 9716, 273, 2037, 397, 4624, 31, 203, 3639, 2583, 12, 10790, 9716, 1545, 2037, 16, 315, 10790, 9391, 329, 8863, 203, 203, 3639, 450, 22536, 63, 685, 22536, 1782, 65, 273, 12279, 14592, 12590, 203, 5411, 2929, 30, 2929, 16, 203, 5411, 460, 30, 460, 16, 203, 5411, 813, 30, 4624, 9716, 16, 203, 5411, 10913, 30, 10913, 16, 203, 5411, 4375, 30, 629, 203, 3639, 15549, 203, 3639, 450, 22536, 1782, 9904, 31, 203, 203, 3639, 3626, 12279, 626, 7423, 12, 685, 22536, 1782, 17, 21, 16, 2929, 16, 460, 16, 4624, 9716, 16, 10913, 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 ]
./partial_match/1/0x4Daf6fA04bA9af69535395EB1517C4316083D8cC/sources/ERC20Pistachio.sol
* @dev Public functions to make the contract accesible/ Initialize Contract Parameters
constructor (address initialAccount, string memory _tokenSymbol, string memory _tokenName, uint256 initialBalance) public { symbol = _tokenSymbol; name = _tokenName; _mint(initialAccount, initialBalance); }
4,488,817
[ 1, 4782, 4186, 358, 1221, 326, 6835, 1721, 764, 1523, 19, 9190, 13456, 7012, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3885, 261, 2867, 2172, 3032, 16, 533, 3778, 389, 2316, 5335, 16, 533, 3778, 389, 2316, 461, 16, 2254, 5034, 2172, 13937, 13, 1071, 288, 203, 203, 3639, 3273, 273, 389, 2316, 5335, 31, 203, 3639, 508, 273, 389, 2316, 461, 31, 203, 203, 3639, 389, 81, 474, 12, 6769, 3032, 16, 2172, 13937, 1769, 203, 540, 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 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract PKKTToken is ERC20, Ownable { /** * @dev A record status of minter. */ mapping (address => bool) public minters; mapping (address => uint256) public mintingAllowance; /** * @dev maximum amount can be minted. */ uint256 private immutable _cap; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); event MintingAllowanceUpdated(address indexed account, uint256 oldAllowance, uint256 newAllowance); constructor(string memory tokenName, string memory symbol, uint256 cap_) public ERC20(tokenName, symbol) { minters[msg.sender] = true; _cap = cap_; } function cap() public view returns(uint256) { return _cap; } function isMinter(address _account) public view returns(bool) { return minters[_account]; } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint _amount) public onlyOwner { _burn(msg.sender, _amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address _account, uint256 _amount) public virtual onlyOwner { uint256 decreasedAllowance = allowance(_account, msg.sender).sub(_amount, "ERC20: burn amount exceeds allowance"); _approve(_account, msg.sender, decreasedAllowance); _burn(_account, _amount); } /// @notice Creates `_amount` token to `_to`. Must only be called by the minter . function mint(address _to, uint256 _amount) public virtual { require(minters[msg.sender], "must have minter role to mint"); require(mintingAllowance[msg.sender] >= _amount, "mint amount exceeds allowance"); require(totalSupply().add(_amount) <= _cap, "mint amount exceeds cap"); mintingAllowance[msg.sender] = mintingAllowance[msg.sender].sub(_amount); _mint(_to, _amount); } /// @notice Add `_minter` . Must only be called by the owner . function addMinter(address _minter,uint256 _amount) public virtual onlyOwner { minters[_minter] = true; mintingAllowance[_minter] = _amount; emit MinterAdded(_minter); } /// @notice Remove `_minter` . Must only be called by the owner . function removeMinter(address _minter) public virtual onlyOwner { minters[_minter] = false; mintingAllowance[_minter] = 0; emit MinterRemoved(_minter); } /// @notice Increase minting allowance for minter` . Must only be called by the owner . function increaseMintingAllowance(address _minter, uint256 _addedValue) public virtual onlyOwner { uint256 currentMintingAllowance = mintingAllowance[_minter]; mintingAllowance[_minter] = currentMintingAllowance.add(_addedValue); emit MintingAllowanceUpdated(_minter, currentMintingAllowance, currentMintingAllowance.add(_addedValue)); } /// @notice Decrease minting allowance for minter` . Must only be called by the owner . function decreaseMintingAllowance(address _minter, uint256 _subtractedValue) public virtual onlyOwner { uint256 currentMintingAllowance = mintingAllowance[_minter]; mintingAllowance[_minter] = currentMintingAllowance.sub(_subtractedValue,"decreased allowance below zero"); emit MintingAllowanceUpdated(_minter, currentMintingAllowance, currentMintingAllowance.sub(_subtractedValue)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.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; 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 { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 () 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; } } // 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.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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; } }
@notice Add `_minter` . Must only be called by the owner .
function addMinter(address _minter,uint256 _amount) public virtual onlyOwner { minters[_minter] = true; mintingAllowance[_minter] = _amount; emit MinterAdded(_minter); }
54,073
[ 1, 986, 1375, 67, 1154, 387, 68, 263, 6753, 1338, 506, 2566, 635, 326, 3410, 263, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 49, 2761, 12, 2867, 389, 1154, 387, 16, 11890, 5034, 389, 8949, 13, 1071, 5024, 1338, 5541, 288, 203, 3639, 1131, 5432, 63, 67, 1154, 387, 65, 273, 638, 31, 203, 3639, 312, 474, 310, 7009, 1359, 63, 67, 1154, 387, 65, 273, 389, 8949, 31, 203, 3639, 3626, 490, 2761, 8602, 24899, 1154, 387, 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 ]
./full_match/1/0xD5d3299585580F10151f991698578a02Fe327Fb9/sources/contracts/CanvaIsland.sol
when was the last harvest, 0 for fixed supply target
uint lastHarvestedAtBlock;
17,145,037
[ 1, 13723, 1703, 326, 1142, 17895, 26923, 16, 374, 364, 5499, 14467, 1018, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 1142, 44, 297, 90, 3149, 861, 1768, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.4; contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256 balance); function transfer(address to, uint256 value) public returns (bool success); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256 remaining); function transferFrom(address from, address to, uint256 value) public returns (bool success); function approve(address spender, uint256 value) public returns (bool success); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @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 Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) public 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 success) { 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 Standard ERC20 token * * @dev Implementation of the basic standard token. */ 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 amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { 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[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @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 success) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); 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 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @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; /** * @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)); owner = newOwner; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will recieve the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } // Токен contract GWTToken is MintableToken { string public constant name = "Global Wind Token"; string public constant symbol = "GWT"; uint32 public constant decimals = 18; } // Контракт краудсейла contract GWTCrowdsale is Ownable { using SafeMath for uint; uint public supplyLimit; // Лимит выпуска токенов address ethAddress; // Адрес получателя эфира uint saleStartTimestamp; // Таймштамп запуска контракта uint public currentStageNumber; // Номер периода uint currentStageStartTimestamp; // Таймштамп старта периода uint currentStageEndTimestamp; // Таймштамп окончания периода uint currentStagePeriodDays; // Кол-во дней (в тестовом минут) проведения периода краудсейла uint public baseExchangeRate; // Курс обмена на токены uint currentStageMultiplier; // Множитель для разных этапов: bcostReal = baseExchangeRate * currentStageMultiplier uint constant M = 1000000000000000000; // 1 GWT = 10^18 GWTunits (wei) uint[] _percs = [40, 30, 25, 20, 15, 10, 5, 0, 0]; // Бонусные проценты uint[] _days = [42, 1, 27, 1, 7, 7, 7, 14, 0]; // Продолжительность в днях // Лимиты на выпуск токенов uint PrivateSaleLimit = M.mul(420000000); uint PreSaleLimit = M.mul(1300000000); uint TokenSaleLimit = M.mul(8400000000); uint RetailLimit = M.mul(22490000000); // Курсы обмена токенов на эфир uint TokensaleRate = M.mul(160000); uint RetailRate = M.mul(16000); GWTToken public token = new GWTToken(); // Токен // Активен ли краудсейл modifier isActive() { require(isInActiveStage()); _; } function isInActiveStage() private returns(bool) { if (currentStageNumber == 8) return true; if (now >= currentStageStartTimestamp && now <= currentStageEndTimestamp){ return true; }else if (now < currentStageStartTimestamp) { return false; }else if (now > currentStageEndTimestamp){ if (currentStageNumber == 0 || currentStageNumber == 2 || currentStageNumber == 7) return false; switchPeriod(); // It is not possible for stage to be finished after straight the start // Also new set currentStageStartTimestamp and currentStageEndTimestamp should be valid by definition //return isInActiveStage(); return true; } // That will never get reached return false; } // Перейти к следующему периоду function switchPeriod() private onlyOwner { if (currentStageNumber == 8) return; currentStageNumber++; currentStageStartTimestamp = currentStageEndTimestamp; // Запуск производится от конца прошлого периода, если нужно запустить с текущего момента поменяйте на now currentStagePeriodDays = _days[currentStageNumber]; currentStageEndTimestamp = currentStageStartTimestamp + currentStagePeriodDays * 1 days; currentStageMultiplier = _percs[currentStageNumber]; if(currentStageNumber == 0 ){ supplyLimit = PrivateSaleLimit; } else if(currentStageNumber < 3){ supplyLimit = PreSaleLimit; } else if(currentStageNumber < 8){ supplyLimit = TokenSaleLimit; } else { // Base rate for phase 8 should update exchange rate baseExchangeRate = RetailRate; supplyLimit = RetailLimit; } } function setStage(uint _index) public onlyOwner { require(_index >= 0 && _index < 9); if (_index == 0) return startPrivateSale(); currentStageNumber = _index - 1; currentStageEndTimestamp = now; switchPeriod(); } // Установить курс обмена function setRate(uint _rate) public onlyOwner { baseExchangeRate = _rate; } // Установить можитель function setBonus(uint _bonus) public onlyOwner { currentStageMultiplier = _bonus; } function setTokenOwner(address _newTokenOwner) public onlyOwner { token.transferOwnership(_newTokenOwner); } // Установить продолжительность текущего периода в днях function setPeriodLength(uint _length) public onlyOwner { // require(now < currentStageStartTimestamp + _length * 1 days); currentStagePeriodDays = _length; currentStageEndTimestamp = currentStageStartTimestamp + currentStagePeriodDays * 1 days; } // Изменить лимит выпуска токенов function modifySupplyLimit(uint _new) public onlyOwner { if (_new >= token.totalSupply()){ supplyLimit = _new; } } // Выпустить токены на кошелек function mintFor(address _to, uint _val) public onlyOwner isActive payable { require(token.totalSupply() + _val <= supplyLimit); token.mint(_to, _val); } // Прекратить выпуск токенов // ВНИМАНИЕ! После вызова этой функции перезапуск будет невозможен! function closeMinting() public onlyOwner { token.finishMinting(); } // Запуск прив. сейла function startPrivateSale() public onlyOwner { currentStageNumber = 0; currentStageStartTimestamp = now; currentStagePeriodDays = _days[0]; currentStageMultiplier = _percs[0]; supplyLimit = PrivateSaleLimit; currentStageEndTimestamp = currentStageStartTimestamp + currentStagePeriodDays * 1 days; baseExchangeRate = TokensaleRate; } function startPreSale() public onlyOwner { currentStageNumber = 0; currentStageEndTimestamp = now; switchPeriod(); } function startTokenSale() public onlyOwner { currentStageNumber = 2; currentStageEndTimestamp = now; switchPeriod(); } function endTokenSale() public onlyOwner { currentStageNumber = 7; currentStageEndTimestamp = now; switchPeriod(); } // 000000000000000000 - 18 нулей, добавить к сумме в целых GWT // Старт function GWTCrowdsale() public { // Init ethAddress = 0xB93B2be636e39340f074F0c7823427557941Be42; // Записываем адрес, на который будет пересылаться эфир // ethAddress = 0x16a49c8af25b3c2ff315934bf38a4cf645813844; // Dev saleStartTimestamp = now; // Записываем дату деплоя startPrivateSale(); } function changeEthAddress(address _newAddress) public onlyOwner { ethAddress = _newAddress; } // Автоматическая покупка токенов function createTokens() public isActive payable { uint tokens = baseExchangeRate.mul(msg.value).div(1 ether); // Переводим ETH в GWT if (currentStageMultiplier > 0 && currentStageEndTimestamp > now) { // Начисляем бонус tokens = tokens + tokens.div(100).mul(currentStageMultiplier); } // require(tokens > minLimit && tokens < buyLimit); require(token.totalSupply() + tokens <= supplyLimit); ethAddress.transfer(msg.value); // переводим на основной кошелек token.mint(msg.sender, tokens); // Начисляем } // Если кто-то перевел эфир на контракт function() external payable { createTokens(); // Вызываем функцию начисления токенов } }
Установить можитель
function setBonus(uint _bonus) public onlyOwner { currentStageMultiplier = _bonus; }
5,351,943
[ 1, 145, 101, 146, 228, 146, 229, 145, 113, 145, 126, 145, 127, 145, 115, 145, 121, 146, 229, 146, 239, 225, 145, 125, 145, 127, 145, 119, 145, 121, 146, 229, 145, 118, 145, 124, 146, 239, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 15268, 22889, 12, 11890, 389, 18688, 407, 13, 1071, 1338, 5541, 288, 203, 3639, 783, 8755, 23365, 273, 389, 18688, 407, 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 ]
./full_match/4/0x3B0dE749344778659D77CED7b076e00fB7378731/sources/contracts/pix_v5.sol
maps proposalID to Proposal struct
mapping(uint => Proposal) public proposals;
683,402
[ 1, 10711, 14708, 734, 358, 19945, 1958, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 516, 19945, 13, 1071, 450, 22536, 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 ]
./full_match/5/0xB059401C4cD2a5083E8468C406396C24C2604050/sources/project_/contracts/StakingEME.sol
42,528,000,000 $EME
totalPool[0] = 42528*1e24;
7,060,213
[ 1, 9452, 16, 25, 6030, 16, 3784, 16, 3784, 271, 41, 958, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2078, 2864, 63, 20, 65, 273, 1059, 2947, 6030, 14, 21, 73, 3247, 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: MIT pragma solidity =0.8.6; import "./OwnableToken.sol"; import "./ERC20Interface.sol"; contract AgriUTToken is OwnableToken, ERC20Interface { string private _name; string private _symbol; uint8 private _decimals = 18; uint256 private _totalSupply; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint256) private _balances; mapping(address => bool) private _frozenAccounts; mapping(address => bool) private _managedAccounts; event FrozenFunds(address indexed target, bool frozen); event Burn(address indexed from, uint256 value); event ManagedAccount(address indexed target, bool managed); /* Initializes contract with initial supply tokens to the creator of the contract */ constructor( uint256 initialSupply, string memory tokenName, string memory tokenSymbol) { _totalSupply = initialSupply * 10 ** uint256(_decimals); // Update total supply with the decimal amount _balances[msg.sender] = _totalSupply; // Give the creator all initial tokens _name = tokenName; // Set the name for display purposes _symbol = tokenSymbol; // Set the symbol for display purposes } /* returns number of decimals */ function decimals() public view returns (uint8) { return _decimals; } /* returns total supply */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /* Name of Token */ function name() public view returns (string memory) { return _name; } /* Symbol of Token */ function symbol() public view returns (string memory) { return _symbol; } /* returns Balance of given account */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /* returns frozen state of given account */ function frozenAccount(address _account) public view returns (bool frozen) { return _frozenAccounts[_account]; } /* returns flag if given account is managed */ function managedAccount(address _account) public view returns (bool managed) { return _managedAccounts[_account]; } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint256 _value) internal { require (_to != address(0x0), "ERC20: No transfer to 0x0 address"); // Prevent transfer to 0x0 address. Use burn() instead require (_balances[_from] >= _value, "ERC20: Insufficent tokens"); // Check if the sender has enough require (_balances[_to] + _value >= _balances[_to], "ERC20:Invalid amount"); // Check for overflows require(!_frozenAccounts[_from], "From account frozen"); // Check if sender is frozen require(!_frozenAccounts[_to], "To account frozen"); // Check if recipient is frozen require (_balances[_to] + _value <= _totalSupply, "ERC20: Total supply exceeded"); //Ensure allocate more than total supply to 1 account _balances[_from] -= _value; // Subtract from the sender _balances[_to] += _value; // Add the same to the recipient emit Transfer(_from, _to, _value); } /** * Transfer tokens * Send _value tokens to _to from your account * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public override returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from 1 account to another * Send _value tokens to _to from specified account * @param sender The address of the sender * @param recipient The address of the recipient * @param amount the amount to send */ function transferFrom( address sender, address recipient, uint256 amount) public virtual override returns (bool) { uint256 currentAllowance = _allowances[sender][msg.sender]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, msg.sender, currentAllowance - amount); } _transfer(sender, recipient, amount); return true; } /** * Transfer tokens from 1 account to another * Send _value tokens to _to from specified account * @param sender The address of the sender * @param recipient The address of the recipient * @param amount the amount to send */ function transferFromGivenApproval( address sender, address recipient, uint256 amount) external onlyOwner returns (bool) { require(_managedAccounts[sender], "Not a Managed wallet"); _transfer(sender, recipient, amount); return true; } /** * Approves owner to be able to transfer on users behalf * @param allowed flag to indicate if allowed to manage */ function approveOwnerToManage(bool allowed) external returns (bool) { _managedAccounts[msg.sender] = allowed; emit ManagedAccount(msg.sender, allowed); return true; } /** * Approve address to spend token on behalf of caller * @param spender account to grant permission * @param amount which spender can access */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } function _approve( address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /* * Returns allowance * @param tokenOwner account owner * @param spender account allowed to use tokens */ function allowance(address tokenOwner, address spender) public view override returns (uint256 remaining) { return _allowances[tokenOwner][spender]; } /// @notice Prevent / allow target from sending and receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner external { require(target != owner(), "Cannot freeze the owner account"); _frozenAccounts[target] = freeze; emit FrozenFunds(target, freeze); } /** * Destroy tokens * Remove _value tokens from the system irreversibly * @param _value the amount of money to burn */ function burn(uint256 _value) external returns (bool success) { _burn(msg.sender, _value); return true; } /** * Burn With Approval * Burns tokens from a pre-approved address * @param _from the address of the sender * @param _value the amount of money to burn */ function burnWithApproval(address _from, uint256 _value) external onlyOwner returns (bool success) { require(_managedAccounts[_from], "Not a Managed wallet"); _burn(_from, _value); return true; } /** * Destroy tokens from other account * Remove _value tokens from the system irreversibly on behalf of _from * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) external returns (bool success) { uint256 currentAllowance = allowance(_from, msg.sender); require(currentAllowance >= _value, "ERC20: burn amount exceeds allowance"); unchecked { _approve(_from, msg.sender, currentAllowance - _value); } _burn(_from, _value); return true; } function _burn(address _address, uint256 _value) internal { require(_address != address(0), "ERC20: burn from the zero address"); require(_balances[_address] >= _value, "ERC20: burn amount exceeds balance"); // Check if the targeted balance is enough require(!_frozenAccounts[_address], "Account is frozen"); _balances[_address] -= _value; // Subtract from the targeted balance _totalSupply -= _value; // Update totalSupply emit Burn(_address, _value); } }
Subtract from the targeted balance
_balances[_address] -= _value;
5,396,831
[ 1, 27904, 628, 326, 20715, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 70, 26488, 63, 67, 2867, 65, 3947, 389, 1132, 31, 18701, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "./utils/OwnablePausable.sol"; contract Budget is OwnablePausable { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; /// @dev Expenditure item. struct Expenditure { address recipient; uint256 min; uint256 target; } /// @notice Expenditure item to address. mapping(address => Expenditure) public expenditures; /// @dev Recipients addresses list. EnumerableSet.AddressSet internal recipients; /// @dev Withdrawal balance of recipients. mapping(address => uint256) internal balances; /// @notice Total withdrawal balance. uint256 public totalSupply; /// @notice An event emitted when expenditure item changed. event ExpenditureChanged(address recipient, uint256 min, uint256 target); /// @notice An event emitted when expenditure item payed. event Payed(address recipient, uint256 amount); receive() external payable {} /** * @notice Change expenditure item. * @param recipient Recipient address. * @param min Minimal balance for payment. * @param target Target balance. */ function changeExpenditure( address recipient, uint256 min, uint256 target ) external onlyOwner { require(min <= target, "Budget::changeExpenditure: minimal balance should be less or equal target balance"); expenditures[recipient] = Expenditure(recipient, min, target); if (target > 0) { recipients.add(recipient); } else { recipients.remove(recipient); } emit ExpenditureChanged(recipient, min, target); } /** * @notice Get withdrawal balance of recipient. */ function balanceOf(address recipient) public view returns (uint256) { return balances[recipient]; } /** * @notice Transfer ETH to recipient. * @param recipient Recipient. * @param amount Transfer amount. */ function transferETH(address payable recipient, uint256 amount) external onlyOwner { require(address(this).balance.sub(totalSupply) >= amount, "Budget::transferETH: transfer amount exceeds balance"); recipient.transfer(amount); } /** * @notice Return all recipients addresses. * @return Recipients addresses. */ function getRecipients() external view returns (address[] memory) { address[] memory result = new address[](recipients.length()); for (uint256 i = 0; i < recipients.length(); i++) { result[i] = recipients.at(i); } return result; } /** * @notice Return balance deficit of recipient. * @param recipient Target recipient. * @return Balance deficit of recipient. */ function deficitTo(address recipient) public view returns (uint256) { require(recipients.contains(recipient), "Budget::deficitTo: recipient not in expenditure item"); uint256 availableBalance = recipient.balance.add(balanceOf(recipient)); if (availableBalance > expenditures[recipient].min) return 0; return expenditures[recipient].target.sub(availableBalance); } /** * @notice Return summary balance deficit of all recipients. * @return Summary balance deficit of all recipients. */ function deficit() public view returns (uint256) { uint256 result; for (uint256 i = 0; i < recipients.length(); i++) { result = result.add(deficitTo(recipients.at(i))); } return result; } /** * @notice Pay ETH to all recipients with balance deficit. */ function pay() external { for (uint256 i = 0; i < recipients.length(); i++) { uint256 budgetBalance = address(this).balance.sub(totalSupply); address recipient = recipients.at(i); uint256 amount = deficitTo(recipient); if (amount == 0 || budgetBalance < amount) continue; balances[recipient] = balanceOf(recipient).add(amount); totalSupply = totalSupply.add(amount); } } /** * @notice Withdraw ETH to recipient. */ function withdraw() external { address payable recipient = _msgSender(); uint256 amount = balanceOf(recipient); require(amount > 0, "Budget::withdraw: transfer amount exceeds balance"); balances[recipient] = 0; totalSupply = totalSupply.sub(amount); recipient.transfer(amount); emit Payed(recipient, amount); } }
* @notice Return balance deficit of recipient. @param recipient Target recipient. @return Balance deficit of recipient./
function deficitTo(address recipient) public view returns (uint256) { require(recipients.contains(recipient), "Budget::deficitTo: recipient not in expenditure item"); uint256 availableBalance = recipient.balance.add(balanceOf(recipient)); if (availableBalance > expenditures[recipient].min) return 0; return expenditures[recipient].target.sub(availableBalance); }
1,035,372
[ 1, 990, 11013, 1652, 335, 305, 434, 8027, 18, 225, 8027, 5916, 8027, 18, 327, 30918, 1652, 335, 305, 434, 8027, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1652, 335, 305, 774, 12, 2867, 8027, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 27925, 18, 12298, 12, 20367, 3631, 315, 16124, 2866, 536, 335, 305, 774, 30, 8027, 486, 316, 431, 1302, 305, 594, 761, 8863, 203, 203, 3639, 2254, 5034, 2319, 13937, 273, 8027, 18, 12296, 18, 1289, 12, 12296, 951, 12, 20367, 10019, 203, 3639, 309, 261, 5699, 13937, 405, 431, 1302, 305, 1823, 63, 20367, 8009, 1154, 13, 327, 374, 31, 203, 203, 3639, 327, 431, 1302, 305, 1823, 63, 20367, 8009, 3299, 18, 1717, 12, 5699, 13937, 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 ]
// SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.10; interface IERC20 { function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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; address private _previousOwner; uint256 private _lockTime; 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; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(block.timestamp > _lockTime, "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } // pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 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 (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); 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 (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } contract BUZABA 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; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000 * 10**1 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "Buzaba"; string private _symbol = "BUZA"; uint8 private _decimals = 9; uint256 public _taxFee = 8; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 2; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public totalTax = _taxFee.add(_liquidityFee); IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address payable public _daoWalletAddress; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public _maxTxAmount = 10000000000 * 10**1 * 10**9; uint256 private numTokensSellToAddToLiquidity = 3000000000 * 10**1 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor(address payable daoWalletAddress) { _daoWalletAddress = daoWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function 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; } else { (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function 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 { totalTax = taxFee.add(_liquidityFee); require(totalTax <= 10, "Tax limit exceeding"); _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner { totalTax = _taxFee.add(liquidityFee); require(totalTax <= 10, "Tax limit exceeding"); _liquidityFee = liquidityFee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner { _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} 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 _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 sendETHtoDAO(uint256 amount) private { swapTokensForEth(amount); _daoWalletAddress.transfer(address(this).balance); } function _setdaoWallet(address payable daoWalletAddress) external onlyOwner { _daoWalletAddress = daoWalletAddress; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address 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"); require(totalTax <= 10, "Tax amount exceeding"); if (from != owner() && to != owner()) require( amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from, to, amount, takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into thirds uint256 halfOfLiquify = contractTokenBalance.div(4); uint256 otherHalfOfLiquify = contractTokenBalance.div(4); uint256 portionForFees = contractTokenBalance.sub(halfOfLiquify).sub( otherHalfOfLiquify ); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(halfOfLiquify); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalfOfLiquify, newBalance); sendETHtoDAO(portionForFees); emit SwapAndLiquify(halfOfLiquify, newBalance, otherHalfOfLiquify); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 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); } }
Create a uniswap pair for this new token set the rest of the contract variablesexclude owner and this contract from fee
constructor(address payable daoWalletAddress) { _daoWalletAddress = daoWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); }
10,109,238
[ 1, 1684, 279, 640, 291, 91, 438, 3082, 364, 333, 394, 1147, 444, 326, 3127, 434, 326, 6835, 3152, 10157, 3410, 471, 333, 6835, 628, 14036, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3885, 12, 2867, 8843, 429, 15229, 16936, 1887, 13, 288, 203, 3639, 389, 2414, 83, 16936, 1887, 273, 15229, 16936, 1887, 31, 203, 3639, 389, 86, 5460, 329, 63, 67, 3576, 12021, 1435, 65, 273, 389, 86, 5269, 31, 203, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 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, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 10756, 203, 5411, 263, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 203, 3639, 389, 291, 16461, 1265, 14667, 63, 8443, 1435, 65, 273, 638, 31, 203, 3639, 389, 291, 16461, 1265, 14667, 63, 2867, 12, 2211, 25887, 273, 638, 31, 203, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 389, 3576, 12021, 9334, 389, 88, 5269, 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 ]
//SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./auxiliary/interfaces/IApi3Token.sol"; import "./auxiliary/SafeMath.sol"; import "hardhat/console.sol"; contract StateUtils { using SafeMath for uint256; struct Checkpoint { uint256 fromBlock; uint256 value; } struct User { uint256 unstaked; // Always up to date Checkpoint[] shares; // Has to be updated before being used (e.g., voting) uint256 locked; // Has to be updated before being used (e.g., withdrawing) uint256 lastStateUpdateTargetBlock; uint256 unstakeScheduledAt; uint256 unstakeAmount; mapping(uint256 => bool) revokedEpochReward; } IApi3Token api3Token; // 1 year in blocks, assuming a 13 second-block time // floor(60 * 60 * 24 * 365 / 13) uint256 public immutable rewardVestingPeriod = 2425846; // 1 week in seconds uint256 public immutable rewardEpochLength = 60 * 60 * 24 * 7; mapping(address => User) public users; Checkpoint[] public totalShares; // Always up to date Checkpoint[] public totalStaked; // Always up to date // // `claimPayouts` keeps the block the claim is paid out and its amount // Checkpoint[] public claimPayouts; // // `claimPayoutReferenceBlocks` maps to `claimPayouts` one-to-one and keeps the // // block number the claim was made // uint256[] public claimPayoutReferenceBlocks; // `locks` keeps both reward locks and claim locks Checkpoint[] public locks; // `rewardReleases` and `claimReleases` are kept separately because `fromBlock`s // of `claimReleases` are not deterministic. We need checkpoints to be // chronologically ordered. (Note that this is not a problem with `locks`.) Checkpoint[] public rewardReleases; Checkpoint[] public claimReleases; // Again, we need to keep the block when the claim was made uint256[] public claimReleaseReferenceBlocks; // Note that we don't need to keep the blocks rewards were paid out at. That's // because we know that it was `rewardVestingPeriod` before it will be released. uint256 onePercent = 1000000; uint256 hundredPercent = 100000000; // VVV These parameters will be governable by the DAO VVV // Percentages are multipl1ied by 1,000,000. uint256 public minApr = 2500000; // 2.5% uint256 public maxApr = 75000000; // 75% uint256 public stakeTarget = 10e6 ether; // 10M API3 // updateCoeff is not in percentages, it's a coefficient that determines // how aggresively inflation rate will be updated to meet the target. uint256 public updateCoeff = 1000000; // ^^^ These parameters will be governable by the DAO ^^^ // Reward-related state parameters mapping(uint256 => bool) public rewardPaidForEpoch; mapping(uint256 => uint256) public rewardAmounts; mapping(uint256 => uint256) public rewardBlocks; uint256 public currentApr = minApr; constructor(address api3TokenAddress) public { // Initialize the share price at 1 API3 totalShares.push(Checkpoint(block.number, 1)); totalStaked.push(Checkpoint(block.number, 1)); api3Token = IApi3Token(api3TokenAddress); } function updateCurrentApr() internal { uint256 totalStakedNow = totalStaked[totalStaked.length - 1].value; if (stakeTarget < totalStakedNow) { currentApr = minApr; return; } uint256 deltaAbsolute = totalStakedNow < stakeTarget ? stakeTarget.sub(totalStakedNow) : totalStakedNow.sub(stakeTarget); uint256 deltaPercentage = deltaAbsolute.mul(hundredPercent).div(stakeTarget); // An updateCoeff of 1,000,000 means that for each 1% deviation from the // stake target, APR will be updated by 1%. uint256 aprUpdate = deltaPercentage.mul(updateCoeff).div(onePercent); // console.log('CONTRACT_APR_UPDATE'); // console.log(aprUpdate); currentApr = currentApr.mul(aprUpdate.add(hundredPercent)).div(hundredPercent); // console.log('CONTRACT_BELOW_TARGET'); // console.log(totalStakedNow < stakeTarget); // console.log('CONTRACT_APR_CALC'); // console.log(currentApr); if (currentApr > maxApr) { currentApr = maxApr; } // console.log('CONTRACT_NEW_APR'); // console.log(currentApr); } function payReward() internal { updateCurrentApr(); uint256 indEpoch = now / rewardEpochLength; uint256 totalStakedNow = totalStaked[totalStaked.length - 1].value; uint256 rewardAmount = totalStakedNow * currentApr / 52 / 100000000; rewardPaidForEpoch[indEpoch] = true; rewardBlocks[indEpoch] = block.number; // We don't want the DAO to revoke minter status from this contract // and lock itself out of operation if (!api3Token.getMinterStatus(address(this))) { return; } if (rewardAmount == 0) { return; } rewardAmounts[indEpoch] = rewardAmount; totalStaked.push(Checkpoint(block.number, totalStakedNow + rewardAmount)); locks.push(Checkpoint(block.number, rewardAmount)); rewardReleases.push(Checkpoint(block.number + rewardVestingPeriod, rewardAmount)); api3Token.mint(address(this), rewardAmount); } // `targetBlock` allows us to do partial updates if updating until `block.number` // costs too much gas (because, for example, too many claim payouts were made since // the last update, which requires the user to create a lot of checkpoints) function updateUserState( address userAddress, uint256 targetBlock ) public { // Make the reward payment if it wasn't made for this epoch if (!rewardPaidForEpoch[now / rewardEpochLength]) { payReward(); } User memory user = users[userAddress]; uint256 userShares = getValueAt(user.shares, block.number); uint256 locked = user.locked; // We should not process events with `fromBlock` of value `targetBlock`. Otherwise, // if `targetBlock` is `block.number`, we may miss some of the events depending on tx order. // Since we are not processing the events on `targetBlock`, we need to start processing // events starting from `lastStateUpdateTargetBlock - 1` uint256 lastStateUpdateTargetBlock = user.lastStateUpdateTargetBlock; if (lastStateUpdateTargetBlock == 0) { lastStateUpdateTargetBlock = 1; } // // We have to record all `shares` checkpoints caused by the claim payouts because // // these values are used to calculate the voting power a user will have at a point in // // time. Therefore, we can't just calculate the final value and do a single write. // // Also, claim payouts need to be processed before locks/releases because the latter depend // // on user `shares`, which is updated by claim payouts. // uint256 ind; // if(lastStateUpdateTargetBlock - 1 < claimPayouts[0].fromBlock) { // ind = 0; // } else { // ind = getIndexOf(claimPayouts, lastStateUpdateTargetBlock - 1) + 1; // } // for ( // uint256 _ind = ind; // ind < claimPayouts.length && claimPayouts[ind].fromBlock < targetBlock; // ind++ // ) // { // uint256 claimPayoutBlock = claimPayouts[ind].fromBlock; // uint256 totalStakedAtPayout = getValueAt(totalStaked, claimPayoutBlock); // uint256 totalSharesAtPayout = getValueAt(totalShares, claimPayoutBlock); // uint256 totalSharesBurned = claimPayouts[ind].value * totalSharesAtPayout / totalStakedAtPayout; // uint256 claimReferenceBlock = claimPayoutReferenceBlocks[ind]; // uint256 totalSharesAtClaim = getValueAt(totalShares, claimReferenceBlock); // uint256 userSharesAtClaim = getValueAt(users[userAddress].shares, claimReferenceBlock); // uint256 userSharesBurned = totalSharesBurned * userSharesAtClaim / totalSharesAtClaim; // userShares -= userSharesBurned; // users[userAddress].shares.push(Checkpoint(claimPayoutBlock, userShares)); // } // ... In contrast, `locked` doesn't need to be kept as checkpoints, so we can just // calculate the final value and write that once, because we only care about its // value at the time of the withdrawal (i.e., at `block.number`). Checkpoint[] memory _totalShares = totalShares; if (locks.length > 0) { Checkpoint[] memory _locks = locks; for ( uint256 ind = lastStateUpdateTargetBlock - 1 < _locks[0].fromBlock ? 0 : getIndexOf(_locks, lastStateUpdateTargetBlock - 1) + 1; ind < _locks.length && _locks[ind].fromBlock < targetBlock; ind++ ) { Checkpoint memory lock = _locks[ind]; uint256 totalSharesAtBlock = getValueAt(_totalShares, lock.fromBlock); uint256 userSharesAtBlock = getValueAt(user.shares, lock.fromBlock); locked += lock.value * userSharesAtBlock / totalSharesAtBlock; } } // for ( // uint256 ind = lastStateUpdateTargetBlock - 1 < claimReleases[0].fromBlock ? 0 : getIndexOf(claimReleases, lastStateUpdateTargetBlock - 1) + 1; // ind < claimReleases.length && claimReleases[ind].fromBlock < targetBlock; // ind++ // ) // { // uint256 claimReleaseReferenceBlock = claimReleaseReferenceBlocks[ind]; // uint256 totalSharesThen = getValueAt(totalShares, claimReleaseReferenceBlock); // uint256 userSharesThen = getValueAt(users[userAddress].shares, claimReleaseReferenceBlock); // // The below will underflow in some cases, cap at 0 // locked -= claimReleases[ind].value * userSharesThen / totalSharesThen; // } if (rewardReleases.length > 0) { Checkpoint[] memory _rewardReleases = rewardReleases; for ( uint256 ind = lastStateUpdateTargetBlock - 1 < _rewardReleases[0].fromBlock ? 0 : getIndexOf(_rewardReleases, lastStateUpdateTargetBlock - 1) + 1; ind < _rewardReleases.length && _rewardReleases[ind].fromBlock < targetBlock; ind++ ) { uint256 rewardReferenceBlock = _rewardReleases[ind].fromBlock - rewardVestingPeriod; uint256 totalSharesThen = getValueAt(_totalShares, rewardReferenceBlock); uint256 userSharesThen = getValueAt(user.shares, rewardReferenceBlock); // The below will underflow in some cases, cap at 0 locked -= _rewardReleases[ind].value * userSharesThen / totalSharesThen; } } users[userAddress].locked = locked; users[userAddress].lastStateUpdateTargetBlock = targetBlock; } // From https://github.com/aragon/minime/blob/1d5251fc88eee5024ff318d95bc9f4c5de130430/contracts/MiniMeToken.sol#L431 function getValueAt(Checkpoint[] memory checkpoints, uint _block) view internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } // Extracted from `getValueAt()` function getIndexOf(Checkpoint[] memory checkpoints, uint _block) view internal returns (uint) { // Repeating the shortcut if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints.length-1; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return min; } // ~~~ Below are some example usage patterns ~~~ // The voting app should not be able to get shares if the user state // hasn't been updated since the proposal has been made function balanceOfAt( uint256 fromBlock, address userAddress ) external view returns(uint256) { // If we don't require this, the user may vote with shares that are supposed to have been slashed // require(users[userAddress].lastStateUpdateTargetBlock >= fromBlock); uint256 shares = getValueAt(users[userAddress].shares, fromBlock); return shares; } function balanceOf(address userAddress) external view returns (uint256) { return this.balanceOfAt(block.number, userAddress); } function getUnstakeAmount(address userAddress) external view returns (uint256) { return users[userAddress].unstakeAmount; } function totalSupplyAt(uint256 fromBlock) external view returns (uint256) { return getValueAt(totalStaked, fromBlock); } function totalSupply() external view returns (uint256) { return this.totalSupplyAt(block.number); } function getScheduledUnstake(address userAddress) external view returns (uint256) { return users[userAddress].unstakeScheduledAt; } // Getters that will be used to populate the dashboard etc. should be preceded // by an `updateUserState()` using `block.number`. Otherwise, the returned value // may be outdated. function updateAndGetBalanceOfAt( address userAddress, uint256 fromBlock ) external returns(uint256) { updateUserState(userAddress, fromBlock); return getValueAt(users[userAddress].shares, fromBlock); } function updateAndGetBalanceOf(address userAddress) external returns (uint256) { return this.updateAndGetBalanceOfAt(userAddress, block.number); } }
The voting app should not be able to get shares if the user state hasn't been updated since the proposal has been made If we don't require this, the user may vote with shares that are supposed to have been slashed require(users[userAddress].lastStateUpdateTargetBlock >= fromBlock);
function balanceOfAt( uint256 fromBlock, address userAddress ) external view returns(uint256) { uint256 shares = getValueAt(users[userAddress].shares, fromBlock); return shares; }
1,029,870
[ 1, 1986, 331, 17128, 595, 1410, 486, 506, 7752, 358, 336, 24123, 309, 326, 729, 919, 13342, 1404, 2118, 3526, 3241, 326, 14708, 711, 2118, 7165, 971, 732, 2727, 1404, 2583, 333, 16, 326, 729, 2026, 12501, 598, 24123, 716, 854, 18405, 358, 1240, 2118, 9026, 329, 2583, 12, 5577, 63, 1355, 1887, 8009, 2722, 1119, 1891, 2326, 1768, 1545, 628, 1768, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 11013, 951, 861, 12, 203, 3639, 2254, 5034, 628, 1768, 16, 203, 3639, 1758, 729, 1887, 203, 3639, 262, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 12, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2254, 5034, 24123, 273, 2366, 861, 12, 5577, 63, 1355, 1887, 8009, 30720, 16, 628, 1768, 1769, 203, 3639, 327, 24123, 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 ]
// SPDX-License-Identifier: MIT-open-group pragma solidity >=0.5.15; pragma abicoder v2; import "../../CryptoLibrary.sol"; import "./EthDKGLibrary.sol"; contract EthDKGGroupAccusationFacet { function Group_Accusation_GPKj( uint256[] memory invArray, uint256[] memory honestIndices, uint256[] memory dishonestIndices ) public { EthDKGLibrary.EthDKGStorage storage es = EthDKGLibrary.ethDKGStorage(); require( (es.T_GPKJ_SUBMISSION_END < block.number) && (block.number <= es.T_GPKJ_DISPUTE_END), "gpkj accusation failed (contract is not in gpkj accusation phase)" ); uint256 k = es.addresses.length / 3; uint256 threshold = 2*k; if (2 == (es.addresses.length - 3*k)) { threshold = threshold + 1; } // All indices are the *correct* indices; we subtract 1 to get the approprtiate stuff. require( honestIndices.length >= (threshold+1), "Incorrect number of honest validators; exit" ); require( CryptoLibrary.checkIndices(honestIndices, dishonestIndices, es.addresses.length), "honestIndices and dishonestIndices do not contain unique indices" ); // Failure here should not result in loss of stake. uint256[2][] memory sigs; sigs = new uint256[2][](threshold+1); uint256[] memory indices; indices = new uint256[](threshold+1); uint256 cur_idx; address cur_addr; require( CryptoLibrary.checkInverses(invArray, es.addresses.length), "invArray does not include correct inverses" ); // Failure here should not result in loss of stake // Construct signature array for honest participants; use first t+1 for (k = 0; k < (threshold+1); k++) { cur_idx = honestIndices[k]; cur_addr = es.addresses[cur_idx-1]; sigs[k] = es.initial_signatures[cur_addr]; indices[k] = cur_idx; } uint256[2] memory grpsig = CryptoLibrary.AggregateSignatures(sigs, indices, threshold, invArray); require( CryptoLibrary.Verify(es.initial_message, grpsig, es.master_public_key), "honestIndices failed to produce valid group signature" ); // Failure above will not result in loss of stake. // At this point, you have not accused anyone of malicious behavior. // Asinine behavior does not necessitate stake burning. for (k = 0; k < dishonestIndices.length; k++) { cur_idx = dishonestIndices[k]; cur_addr = es.addresses[cur_idx-1]; indices[threshold] = cur_idx; sigs[threshold] = es.initial_signatures[cur_addr]; grpsig = CryptoLibrary.AggregateSignatures(sigs, indices, threshold, invArray); // Either the group signature is invalid, implying the person // is dishonest, or the signature is valid, implying whoever // submitted the accusation is dishonest. Either way, someone // is getting burned. if (!CryptoLibrary.Verify(es.initial_message, grpsig, es.master_public_key)) { delete es.gpkj_submissions[cur_addr]; es.is_malicious[cur_addr] = true; } else { delete es.gpkj_submissions[msg.sender]; es.is_malicious[msg.sender] = true; } } } // Perform Group accusation by computing gpkj* // // gpkj has already been submitted and stored in gpkj_submissions. // To confirm this is valid, we need to compute gpkj*, the corresponding // G1 element; we remember gpkj is a public key and an element of G2. // Once, we compute gpkj*, we can confirm // // e(gpkj*, h2) != e(g1, gpkj) // // via a pairing check. // If we have inequality, then the participant is malicious; // if we have equality, then the accusor is malicious. function Group_Accusation_GPKj_Comp( uint256[][] memory encrypted_shares, uint256[2][][] memory commitments, uint256 dishonest_list_idx, address dishonestAddress ) public { EthDKGLibrary.EthDKGStorage storage es = EthDKGLibrary.ethDKGStorage(); require( (es.T_GPKJ_SUBMISSION_END < block.number) && (block.number <= es.T_GPKJ_DISPUTE_END), "gpkj acc comp failed: contract is not in gpkj accusation phase" ); // n is total participants; // t is threshold, so that t+1 is BFT majority. uint256 n = es.addresses.length; uint256 k = n / 3; uint256 t = 2*k; if (2 == (n - 3*k)) { t = t + 1; } // Begin initial check //////////////////////////////////////////////////////////////////////// // First, check length of things require( (encrypted_shares.length == n) && (commitments.length == n), "gpkj acc comp failed: invalid submission of arguments" ); // Now, ensure subarrays are the correct length as well for (k = 0; k < n; k++) { require( encrypted_shares[k].length == n - 1, "gpkj acc comp failed: invalid number of encrypted shares provided" ); require( commitments[k].length == t + 1, "gpkj acc comp failed: invalid number of commitments provided" ); } // Ensure submissions are valid for (k = 0; k < n; k++) { address currentAddr = es.addresses[k]; require( es.share_distribution_hashes[currentAddr] == keccak256( abi.encodePacked(encrypted_shares[k], commitments[k]) ), "gpkj acc comp failed: invalid shares or commitments" ); } // Confirm nontrivial submission if ((es.gpkj_submissions[dishonestAddress][0] == 0) && (es.gpkj_submissions[dishonestAddress][1] == 0) && (es.gpkj_submissions[dishonestAddress][2] == 0) && (es.gpkj_submissions[dishonestAddress][3] == 0)) { return; } // ^^^ TODO: this check will need to be changed once we allow for multiple accusations per loop // Ensure address submissions are correct; this will be converted to loop later require( es.addresses[dishonest_list_idx] == dishonestAddress, "gpkj acc comp failed: dishonest index does not match dishonest address" ); //////////////////////////////////////////////////////////////////////// // End initial check // At this point, everything has been validated. uint256 j = dishonest_list_idx + 1; // Info for looping computation uint256 pow; uint256[2] memory gpkjStar; uint256[2] memory tmp; uint256 idx; // Begin computation loop // // We remember // // F_i(x) = C_i0 * C_i1^x * C_i2^(x^2) * ... * C_it^(x^t) // = Prod(C_ik^(x^k), k = 0, 1, ..., t) // // We now compute gpkj*. We have // // gpkj* = Prod(F_i(j), i) // = Prod( Prod(C_ik^(j^k), k = 0, 1, ..., t), i) // = Prod( Prod(C_ik^(j^k), i), k = 0, 1, ..., t) // Switch order // = Prod( [Prod(C_ik, i)]^(j^k), k = 0, 1, ..., t) // Move exponentiation outside // // More explicityly, we have // // gpkj* = Prod(C_i0, i) * // [Prod(C_i1, i)]^j * // [Prod(C_i2, i)]^(j^2) * // ... // [Prod(C_it, i)]^(j^t) * // //////////////////////////////////////////////////////////////////////// // Add constant terms gpkjStar = commitments[0][0]; // Store initial constant term for (idx = 1; idx < n; idx++) { gpkjStar = CryptoLibrary.bn128_add([gpkjStar[0], gpkjStar[1], commitments[idx][0][0], commitments[idx][0][1]]); } // Add linear term tmp = commitments[0][1]; // Store initial linear term pow = j; for (idx = 1; idx < n; idx++) { tmp = CryptoLibrary.bn128_add([tmp[0], tmp[1], commitments[idx][1][0], commitments[idx][1][1]]); } tmp = CryptoLibrary.bn128_multiply([tmp[0], tmp[1], pow]); gpkjStar = CryptoLibrary.bn128_add([gpkjStar[0], gpkjStar[1], tmp[0], tmp[1]]); // Loop through higher order terms for (k = 2; k <= t; k++) { tmp = commitments[0][k]; // Store initial degree k term // Increase pow by factor pow = mulmod(pow, j, CryptoLibrary.GROUP_ORDER); //x = mulmod(x, disputer_idx, GROUP_ORDER); for (idx = 1; idx < n; idx++) { tmp = CryptoLibrary.bn128_add([tmp[0], tmp[1], commitments[idx][k][0], commitments[idx][k][1]]); } tmp = CryptoLibrary.bn128_multiply([tmp[0], tmp[1], pow]); gpkjStar = CryptoLibrary.bn128_add([gpkjStar[0], gpkjStar[1], tmp[0], tmp[1]]); } //////////////////////////////////////////////////////////////////////// // End computation loop // We now have gpkj*; we now verify. uint256[4] memory gpkj = es.gpkj_submissions[dishonestAddress]; bool isValid = CryptoLibrary.bn128_check_pairing([ gpkjStar[0], gpkjStar[1], CryptoLibrary.H2xi, CryptoLibrary.H2x, CryptoLibrary.H2yi, CryptoLibrary.H2y, CryptoLibrary.G1x, CryptoLibrary.G1y, gpkj[0], gpkj[1], gpkj[2], gpkj[3] ]); if (isValid) { // Valid gpkj submission; burn whomever submitted accusation delete es.gpkj_submissions[msg.sender]; es.is_malicious[msg.sender] = true; } else { // Invalid gpkj submission; burn participant delete es.gpkj_submissions[dishonestAddress]; es.is_malicious[dishonestAddress] = true; } } }
Construct signature array for honest participants; use first t+1 Either the group signature is invalid, implying the person is dishonest, or the signature is valid, implying whoever submitted the accusation is dishonest. Either way, someone is getting burned.
{ EthDKGLibrary.EthDKGStorage storage es = EthDKGLibrary.ethDKGStorage(); require( (es.T_GPKJ_SUBMISSION_END < block.number) && (block.number <= es.T_GPKJ_DISPUTE_END), "gpkj accusation failed (contract is not in gpkj accusation phase)" ); uint256 k = es.addresses.length / 3; uint256 threshold = 2*k; if (2 == (es.addresses.length - 3*k)) { threshold = threshold + 1; } honestIndices.length >= (threshold+1), "Incorrect number of honest validators; exit" ); require( CryptoLibrary.checkIndices(honestIndices, dishonestIndices, es.addresses.length), "honestIndices and dishonestIndices do not contain unique indices" ); sigs = new uint256[2][](threshold+1); uint256[] memory indices; indices = new uint256[](threshold+1); uint256 cur_idx; address cur_addr; require( CryptoLibrary.checkInverses(invArray, es.addresses.length), "invArray does not include correct inverses" ); for (k = 0; k < (threshold+1); k++) { cur_idx = honestIndices[k]; cur_addr = es.addresses[cur_idx-1]; sigs[k] = es.initial_signatures[cur_addr]; indices[k] = cur_idx; } uint256[2] memory grpsig = CryptoLibrary.AggregateSignatures(sigs, indices, threshold, invArray); require( CryptoLibrary.Verify(es.initial_message, grpsig, es.master_public_key), "honestIndices failed to produce valid group signature" ); for (k = 0; k < dishonestIndices.length; k++) { cur_idx = dishonestIndices[k]; cur_addr = es.addresses[cur_idx-1]; indices[threshold] = cur_idx; sigs[threshold] = es.initial_signatures[cur_addr]; grpsig = CryptoLibrary.AggregateSignatures(sigs, indices, threshold, invArray); if (!CryptoLibrary.Verify(es.initial_message, grpsig, es.master_public_key)) { delete es.gpkj_submissions[cur_addr]; es.is_malicious[cur_addr] = true; delete es.gpkj_submissions[msg.sender]; es.is_malicious[msg.sender] = true; } } }
2,510,662
[ 1, 7249, 3372, 526, 364, 24338, 395, 22346, 31, 999, 1122, 268, 15, 21, 14635, 326, 1041, 3372, 353, 2057, 16, 709, 1283, 310, 326, 6175, 353, 1015, 76, 265, 395, 16, 578, 326, 3372, 353, 923, 16, 709, 1283, 310, 10354, 6084, 9638, 326, 4078, 407, 367, 353, 1015, 76, 265, 395, 18, 14635, 4031, 16, 18626, 353, 8742, 18305, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 288, 203, 3639, 512, 451, 3398, 43, 9313, 18, 41, 451, 3398, 43, 3245, 2502, 5001, 273, 512, 451, 3398, 43, 9313, 18, 546, 3398, 43, 3245, 5621, 203, 203, 3639, 2583, 12, 203, 5411, 261, 281, 18, 56, 67, 43, 8784, 46, 67, 8362, 15566, 67, 4415, 411, 1203, 18, 2696, 13, 597, 261, 2629, 18, 2696, 1648, 5001, 18, 56, 67, 43, 8784, 46, 67, 2565, 3118, 9099, 67, 4415, 3631, 203, 5411, 315, 75, 5465, 78, 4078, 407, 367, 2535, 261, 16351, 353, 486, 316, 4178, 79, 78, 4078, 407, 367, 6855, 2225, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 417, 273, 5001, 18, 13277, 18, 2469, 342, 890, 31, 203, 3639, 2254, 5034, 5573, 273, 576, 14, 79, 31, 203, 3639, 309, 261, 22, 422, 261, 281, 18, 13277, 18, 2469, 300, 890, 14, 79, 3719, 288, 203, 5411, 5573, 273, 5573, 397, 404, 31, 203, 3639, 289, 203, 5411, 24338, 395, 8776, 18, 2469, 1545, 261, 8699, 15, 21, 3631, 203, 5411, 315, 16268, 1300, 434, 24338, 395, 11632, 31, 2427, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 15629, 9313, 18, 1893, 8776, 12, 76, 265, 395, 8776, 16, 1015, 76, 265, 395, 8776, 16, 5001, 18, 13277, 18, 2469, 3631, 203, 5411, 315, 76, 265, 395, 8776, 471, 1015, 76, 265, 395, 8776, 741, 486, 912, 3089, 4295, 6, 203, 3639, 11272, 203, 203, 3639, 3553, 87, 273, 394, 2254, 5034, 63, 22, 6362, 29955, 8699, 15, 21, 1769, 203, 3639, 2254, 5034, 2 ]
// File: contracts/utils/math/Math.sol pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** * @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); } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // 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/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/IERC20.sol /** * @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/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/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/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: contracts/Staking/IStakingRewards.sol interface IStakingRewards { function stakeLockedFor( address who, uint256 amount, uint256 duration ) external; function stakeFor(address who, uint256 amount) external; function stakeLocked(uint256 amount, uint256 secs) external; function withdrawLocked(bytes32 kekId) external; function getReward() external; function stake(uint256 amount) external; function withdraw(uint256 amount) external; function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); } // File: contracts/utils/StringHelpers.sol library StringHelpers { function parseAddr(string memory _a) internal pure returns (address _parsedAddress) { bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint256 i = 2; i < 2 + 2 * 20; i += 2) { iaddr *= 256; b1 = uint160(uint8(tmp[i])); b2 = uint160(uint8(tmp[i + 1])); if ((b1 >= 97) && (b1 <= 102)) { b1 -= 87; } else if ((b1 >= 65) && (b1 <= 70)) { b1 -= 55; } else if ((b1 >= 48) && (b1 <= 57)) { b1 -= 48; } if ((b2 >= 97) && (b2 <= 102)) { b2 -= 87; } else if ((b2 >= 65) && (b2 <= 70)) { b2 -= 55; } else if ((b2 >= 48) && (b2 <= 57)) { b2 -= 48; } iaddr += (b1 * 16 + b2); } return address(iaddr); } function strCompare(string memory _a, string memory _b) internal pure returns (int256 _returnCode) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint256 minLength = a.length; if (b.length < minLength) { minLength = b.length; } for (uint256 i = 0; i < minLength; i++) { if (a[i] < b[i]) { return -1; } else if (a[i] > b[i]) { return 1; } } if (a.length < b.length) { return -1; } else if (a.length > b.length) { return 1; } else { return 0; } } function indexOf(string memory _haystack, string memory _needle) internal pure returns (int256 _returnCode) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if (h.length < 1 || n.length < 1 || (n.length > h.length)) { return -1; } else if (h.length > (2**128 - 1)) { return -1; } else { uint256 subindex = 0; for (uint256 i = 0; i < h.length; i++) { if (h[i] == n[0]) { subindex = 1; while ( subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex] ) { subindex++; } if (subindex == n.length) { return int256(i); } } } return -1; } } function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, '', '', ''); } function strConcat( string memory _a, string memory _b, string memory _c ) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, '', ''); } function strConcat( string memory _a, string memory _b, string memory _c, string memory _d ) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, _d, ''); } function strConcat( string memory _a, string memory _b, string memory _c, string memory _d, string memory _e ) internal pure returns (string memory _concatenatedString) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string( _ba.length + _bb.length + _bc.length + _bd.length + _be.length ); bytes memory babcde = bytes(abcde); uint256 k = 0; uint256 i = 0; for (i = 0; i < _ba.length; i++) { babcde[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { babcde[k++] = _bb[i]; } for (i = 0; i < _bc.length; i++) { babcde[k++] = _bc[i]; } for (i = 0; i < _bd.length; i++) { babcde[k++] = _bd[i]; } for (i = 0; i < _be.length; i++) { babcde[k++] = _be[i]; } return string(babcde); } function safeParseInt(string memory _a) internal pure returns (uint256 _parsedInt) { return safeParseInt(_a, 0); } function safeParseInt(string memory _a, uint256 _b) internal pure returns (uint256 _parsedInt) { bytes memory bresult = bytes(_a); uint256 mint = 0; bool decimals = false; for (uint256 i = 0; i < bresult.length; i++) { if ( (uint256(uint8(bresult[i])) >= 48) && (uint256(uint8(bresult[i])) <= 57) ) { if (decimals) { if (_b == 0) break; else _b--; } mint *= 10; mint += uint256(uint8(bresult[i])) - 48; } else if (uint256(uint8(bresult[i])) == 46) { require( !decimals, 'More than one decimal encountered in string!' ); decimals = true; } else { revert('Non-numeral character encountered in string!'); } } if (_b > 0) { mint *= 10**_b; } return mint; } function parseInt(string memory _a) internal pure returns (uint256 _parsedInt) { return parseInt(_a, 0); } function parseInt(string memory _a, uint256 _b) internal pure returns (uint256 _parsedInt) { bytes memory bresult = bytes(_a); uint256 mint = 0; bool decimals = false; for (uint256 i = 0; i < bresult.length; i++) { if ( (uint256(uint8(bresult[i])) >= 48) && (uint256(uint8(bresult[i])) <= 57) ) { if (decimals) { if (_b == 0) { break; } else { _b--; } } mint *= 10; mint += uint256(uint8(bresult[i])) - 48; } else if (uint256(uint8(bresult[i])) == 46) { decimals = true; } } if (_b > 0) { mint *= 10**_b; } return mint; } function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return '0'; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (_i != 0) { bstr[k--] = bytes1(uint8(48 + (_i % 10))); _i /= 10; } return string(bstr); } } // File: contracts/Arth/IARTHController.sol interface IARTHController { function toggleCollateralRatio() external; function refreshCollateralRatio() external; function addPool(address pool_address) external; function removePool(address pool_address) external; function getARTHInfo() external view returns ( uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256 ); function setMintingFee(uint256 fee) external; function setARTHXETHOracle( address _arthxOracleAddress, address _wethAddress ) external; function setARTHETHOracle(address _arthOracleAddress, address _wethAddress) external; function setArthStep(uint256 newStep) external; function setRedemptionFee(uint256 fee) external; function setOwner(address _ownerAddress) external; function setPriceBand(uint256 _priceBand) external; function setTimelock(address newTimelock) external; function setPriceTarget(uint256 newPriceTarget) external; function setARTHXAddress(address _arthxAddress) external; function setRefreshCooldown(uint256 newCooldown) external; function setETHGMUOracle(address _ethGMUConsumerAddress) external; function setGlobalCollateralRatio(uint256 _globalCollateralRatio) external; function getRefreshCooldown() external view returns (uint256); function getARTHPrice() external view returns (uint256); function getARTHXPrice() external view returns (uint256); function getETHGMUPrice() external view returns (uint256); function getGlobalCollateralRatio() external view returns (uint256); function getGlobalCollateralValue() external view returns (uint256); function arthPools(address pool) external view returns (bool); } // File: contracts/utils/ReentrancyGuard.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 ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, 'ReentrancyGuard: reentrant call'); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: contracts/Uniswap/TransferHelper.sol /** * @dev A helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false. */ library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // 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/Staking/RewardsDistributionRecipient.sol /// Refer: https://docs.synthetix.io/contracts/RewardsDistributionRecipient abstract contract RewardsDistributionRecipient is Ownable { /** * State variables. */ address public rewardsDistribution; // function notifyRewardAmount(uint256 reward) external virtual; /** * Modifer. */ modifier onlyRewardsDistribution() { require( msg.sender == rewardsDistribution, 'Caller is not RewardsDistribution contract' ); _; } /** * External. */ function setRewardsDistribution(address _rewardsDistribution) external onlyOwner { rewardsDistribution = _rewardsDistribution; } } // File: contracts/Staking/StakingRewards.sol /** * @title StakingRewards. * @author MahaDAO. * * Original code written by: * - Travis Moore, Jason Huan, Same Kazemian, Sam Sun. * * Modified originally from Synthetixio * https://raw.githubusercontent.com/Synthetixio/synthetix/develop/contracts/StakingRewards.sol */ contract StakingRewards is AccessControl, IStakingRewards, RewardsDistributionRecipient, ReentrancyGuard, Pausable { using SafeMath for uint256; using SafeERC20 for IERC20; /** * State variables. */ struct LockedStake { bytes32 kekId; uint256 startTimestamp; uint256 amount; uint256 endingTimestamp; uint256 multiplier; // 6 decimals of precision. 1x = 1000000 } IERC20 public rewardsToken; IERC20 public stakingToken; IARTH private _ARTH; IARTHController private _arthController; // This staking pool's percentage of the total ARTHX being distributed by all pools, 6 decimals of precision uint256 public poolWeight; // Max reward per second uint256 public rewardRate; uint256 public periodFinish; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored = 0; // uint256 public rewardsDuration = 86400 hours; uint256 public rewardsDuration = 604800; // 7 * 86400 (7 days). uint256 public lockedStakeMinTime = 604800; // 7 * 86400 (7 days) string private lockedStakeMinTimeStr = '604800'; // 7 days on genesis uint256 public lockedStakeMaxMultiplier = 3000000; // 6 decimals of precision. 1x = 1000000 uint256 public lockedStakeTimeGorMaxMultiplier = 3 * 365 * 86400; // 3 years address public ownerAddress; address public timelockAddress; // Governance timelock address uint256 private _stakingTokenSupply = 0; uint256 private _stakingTokenBoostedSupply = 0; bool public isLockedStakes; // Release lock stakes in case of system migration uint256 private constant _PRICE_PRECISION = 1e6; uint256 private constant _MULTIPLIER_BASE = 1e6; bytes32 private constant _POOL_ROLE = keccak256('_POOL_ROLE'); uint256 public crBoostMaxMultiplier = 3000000; // 6 decimals of precision. 1x = 1000000 mapping(address => bool) public greylist; mapping(address => uint256) public rewards; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) private _lockedBalances; mapping(address => uint256) private _boostedBalances; mapping(address => uint256) private _unlockedBalances; mapping(address => LockedStake[]) private _lockedStakes; /** * Events. */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event StakeLocked(address indexed user, uint256 amount, uint256 secs); event Withdrawn(address indexed user, uint256 amount); event WithdrawnLocked(address indexed user, uint256 amount, bytes32 kekId); event RewardPaid(address indexed user, uint256 reward); event RewardsDurationUpdated(uint256 newDuration); event Recovered(address token, uint256 amount); event RewardsPeriodRenewed(address token); event DefaultInitialization(); event LockedStakeMaxMultiplierUpdated(uint256 multiplier); event LockedStakeTimeForMaxMultiplier(uint256 secs); event LockedStakeMinTime(uint256 secs); event MaxCRBoostMultiplier(uint256 multiplier); /** * Modifier. */ modifier onlyPool { require(hasRole(_POOL_ROLE, msg.sender), 'Staking: FORBIDDEN'); _; } modifier updateReward(address account) { // Need to retro-adjust some things if the period hasn't been renewed, then start a new one if (block.timestamp > periodFinish) { _retroCatchUp(); } else { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); } if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } modifier onlyByOwnerOrGovernance() { require( msg.sender == ownerAddress || msg.sender == timelockAddress, 'You are not the owner or the governance timelock' ); _; } /** * Constructor. */ constructor( address _owner, address _rewardsDistribution, address _rewardsToken, address _stakingToken, address _arthAddress, address _timelockAddress, uint256 _poolWeight ) { ownerAddress = _owner; _ARTH = IARTH(_arthAddress); rewardsToken = IERC20(_rewardsToken); stakingToken = IERC20(_stakingToken); poolWeight = _poolWeight; lastUpdateTime = block.timestamp; timelockAddress = _timelockAddress; rewardsDistribution = _rewardsDistribution; isLockedStakes = false; rewardRate = 380517503805175038; // (uint256(12000000e18)).div(365 * 86400); // Base emission rate of 12M ARTHX over the first year rewardRate = rewardRate.mul(poolWeight).div(1e6); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(_POOL_ROLE, _msgSender()); } /** * External. */ function stakeLockedFor( address who, uint256 amount, uint256 duration ) external override onlyPool { _stakeLocked(who, amount, duration); } function withdraw(uint256 amount) external override nonReentrant updateReward(msg.sender) { require(amount > 0, 'Cannot withdraw 0'); // Staking token balance and boosted balance _unlockedBalances[msg.sender] = _unlockedBalances[msg.sender].sub( amount ); _boostedBalances[msg.sender] = _boostedBalances[msg.sender].sub(amount); // Staking token supply and boosted supply _stakingTokenSupply = _stakingTokenSupply.sub(amount); _stakingTokenBoostedSupply = _stakingTokenBoostedSupply.sub(amount); // Give the tokens to the withdrawer stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function renewIfApplicable() external { if (block.timestamp > periodFinish) { _retroCatchUp(); } } function withdrawLocked(bytes32 kekId) external override nonReentrant updateReward(msg.sender) { LockedStake memory thisStake; thisStake.amount = 0; uint256 theIndex; for (uint256 i = 0; i < _lockedStakes[msg.sender].length; i++) { if (kekId == _lockedStakes[msg.sender][i].kekId) { thisStake = _lockedStakes[msg.sender][i]; theIndex = i; break; } } require(thisStake.kekId == kekId, 'Stake not found'); require( block.timestamp >= thisStake.endingTimestamp || isLockedStakes == true, 'Stake is still locked!' ); uint256 theAmount = thisStake.amount; uint256 boostedAmount = theAmount.mul(thisStake.multiplier).div(_PRICE_PRECISION); if (theAmount > 0) { // Staking token balance and boosted balance _lockedBalances[msg.sender] = _lockedBalances[msg.sender].sub( theAmount ); _boostedBalances[msg.sender] = _boostedBalances[msg.sender].sub( boostedAmount ); // Staking token supply and boosted supply _stakingTokenSupply = _stakingTokenSupply.sub(theAmount); _stakingTokenBoostedSupply = _stakingTokenBoostedSupply.sub( boostedAmount ); // Remove the stake from the array delete _lockedStakes[msg.sender][theIndex]; // Give the tokens to the withdrawer stakingToken.safeTransfer(msg.sender, theAmount); emit WithdrawnLocked(msg.sender, theAmount, kekId); } } // Added to support recovering LP Rewards from other systems to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance { // Admin cannot withdraw the staking token from the contract require(tokenAddress != address(stakingToken)); IERC20(tokenAddress).transfer(ownerAddress, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function setRewardsDuration(uint256 _rewardsDuration) external onlyByOwnerOrGovernance { require( periodFinish == 0 || block.timestamp > periodFinish, 'Previous rewards period must be complete before changing the duration for the new period' ); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } function setMultipliers( uint256 _lockedStakeMaxMultiplier, uint256 _crBoostMaxMultiplier ) external onlyByOwnerOrGovernance { require( _lockedStakeMaxMultiplier >= 1, 'Multiplier must be greater than or equal to 1' ); require( _crBoostMaxMultiplier >= 1, 'Max CR Boost must be greater than or equal to 1' ); lockedStakeMaxMultiplier = _lockedStakeMaxMultiplier; crBoostMaxMultiplier = _crBoostMaxMultiplier; emit MaxCRBoostMultiplier(crBoostMaxMultiplier); emit LockedStakeMaxMultiplierUpdated(lockedStakeMaxMultiplier); } function setLockedStakeTimeForMinAndMaxMultiplier( uint256 _lockedStakeTimeGorMaxMultiplier, uint256 _lockedStakeMinTime ) external onlyByOwnerOrGovernance { require( _lockedStakeTimeGorMaxMultiplier >= 1, 'Multiplier Max Time must be greater than or equal to 1' ); require( _lockedStakeMinTime >= 1, 'Multiplier Min Time must be greater than or equal to 1' ); lockedStakeTimeGorMaxMultiplier = _lockedStakeTimeGorMaxMultiplier; lockedStakeMinTime = _lockedStakeMinTime; lockedStakeMinTimeStr = StringHelpers.uint2str(_lockedStakeMinTime); emit LockedStakeTimeForMaxMultiplier(lockedStakeTimeGorMaxMultiplier); emit LockedStakeMinTime(_lockedStakeMinTime); } function initializeDefault() external onlyByOwnerOrGovernance { lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit DefaultInitialization(); } function greylistAddress(address _address) external onlyByOwnerOrGovernance { greylist[_address] = !(greylist[_address]); } function unlockStakes() external onlyByOwnerOrGovernance { isLockedStakes = !isLockedStakes; } function setRewardRate(uint256 _newRate) external onlyByOwnerOrGovernance { rewardRate = _newRate; } function setOwnerAndTimelock(address _newOwner, address _newTimelock) external onlyByOwnerOrGovernance { ownerAddress = _newOwner; timelockAddress = _newTimelock; } function stakeFor(address who, uint256 amount) external override onlyPool { _stake(who, amount); } function stake(uint256 amount) external override { _stake(msg.sender, amount); } function stakeLocked(uint256 amount, uint256 secs) external override { _stakeLocked(msg.sender, amount, secs); } function totalSupply() external view override returns (uint256) { return _stakingTokenSupply; } function totalBoostedSupply() external view returns (uint256) { return _stakingTokenBoostedSupply; } // Total unlocked and locked liquidity tokens function balanceOf(address account) external view override returns (uint256) { return (_unlockedBalances[account]).add(_lockedBalances[account]); } // Total unlocked liquidity tokens function unlockedBalanceOf(address account) external view returns (uint256) { return _unlockedBalances[account]; } // Total 'balance' used for calculating the percent of the pool the account owns // Takes into account the locked stake time multiplier function boostedBalanceOf(address account) external view returns (uint256) { return _boostedBalances[account]; } function _lockedStakesOf(address account) external view returns (LockedStake[] memory) { return _lockedStakes[account]; } function stakingDecimals() external view returns (uint256) { return stakingToken.decimals(); } function rewardsFor(address account) external view returns (uint256) { // You may have use earned() instead, because of the order in which the contract executes return rewards[account]; } function getRewardForDuration() external view override returns (uint256) { return rewardRate.mul(rewardsDuration).mul(crBoostMultiplier()).div( _PRICE_PRECISION ); } /** * Public */ function stakingMultiplier(uint256 secs) public view returns (uint256) { uint256 multiplier = uint256(_MULTIPLIER_BASE).add( secs.mul(lockedStakeMaxMultiplier.sub(_MULTIPLIER_BASE)).div( lockedStakeTimeGorMaxMultiplier ) ); if (multiplier > lockedStakeMaxMultiplier) multiplier = lockedStakeMaxMultiplier; return multiplier; } function crBoostMultiplier() public view returns (uint256) { uint256 multiplier = uint256(_MULTIPLIER_BASE).add( ( uint256(_MULTIPLIER_BASE).sub( _arthController.getGlobalCollateralRatio() ) ) .mul(crBoostMaxMultiplier.sub(_MULTIPLIER_BASE)) .div(_MULTIPLIER_BASE) ); return multiplier; } // Total locked liquidity tokens function lockedBalanceOf(address account) public view returns (uint256) { return _lockedBalances[account]; } function lastTimeRewardApplicable() public view override returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view override returns (uint256) { if (_stakingTokenSupply == 0) { return rewardPerTokenStored; } else { return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(crBoostMultiplier()) .mul(1e18) .div(_PRICE_PRECISION) .div(_stakingTokenBoostedSupply) ); } } function getReward() public override nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.transfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function earned(address account) public view override returns (uint256) { return _boostedBalances[account] .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } /** * Internal. */ function _stake(address who, uint256 amount) internal nonReentrant notPaused updateReward(who) { require(amount > 0, 'Cannot stake 0'); require(greylist[who] == false, 'address has been greylisted'); // Pull the tokens from the staker TransferHelper.safeTransferFrom( address(stakingToken), msg.sender, address(this), amount ); // Staking token supply and boosted supply _stakingTokenSupply = _stakingTokenSupply.add(amount); _stakingTokenBoostedSupply = _stakingTokenBoostedSupply.add(amount); // Staking token balance and boosted balance _unlockedBalances[who] = _unlockedBalances[who].add(amount); _boostedBalances[who] = _boostedBalances[who].add(amount); emit Staked(who, amount); } function _stakeLocked( address who, uint256 amount, uint256 secs ) internal nonReentrant notPaused updateReward(who) { require(amount > 0, 'Cannot stake 0'); require(secs > 0, 'Cannot wait for a negative number'); require(greylist[who] == false, 'address has been greylisted'); require( secs >= lockedStakeMinTime, StringHelpers.strConcat( 'Minimum stake time not met (', lockedStakeMinTimeStr, ')' ) ); require( secs <= lockedStakeTimeGorMaxMultiplier, 'You are trying to stake for too long' ); uint256 multiplier = stakingMultiplier(secs); uint256 boostedAmount = amount.mul(multiplier).div(_PRICE_PRECISION); _lockedStakes[who].push( LockedStake( keccak256(abi.encodePacked(who, block.timestamp, amount)), block.timestamp, amount, block.timestamp.add(secs), multiplier ) ); // Pull the tokens from the staker or the operator TransferHelper.safeTransferFrom( address(stakingToken), msg.sender, address(this), amount ); // Staking token supply and boosted supply _stakingTokenSupply = _stakingTokenSupply.add(amount); _stakingTokenBoostedSupply = _stakingTokenBoostedSupply.add( boostedAmount ); // Staking token balance and boosted balance _lockedBalances[who] = _lockedBalances[who].add(amount); _boostedBalances[who] = _boostedBalances[who].add(boostedAmount); emit StakeLocked(who, amount, secs); } // If the period expired, renew it function _retroCatchUp() internal { // Failsafe check require(block.timestamp > periodFinish, 'Period has not expired yet!'); // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint256 numPeriodsElapsed = uint256(block.timestamp.sub(periodFinish)) / rewardsDuration; // Floor division to the nearest period uint256 balance = rewardsToken.balanceOf(address(this)); require( rewardRate .mul(rewardsDuration) .mul(crBoostMultiplier()) .mul(numPeriodsElapsed + 1) .div(_PRICE_PRECISION) <= balance, 'Not enough ARTHX available for rewards!' ); // uint256 old_lastUpdateTime = lastUpdateTime; // uint256 new_lastUpdateTime = block.timestamp; // lastUpdateTime = periodFinish; periodFinish = periodFinish.add( (numPeriodsElapsed.add(1)).mul(rewardsDuration) ); rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); emit RewardsPeriodRenewed(address(stakingToken)); } /* // This notifies people that the reward is being changed function notifyRewardAmount(uint256 reward) external override onlyRewardsDistribution updateReward(address(0)) { // Needed to make compiler happy // if (block.timestamp >= periodFinish) { // rewardRate = reward.mul(crBoostMultiplier()).div(rewardsDuration).div(_PRICE_PRECISION); // } else { // uint256 remaining = periodFinish.sub(block.timestamp); // uint256 leftover = remaining.mul(rewardRate); // rewardRate = reward.mul(crBoostMultiplier()).add(leftover).div(rewardsDuration).div(_PRICE_PRECISION); // } // // Ensure the provided reward amount is not more than the balance in the contract. // // This keeps the reward rate in the right range, preventing overflows due to // // very high values of rewardRate in the earned and rewardsPerToken functions; // // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. // uint balance = rewardsToken.balanceOf(address(this)); // require(rewardRate <= balance.div(rewardsDuration), "Provided reward too high"); // lastUpdateTime = block.timestamp; // periodFinish = block.timestamp.add(rewardsDuration); // emit RewardAdded(reward); } */ }
* @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; }
12,593,415
[ 1, 1356, 326, 720, 25693, 434, 2795, 9088, 12321, 16, 15226, 310, 598, 1679, 883, 603, 9391, 261, 13723, 326, 563, 353, 6092, 2934, 6425, 13269, 30, 1220, 445, 353, 6849, 2724, 518, 4991, 4767, 1776, 3778, 364, 326, 555, 883, 16209, 21513, 18, 2457, 1679, 15226, 14000, 999, 288, 698, 1676, 5496, 9354, 2680, 358, 348, 7953, 560, 1807, 1375, 17, 68, 3726, 18, 29076, 30, 300, 2592, 25693, 2780, 9391, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 720, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 16, 533, 3778, 9324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 203, 5411, 2583, 12, 70, 1648, 279, 16, 9324, 1769, 203, 5411, 327, 279, 300, 324, 31, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x320CCb623b612Eef62F186AfF6b664377cb4260b/sources/contracts/common/LogoModel.sol
@notice A logo container which holds layers of composable visual onchain assets
struct Logo { uint16 width; uint16 height; LogoElement[] layers; LogoElement text; }
17,014,332
[ 1, 37, 19128, 1478, 1492, 14798, 6623, 434, 532, 23252, 11623, 603, 5639, 7176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 1958, 1827, 83, 288, 203, 565, 2254, 2313, 1835, 31, 203, 565, 2254, 2313, 2072, 31, 203, 565, 1827, 83, 1046, 8526, 6623, 31, 203, 565, 1827, 83, 1046, 977, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x1E7407b5f0c3ec55cFEEb0B19Dfb006e32F8EBB0/sources/TOW3.sol
* @dev See {IERC721Metadata-tokenURI}./
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
2,838,400
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 2277, 17, 2316, 3098, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x07d44f5f09a4c1Dfad6CbA6459528dDaffe23F77/sources/contracts/EthBio.sol
Remember to implement the access control function example implementation:
function _canSetAppURI() internal view override returns (bool) { return true; }
9,462,597
[ 1, 28810, 358, 2348, 326, 2006, 3325, 445, 3454, 4471, 30, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4169, 694, 3371, 3098, 1435, 2713, 1476, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 327, 638, 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 ]
./partial_match/1/0xf3460869f29e356D9A725103DF62FBcEC504d67d/sources/contracts/Pixel.sol
* @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, uint256 rawAmount ) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "PXL::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "PXL::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; }
2,714,756
[ 1, 5912, 1375, 8949, 68, 2430, 628, 1375, 4816, 68, 358, 1375, 11057, 68, 225, 1705, 1021, 1758, 434, 326, 1084, 2236, 225, 3046, 1021, 1758, 434, 326, 2929, 2236, 225, 1831, 6275, 1021, 1300, 434, 2430, 358, 7412, 327, 17403, 578, 486, 326, 7412, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7412, 1265, 12, 203, 565, 1758, 1705, 16, 203, 565, 1758, 3046, 16, 203, 565, 2254, 5034, 1831, 6275, 203, 225, 262, 3903, 1135, 261, 6430, 13, 288, 203, 565, 1758, 17571, 264, 273, 1234, 18, 15330, 31, 203, 565, 2254, 10525, 17571, 264, 7009, 1359, 273, 1699, 6872, 63, 4816, 6362, 87, 1302, 264, 15533, 203, 565, 2254, 10525, 3844, 273, 4183, 10525, 12, 1899, 6275, 16, 315, 52, 23668, 2866, 12908, 537, 30, 3844, 14399, 19332, 4125, 8863, 203, 203, 565, 309, 261, 87, 1302, 264, 480, 1705, 597, 17571, 264, 7009, 1359, 480, 2254, 10525, 19236, 21, 3719, 288, 203, 1377, 2254, 10525, 394, 7009, 1359, 273, 720, 10525, 12, 87, 1302, 264, 7009, 1359, 16, 3844, 16, 315, 52, 23668, 2866, 13866, 1265, 30, 7412, 3844, 14399, 17571, 264, 1699, 1359, 8863, 203, 1377, 1699, 6872, 63, 4816, 6362, 87, 1302, 264, 65, 273, 394, 7009, 1359, 31, 203, 203, 1377, 3626, 1716, 685, 1125, 12, 4816, 16, 17571, 264, 16, 394, 7009, 1359, 1769, 203, 565, 289, 203, 203, 565, 389, 13866, 5157, 12, 4816, 16, 3046, 16, 3844, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title The Lazy Corner Contract * @author Idoia Rojo Lázaro * @dev Contract for selling and bying notes */ contract TheLazyCornerContract { using SafeMath for uint256; bool private theLazyCornerIsClosed = false; address payable private admin; constructor(){ admin = payable(msg.sender); } Note[] public notesArr; User[] public usersArr; bool locked = false; // List of notes indexed by note hash mapping(bytes32 => uint) private notesHashes; // List of notes indexed by ifps hash mapping(bytes32 => bytes32) private IPFSHashes; // List of users indexed by address mapping(address => User) private users; // List of all note purchase tokens // Each note(noteHash) has a collection of buyers' accessTokens(addr -> accessToken) mapping(bytes32 => mapping(address => bytes32)) private purchaseTokens; // List of notes bought by buyers mapping(address => bytes32[]) private boughtNotes; // List of notes owned by sellers mapping(address => bytes32[]) private ownedNotes; // STRUCTS // User -> buyer or seller // Buy -> All buyers can buy notes // Sell -> Just approved sellers can sell notes struct User{ uint id; // id - 1 -> position of user in array address userAddr; bool seller; // Note owner bool isSellerApproved; // Is approved to sell uint8 exits; // is registered } struct Note{ bytes32 noteHash; // note id hash bytes32 IPFSHash; // note ipfs reference uint id; // id - 1 -> position of note in array address payable owner; uint256 price; // price in tokens uint120 purchaseCount; // number of notes purchases uint8 exits; bool isApproved; // approved for sale string title; string description; string author; } // EVENTS event UserCreated(string message, address userAddress, bool isSeller); event UserRemoved(string message); event UserSellerApproved(string message); event NoteAdded(string message, bytes32 indexed noteHash, string title, string author); event NoteRemoved(string message); event NotePriceUpdated(string message, uint256 price); event NoteBought(string message, bytes32 indexed noteHash, address indexed buyer, address seller); // MODIFIERS /** * @dev Checks if caller is role admin * @param userAddress Address of user */ modifier isAdmin(address userAddress){ require(userAddress == admin, "Is not admin"); _; } /** * @dev Checks if thelazycorner(market) is open - circuit breaker */ modifier theLazyCornerIsOpen(){ require(theLazyCornerIsClosed == false, "Notesmarket is closed by admin" ); _; } /** * @dev Checks if the user exists * @param userAddress Address of user */ modifier userExists(address userAddress){ require(users[userAddress].exits == 1, "User doesn't exist" ); _; } /** * @dev Checks if is the admin or a user that exists * @param userAddress Address of user, noteHash hash of the note */ modifier isUserOrAdmin(address userAddress){ require(users[userAddress].exits == 1 || userAddress == admin, "User doesn't exist" ); _; } /** * @dev Checks if the user is the admin or the owner of the note * @param userAddress Address of user, noteHash hash of the note * @param noteHash hash of the note */ modifier isNoteOwnerOrAdmin(address userAddress, bytes32 noteHash){ uint noteId = notesHashes[noteHash]; require(userAddress == admin || userAddress == notesArr[noteId - 1].owner, "Is not admin nor the note owner"); _; } /** * @dev Checks if a user is approved to sell notes * @param userAddress Address of user, noteHash hash of the note */ modifier canSellNotes(address userAddress){ require(users[userAddress].seller && users[userAddress].isSellerApproved, "User can't sell notes"); _; } /** * @dev Checks if the note exists * @param noteHash hash of the note */ modifier doesNoteExist(bytes32 noteHash){ require(notesHashes[noteHash] != 0, "Note doesn't exist"); uint noteId = notesHashes[noteHash]; require(notesArr[noteId - 1].id != 0, "Note doesn't exist"); _; } /** * @dev Checks if the note has not been purchased * @param noteHash hash of the note */ modifier notPurchased(bytes32 noteHash){ uint noteId = notesHashes[noteHash]; require(notesArr[noteId - 1].purchaseCount == 0, "Note has been purchased"); _; } /** * @dev Checks if a user has sufficient funds to buy a note * @param price Price of the note */ modifier sufficientFunds(uint price){ require(price <= msg.value, "Insufficient funds"); _; } /** * @dev Refunds with excess money to buyer after payment * @param price Price of the note */ modifier returnExcess(uint price) { //refund them after pay for note _; // Silent failure if "there is no leftover to refund to buyer" if(msg.value > price){ require(!locked, "Reentrant call detected!"); locked = true; uint amountToRefund = msg.value - price; (bool success, ) = payable(msg.sender).call{value: amountToRefund}(""); require(success); locked = false; } } // FUNCTIONS /* NoteMarket */ /** * @dev Toggle contract status(open/close), just the admin can do it(Circuit breaker) */ function changeTheLazyCornerStatus() isAdmin(msg.sender) external{ theLazyCornerIsClosed = !theLazyCornerIsClosed; } /* Users */ /** * @dev Register of a new user * @param isSeller Is seller or buyer? */ function addUser(bool isSeller) theLazyCornerIsOpen external{ require(users[msg.sender].exits == 0, "User already registered"); User memory user; user.id = usersArr.length + 1; user.userAddr = msg.sender; user.seller = isSeller; user.isSellerApproved = false; // Is approved to sell user.exits = 1; users[msg.sender] = user; usersArr.push(user); emit UserCreated("User successfully created", msg.sender, isSeller); } /** * @dev Delete a user that exists, and delete all of its notes */ function removeUser() userExists(msg.sender) external{ if(users[(msg.sender)].seller){ bytes32[] memory hashes = ownedNotes[msg.sender]; for (uint i = 0; i < hashes.length; i++) { removeNote(hashes[i]); } delete ownedNotes[msg.sender]; } delete users[msg.sender]; emit UserRemoved("User successfully deleted"); } /** * @dev Get info of a user, just if it's the user itself or the admin * @return _authStatus * @return _isSeller * @return _isAdmin * @return _isSellerApproved */ function getUser() isUserOrAdmin(msg.sender) view external returns(bool _authStatus, bool _isSeller, bool _isAdmin, bool _isSellerApproved){ _authStatus = true; _isSeller = users[msg.sender].seller; _isSellerApproved = users[msg.sender].isSellerApproved; if(msg.sender == admin) _isAdmin = true; } /** * @dev Approve a seller to sell notes and receive payments, just the admin can do it * @param userAddress Address of user, noteHash hash of the note */ function approveSeller(address userAddress) theLazyCornerIsOpen isAdmin(msg.sender) userExists(userAddress) external{ if(users[userAddress].seller){ User storage user = users[userAddress]; user.isSellerApproved = true; usersArr[user.id - 1].isSellerApproved = true; emit UserSellerApproved("User seller is approved for sell"); }else{ revert("User is not a seller"); } } /** * @dev Admin fetches users using filters, max 50 results // TO-DO pagination * @return _users array of users */ function getAllUsers() isAdmin(msg.sender) view external returns (User[] memory _users){ require(usersArr.length < 50 , "Can not fetch more than 50 results"); _users = usersArr; return _users; } /* Notes */ /** * @dev Create a new note * @param _IPFShash Hash of the file(note) uploaded to IPFS * @param _title Title of the note * @param _description Description of the note * @param _author Author of the note * @param _price Price of the note (eth) */ function addNote(bytes32 _IPFShash, string memory _title, string memory _description, string memory _author, uint256 _price) theLazyCornerIsOpen userExists(msg.sender) canSellNotes(msg.sender) external{ bytes32 _noteHash = IPFSHashes[_IPFShash]; uint _noteId = notesHashes[_noteHash]; require(_noteId == 0, "Note already exists"); uint newNoteId = notesArr.length + 1; _noteHash = keccak256(abi.encodePacked(newNoteId)); notesHashes[_noteHash] = newNoteId; IPFSHashes[_IPFShash] = _noteHash; ownedNotes[msg.sender].push(_noteHash); Note memory note; note.noteHash = _noteHash; note.IPFSHash = _IPFShash; note.id = newNoteId; note.owner = payable(msg.sender); note.price = _price; // wei note.purchaseCount = 0; note.exits = 1; note.title = _title; note.description = _description; note.author = _author; note.isApproved = true; notesArr.push(note); emit NoteAdded("Note successfully created", _noteHash, _title, _author); } /** * @dev Delete an existing note * @param noteHash Hash of the note */ function removeNote(bytes32 noteHash) doesNoteExist(noteHash) notPurchased(noteHash) isNoteOwnerOrAdmin(msg.sender, noteHash) public{ delete notesHashes[noteHash]; emit NoteRemoved("User successfully deleted"); } /** * @dev Buyer buy a note, only if the market is open * @param noteHash Hash of the note */ function buyNote(bytes32 noteHash) theLazyCornerIsOpen userExists(msg.sender) doesNoteExist(noteHash) sufficientFunds(notesArr[notesHashes[noteHash] - 1].price) returnExcess(notesArr[notesHashes[noteHash] - 1].price) payable external { uint noteId = notesHashes[noteHash]; Note memory note = notesArr[noteId - 1]; address payable seller = note.owner; uint commissionFunds = note.price.div(100); uint paymentToSeller = note.price.sub(commissionFunds); bytes32 accessToken = generateAccessToken(msg.sender, note.IPFSHash); // store access token purchaseTokens[noteHash][msg.sender] = accessToken; // keep note purchase boughtNotes[msg.sender].push(noteHash); note.purchaseCount ++; notesArr[noteId - 1].purchaseCount = note.purchaseCount; (bool successSellerPayment, ) = seller.call{value: paymentToSeller}(""); require(successSellerPayment, "Failed to send payment to seller"); (bool successAdminPayment, ) = admin.call{value: commissionFunds}(""); require(successAdminPayment, "Failed to send commission to admin"); emit NoteBought("note bought", noteHash, msg.sender, seller); } /** * @dev Admin fetches notes using filters, max 50 results // TO-DO pagination * @return Array of notes */ function getAllNotes() userExists(msg.sender) view external returns (Note[] memory){ require(notesArr.length < 50 , "Can not fetch more than 50 results"); Note[] memory _notes; _notes = notesArr; return _notes; } /** * @dev Fetch all of the notes that the buyer bought * @return _boughtNotes Array of hashes of the notes bought */ function getMyPurchasedNotes() userExists(msg.sender) view public returns(bytes32[] memory _boughtNotes){ _boughtNotes = boughtNotes[msg.sender]; } /** * @dev Fetch all of the notes that the seller uploaded, just if it's a seller * @return _ownedNotes Array of hashes of the owned bought */ function getMyUploadedNotes() canSellNotes(msg.sender) userExists(msg.sender) view external returns(bytes32[] memory _ownedNotes){ _ownedNotes = ownedNotes[msg.sender]; for(uint i=0; i < _ownedNotes.length; i++){ // exclude the leftover hashes in state array map ownedNotes if(notesHashes[_ownedNotes[i]] == 0){ delete _ownedNotes[i]; } } } /** * @dev Generate access token to verify that the buyer bought a note, before providing access to the file * @param userAddr Address of user * @param IPFShash Hash of the file(note) uploaded to IPFS * @return Token */ function generateAccessToken(address userAddr, bytes32 IPFShash) private pure returns(bytes32) { //isAdmin(msg.sender) bytes32 salt = "S}7#%*SD30o7D"; bytes32 accessToken = keccak256(abi.encodePacked(userAddr, IPFShash, salt)); return accessToken; } }
* @dev Delete a user that exists, and delete all of its notes/
function removeUser() userExists(msg.sender) external{ if(users[(msg.sender)].seller){ bytes32[] memory hashes = ownedNotes[msg.sender]; for (uint i = 0; i < hashes.length; i++) { removeNote(hashes[i]); } delete ownedNotes[msg.sender]; } delete users[msg.sender]; emit UserRemoved("User successfully deleted"); }
15,846,276
[ 1, 2613, 279, 729, 716, 1704, 16, 471, 1430, 777, 434, 2097, 10913, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1206, 1299, 1435, 729, 4002, 12, 3576, 18, 15330, 13, 3903, 95, 203, 565, 309, 12, 5577, 63, 12, 3576, 18, 15330, 13, 8009, 1786, 749, 15329, 203, 1377, 1731, 1578, 8526, 3778, 9869, 273, 16199, 18063, 63, 3576, 18, 15330, 15533, 203, 203, 1377, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 9869, 18, 2469, 31, 277, 27245, 288, 203, 3639, 1206, 8067, 12, 17612, 63, 77, 19226, 203, 1377, 289, 203, 1377, 1430, 16199, 18063, 63, 3576, 18, 15330, 15533, 203, 565, 289, 203, 565, 1430, 3677, 63, 3576, 18, 15330, 15533, 203, 203, 565, 3626, 2177, 10026, 2932, 1299, 4985, 4282, 8863, 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 ]
// Sources flattened with hardhat v2.1.2 https://hardhat.org // File contracts/proxy/Base.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract Base { constructor () public { } //0x20 - length //0x53c6eaee8696e4c5200d3d231b29cc6a40b3893a5ae1536b0ac08212ffada877 bytes constant notFoundMark = abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("404-method-not-found"))))))); //return the payload of returnData, stripe the leading length function returnAsm(bool isRevert, bytes memory returnData) pure internal { assembly{ let length := mload(returnData) switch isRevert case 0x00{ return (add(returnData, 0x20), length) } default{ revert (add(returnData, 0x20), length) } } } modifier nonPayable(){ require(msg.value == 0, "nonPayable"); _; } } // File contracts/proxy/SlotData.sol contract SlotData { constructor() public {} // for map, key could be 0x00, but value can't be 0x00; // if value == 0x00, it mean the key doesn't has any value function sysMapSet(bytes32 mappingSlot, bytes32 key, bytes32 value) internal returns (uint256 length){ length = sysMapLen(mappingSlot); bytes32 elementOffset = sysCalcMapOffset(mappingSlot, key); bytes32 storedValue = sysLoadSlotData(elementOffset); if (value == storedValue) { //if value == 0 & storedValue == 0 //if value == storedValue != 0 //needn't set same value; } else if (value == bytes32(0x00)) { //storedValue != 0 //deleting value sysSaveSlotData(elementOffset, value); length--; sysSaveSlotData(mappingSlot, bytes32(length)); } else if (storedValue == bytes32(0x00)) { //value != 0 //adding new value sysSaveSlotData(elementOffset, value); length++; sysSaveSlotData(mappingSlot, bytes32(length)); } else { //value != storedValue & value != 0 & storedValue !=0 //updating sysSaveSlotData(elementOffset, value); } return length; } function sysMapGet(bytes32 mappingSlot, bytes32 key) internal view returns (bytes32){ bytes32 elementOffset = sysCalcMapOffset(mappingSlot, key); return sysLoadSlotData(elementOffset); } function sysMapLen(bytes32 mappingSlot) internal view returns (uint256){ return uint256(sysLoadSlotData(mappingSlot)); } function sysLoadSlotData(bytes32 slot) internal view returns (bytes32){ //ask a stack position bytes32 ret; assembly{ ret := sload(slot) } return ret; } function sysSaveSlotData(bytes32 slot, bytes32 data) internal { assembly{ sstore(slot, data) } } function sysCalcMapOffset(bytes32 mappingSlot, bytes32 key) internal pure returns (bytes32){ return bytes32(keccak256(abi.encodePacked(key, mappingSlot))); } function sysCalcSlot(bytes memory name) public pure returns (bytes32){ return keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked(name)))))); } function calcNewSlot(bytes32 slot, string memory name) internal pure returns (bytes32){ return keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked(slot, name)))))); } } // File contracts/proxy/EnhancedMap.sol //this is just a normal mapping, but which holds size and you can specify slot /* both key and value shouldn't be 0x00 the key must be unique, the value would be whatever slot key --- value a --- 1 b --- 2 c --- 3 c --- 4 X not allowed d --- 3 e --- 0 X not allowed 0 --- 9 X not allowed */ contract EnhancedMap is SlotData { constructor() public {} //set value to 0x00 to delete function sysEnhancedMapSet(bytes32 slot, bytes32 key, bytes32 value) internal { require(key != bytes32(0x00), "sysEnhancedMapSet, notEmptyKey"); sysMapSet(slot, key, value); } function sysEnhancedMapAdd(bytes32 slot, bytes32 key, bytes32 value) internal { require(key != bytes32(0x00), "sysEnhancedMapAdd, notEmptyKey"); require(value != bytes32(0x00), "EnhancedMap add, the value shouldn't be empty"); require(sysMapGet(slot, key) == bytes32(0x00), "EnhancedMap, the key already has value, can't add duplicate key"); sysMapSet(slot, key, value); } function sysEnhancedMapDel(bytes32 slot, bytes32 key) internal { require(key != bytes32(0x00), "sysEnhancedMapDel, notEmptyKey"); require(sysMapGet(slot, key) != bytes32(0x00), "sysEnhancedMapDel, the key doesn't has value, can't delete empty key"); sysMapSet(slot, key, bytes32(0x00)); } function sysEnhancedMapReplace(bytes32 slot, bytes32 key, bytes32 value) public { require(key != bytes32(0x00), "sysEnhancedMapReplace, notEmptyKey"); require(value != bytes32(0x00), "EnhancedMap replace, the value shouldn't be empty"); require(sysMapGet(slot, key) != bytes32(0x00), "EnhancedMap, the key doesn't has value, can't replace it"); sysMapSet(slot, key, value); } function sysEnhancedMapGet(bytes32 slot, bytes32 key) internal view returns (bytes32){ require(key != bytes32(0x00), "sysEnhancedMapGet, notEmptyKey"); return sysMapGet(slot, key); } function sysEnhancedMapSize(bytes32 slot) internal view returns (uint256){ return sysMapLen(slot); } } // File contracts/proxy/EnhancedUniqueIndexMap.sol //once you input a value, it will auto generate an index for that //index starts from 1, 0 means this value doesn't exist //the value must be unique, and can't be 0x00 //the index must be unique, and can't be 0x00 /* slot value --- index a --- 1 b --- 2 c --- 3 c --- 4 X not allowed d --- 3 X not allowed e --- 0 X not allowed indexSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked(slot)))))); index --- value 1 --- a 2 --- b 3 --- c 3 --- d X not allowed */ contract EnhancedUniqueIndexMap is SlotData { constructor() public {} // slot : value => index function sysUniqueIndexMapAdd(bytes32 slot, bytes32 value) internal { require(value != bytes32(0x00)); bytes32 indexSlot = calcIndexSlot(slot); uint256 index = uint256(sysMapGet(slot, value)); require(index == 0, "sysUniqueIndexMapAdd, value already exist"); uint256 last = sysUniqueIndexMapSize(slot); last ++; sysMapSet(slot, value, bytes32(last)); sysMapSet(indexSlot, bytes32(last), value); } function sysUniqueIndexMapDel(bytes32 slot, bytes32 value) internal { //require(value != bytes32(0x00), "sysUniqueIndexMapDel, value must not be 0x00"); bytes32 indexSlot = calcIndexSlot(slot); uint256 index = uint256(sysMapGet(slot, value)); require(index != 0, "sysUniqueIndexMapDel, value doesn't exist"); uint256 lastIndex = sysUniqueIndexMapSize(slot); require(lastIndex > 0, "sysUniqueIndexMapDel, lastIndex must be large than 0, this must not happen"); if (index != lastIndex) { bytes32 lastValue = sysMapGet(indexSlot, bytes32(lastIndex)); //move the last to the current place //this would be faster than move all elements forward after the deleting one, but not stable(the sequence will change) sysMapSet(slot, lastValue, bytes32(index)); sysMapSet(indexSlot, bytes32(index), lastValue); } sysMapSet(slot, value, bytes32(0x00)); sysMapSet(indexSlot, bytes32(lastIndex), bytes32(0x00)); } function sysUniqueIndexMapDelArrange(bytes32 slot, bytes32 value) internal { require(value != bytes32(0x00), "sysUniqueIndexMapDelArrange, value must not be 0x00"); bytes32 indexSlot = calcIndexSlot(slot); uint256 index = uint256(sysMapGet(slot, value)); require(index != 0, "sysUniqueIndexMapDelArrange, value doesn't exist"); uint256 lastIndex = (sysUniqueIndexMapSize(slot)); require(lastIndex > 0, "sysUniqueIndexMapDelArrange, lastIndex must be large than 0, this must not happen"); sysMapSet(slot, value, bytes32(0x00)); while (index < lastIndex) { bytes32 nextValue = sysMapGet(indexSlot, bytes32(index + 1)); sysMapSet(indexSlot, bytes32(index), nextValue); sysMapSet(slot, nextValue, bytes32(index)); index ++; } sysMapSet(indexSlot, bytes32(lastIndex), bytes32(0x00)); } function sysUniqueIndexMapReplace(bytes32 slot, bytes32 oldValue, bytes32 newValue) internal { require(oldValue != bytes32(0x00), "sysUniqueIndexMapReplace, oldValue must not be 0x00"); require(newValue != bytes32(0x00), "sysUniqueIndexMapReplace, newValue must not be 0x00"); bytes32 indexSlot = calcIndexSlot(slot); uint256 index = uint256(sysMapGet(slot, oldValue)); require(index != 0, "sysUniqueIndexMapDel, oldValue doesn't exists"); require(uint256(sysMapGet(slot, newValue)) == 0, "sysUniqueIndexMapDel, newValue already exists"); sysMapSet(slot, oldValue, bytes32(0x00)); sysMapSet(slot, newValue, bytes32(index)); sysMapSet(indexSlot, bytes32(index), newValue); } //============================view & pure============================ function sysUniqueIndexMapSize(bytes32 slot) internal view returns (uint256){ return sysMapLen(slot); } //returns index, 0 mean not exist function sysUniqueIndexMapGetIndex(bytes32 slot, bytes32 value) internal view returns (uint256){ return uint256(sysMapGet(slot, value)); } function sysUniqueIndexMapGetValue(bytes32 slot, uint256 index) internal view returns (bytes32){ bytes32 indexSlot = calcIndexSlot(slot); return sysMapGet(indexSlot, bytes32(index)); } // index => value function calcIndexSlot(bytes32 slot) internal pure returns (bytes32){ return calcNewSlot(slot, "index"); } } // File contracts/proxy/Proxy.sol contract Proxy is Base, EnhancedMap, EnhancedUniqueIndexMap { constructor (address admin) public { require(admin != address(0)); sysSaveSlotData(adminSlot, bytes32(uint256(admin))); sysSaveSlotData(userSigZeroSlot, bytes32(uint256(0))); sysSaveSlotData(outOfServiceSlot, bytes32(uint256(0))); sysSaveSlotData(revertMessageSlot, bytes32(uint256(1))); //sysSetDelegateFallback(address(0)); sysSaveSlotData(transparentSlot, bytes32(uint256(1))); } bytes32 constant adminSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("adminSlot")))))); bytes32 constant revertMessageSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("revertMessageSlot")))))); bytes32 constant outOfServiceSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("outOfServiceSlot")))))); //address <===> index EnhancedUniqueIndexMap //0x2f80e9a12a11b80d2130b8e7dfc3bb1a6c04d0d87cc5c7ea711d9a261a1e0764 bytes32 constant delegatesSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("delegatesSlot")))))); //bytes4 abi ===> address, both not 0x00 //0xba67a9e2b7b43c3c9db634d1c7bcdd060aa7869f4601d292a20f2eedaf0c2b1c bytes32 constant userAbiSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("userAbiSlot")))))); bytes32 constant userAbiSearchSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("userAbiSearchSlot")))))); //0xe2bb2e16cbb16a10fab839b4a5c3820d63a910f4ea675e7821846c4b2d3041dc bytes32 constant userSigZeroSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("userSigZeroSlot")))))); bytes32 constant transparentSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("transparentSlot")))))); event DelegateSet(address delegate, bool activated); event AbiSet(bytes4 abi, address delegate, bytes32 slot); event PrintBytes(bytes data); //=================================================================================== // function sysCountDelegate() public view returns (uint256){ return sysUniqueIndexMapSize(delegatesSlot); } function sysGetDelegateAddress(uint256 index) public view returns (address){ return address(uint256(sysUniqueIndexMapGetValue(delegatesSlot, index))); } function sysGetDelegateIndex(address addr) public view returns (uint256) { return uint256(sysUniqueIndexMapGetIndex(delegatesSlot, bytes32(uint256(addr)))); } function sysGetDelegateAddresses() public view returns (address[] memory){ uint256 count = sysCountDelegate(); address[] memory delegates = new address[](count); for (uint256 i = 0; i < count; i++) { delegates[i] = sysGetDelegateAddress(i + 1); } return delegates; } //add delegates on current version function sysAddDelegates(address[] memory _inputs) public onlyAdmin { for (uint256 i = 0; i < _inputs.length; i ++) { sysUniqueIndexMapAdd(delegatesSlot, bytes32(uint256(_inputs[i]))); emit DelegateSet(_inputs[i], true); } } //delete delegates //be careful, if you delete a delegate, the index will change function sysDelDelegates(address[] memory _inputs) public onlyAdmin { for (uint256 i = 0; i < _inputs.length; i ++) { //travers all abis to delete those abis mapped to the given address uint256 j; uint256 k; /*bytes4[] memory toDeleteSelectors = new bytes4[](count + 1); uint256 pivot = 0;*/ uint256 count = sysCountSelectors(); /*for (j = 0; j < count; j ++) { bytes4 selector; address delegate; (selector, delegate) = sysGetUserSelectorAndDelegateByIndex(j + 1); if (delegate == _inputs[i]) { toDeleteSelectors[pivot] = selector; pivot++; } } pivot = 0; while (toDeleteSelectors[pivot] != bytes4(0x00)) { sysSetUserSelectorAndDelegate(toDeleteSelectors[pivot], address(0)); pivot++; }*/ k = 1; for (j = 0; j < count; j++) { bytes4 selector; address delegate; (selector, delegate) = sysGetSelectorAndDelegateByIndex(k); if (delegate == _inputs[i]) { sysSetSelectorAndDelegate(selector, address(0)); } else { k++; } } if (sysGetSigZero() == _inputs[i]) { sysSetSigZero(address(0x00)); } sysUniqueIndexMapDelArrange(delegatesSlot, bytes32(uint256(_inputs[i]))); emit DelegateSet(_inputs[i], false); } } //add and delete delegates function sysReplaceDelegates(address[] memory _delegatesToDel, address[] memory _delegatesToAdd) public onlyAdmin { require(_delegatesToDel.length == _delegatesToAdd.length, "sysReplaceDelegates, length does not match"); for (uint256 i = 0; i < _delegatesToDel.length; i ++) { sysUniqueIndexMapReplace(delegatesSlot, bytes32(uint256(_delegatesToDel[i])), bytes32(uint256(_delegatesToAdd[i]))); emit DelegateSet(_delegatesToDel[i], false); emit DelegateSet(_delegatesToAdd[i], true); } } //============================================= function sysGetSigZero() public view returns (address){ return address(uint256(sysLoadSlotData(userSigZeroSlot))); } function sysSetSigZero(address _input) public onlyAdmin { sysSaveSlotData(userSigZeroSlot, bytes32(uint256(_input))); } function sysGetAdmin() public view returns (address){ return address(uint256(sysLoadSlotData(adminSlot))); } function sysSetAdmin(address _input) external onlyAdmin { sysSaveSlotData(adminSlot, bytes32(uint256(_input))); } function sysGetRevertMessage() public view returns (uint256){ return uint256(sysLoadSlotData(revertMessageSlot)); } function sysSetRevertMessage(uint256 _input) external onlyAdmin { sysSaveSlotData(revertMessageSlot, bytes32(_input)); } function sysGetOutOfService() public view returns (uint256){ return uint256(sysLoadSlotData(outOfServiceSlot)); } function sysSetOutOfService(uint256 _input) external onlyAdmin { sysSaveSlotData(outOfServiceSlot, bytes32(_input)); } function sysGetTransparent() public view returns (uint256){ return uint256(sysLoadSlotData(transparentSlot)); } function sysSetTransparent(uint256 _input) public onlyAdmin { sysSaveSlotData(transparentSlot, bytes32(_input)); } //============================================= //abi and delegates should not be 0x00 in mapping; //set delegate to 0x00 for delete the entry function sysSetSelectorsAndDelegates(bytes4[] memory selectors, address[] memory delegates) public onlyAdmin { require(selectors.length == delegates.length, "sysSetUserSelectorsAndDelegates, length does not matchs"); for (uint256 i = 0; i < selectors.length; i ++) { sysSetSelectorAndDelegate(selectors[i], delegates[i]); } } function sysSetSelectorAndDelegate(bytes4 selector, address delegate) public { require(selector != bytes4(0x00), "sysSetSelectorAndDelegate, selector should not be selector"); //require(delegates[i] != address(0x00)); address oldDelegate = address(uint256(sysEnhancedMapGet(userAbiSlot, bytes32(selector)))); if (oldDelegate == delegate) { //if oldDelegate == 0 & delegate == 0 //if oldDelegate == delegate != 0 //do nothing here } if (oldDelegate == address(0x00)) { //delegate != 0 //adding new value sysEnhancedMapAdd(userAbiSlot, bytes32(selector), bytes32(uint256(delegate))); sysUniqueIndexMapAdd(userAbiSearchSlot, bytes32(selector)); } if (delegate == address(0x00)) { //oldDelegate != 0 //deleting new value sysEnhancedMapDel(userAbiSlot, bytes32(selector)); sysUniqueIndexMapDel(userAbiSearchSlot, bytes32(selector)); } else { //oldDelegate != delegate & oldDelegate != 0 & delegate !=0 //updating sysEnhancedMapReplace(userAbiSlot, bytes32(selector), bytes32(uint256(delegate))); } } function sysGetDelegateBySelector(bytes4 selector) public view returns (address){ return address(uint256(sysEnhancedMapGet(userAbiSlot, bytes32(selector)))); } function sysCountSelectors() public view returns (uint256){ return sysEnhancedMapSize(userAbiSlot); } function sysGetSelector(uint256 index) public view returns (bytes4){ bytes4 selector = bytes4(sysUniqueIndexMapGetValue(userAbiSearchSlot, index)); return selector; } function sysGetSelectorAndDelegateByIndex(uint256 index) public view returns (bytes4, address){ bytes4 selector = sysGetSelector(index); address delegate = sysGetDelegateBySelector(selector); return (selector, delegate); } function sysGetSelectorsAndDelegates() public view returns (bytes4[] memory selectors, address[] memory delegates){ uint256 count = sysCountSelectors(); selectors = new bytes4[](count); delegates = new address[](count); for (uint256 i = 0; i < count; i ++) { (selectors[i], delegates[i]) = sysGetSelectorAndDelegateByIndex(i + 1); } } function sysClearSelectorsAndDelegates() public { uint256 count = sysCountSelectors(); for (uint256 i = 0; i < count; i ++) { bytes4 selector; address delegate; //always delete the first, after 'count' times, it will clear all (selector, delegate) = sysGetSelectorAndDelegateByIndex(1); sysSetSelectorAndDelegate(selector, address(0x00)); } } //=====================internal functions===================== receive() payable external { process(); } fallback() payable external { process(); } //since low-level address.delegateCall is available in solidity, //we don't need to write assembly function process() internal outOfService { if (msg.sender == sysGetAdmin() && sysGetTransparent() == 1) { revert("admin cann't call normal function in Transparent mode"); } /* the default transfer will set data to empty, so that the msg.data.length = 0 and msg.sig = bytes4(0x00000000), however some one can manually set msg.sig to 0x00000000 and tails more man-made data, so here we have to forward all msg.data to delegates */ address targetDelegate; //for look-up table /* if (msg.sig == bytes4(0x00000000)) { targetDelegate = sysGetUserSigZero(); if (targetDelegate != address(0x00)) { delegateCallExt(targetDelegate, msg.data); } targetDelegate = sysGetSystemSigZero(); if (targetDelegate != address(0x00)) { delegateCallExt(targetDelegate, msg.data); } } else { targetDelegate = sysGetUserDelegate(msg.sig); if (targetDelegate != address(0x00)) { delegateCallExt(targetDelegate, msg.data); } //check system abi look-up table targetDelegate = sysGetSystemDelegate(msg.sig); if (targetDelegate != address(0x00)) { delegateCallExt(targetDelegate, msg.data); } }*/ if (msg.sig == bytes4(0x00000000)) { targetDelegate = sysGetSigZero(); if (targetDelegate != address(0x00)) { delegateCallExt(targetDelegate, msg.data); } } else { targetDelegate = sysGetDelegateBySelector(msg.sig); if (targetDelegate != address(0x00)) { delegateCallExt(targetDelegate, msg.data); } } //goes here means this abi is not in the system abi look-up table discover(); //hit here means not found selector if (sysGetRevertMessage() == 1) { revert(string(abi.encodePacked(sysPrintAddressToHex(address(this)), ", function selector not found : ", sysPrintBytes4ToHex(msg.sig)))); } else { revert(); } } function discover() internal { bool found = false; bool error; bytes memory returnData; address targetDelegate; uint256 len = sysCountDelegate(); for (uint256 i = 0; i < len; i++) { targetDelegate = sysGetDelegateAddress(i + 1); (found, error, returnData) = redirect(targetDelegate, msg.data); if (found) { /*if (msg.sig == bytes4(0x00000000)) { sysSetSystemSigZero(targetDelegate); } else { sysSetSystemSelectorAndDelegate(msg.sig, targetDelegate); }*/ returnAsm(error, returnData); } } } function delegateCallExt(address targetDelegate, bytes memory callData) internal { bool found = false; bool error; bytes memory returnData; (found, error, returnData) = redirect(targetDelegate, callData); require(found, "delegateCallExt to a delegate in the map but finally not found, this shouldn't happen"); returnAsm(error, returnData); } //since low-level ```<address>.delegatecall(bytes memory) returns (bool, bytes memory)``` can return returndata, //we use high-level solidity for better reading function redirect(address delegateTo, bytes memory callData) internal returns (bool found, bool error, bytes memory returnData){ require(delegateTo != address(0), "delegateTo must not be 0x00"); bool success; (success, returnData) = delegateTo.delegatecall(callData); if (success == true && keccak256(returnData) == keccak256(notFoundMark)) { //the delegate returns ```notFoundMark``` notFoundMark, which means invoke goes to wrong contract or function doesn't exist return (false, true, returnData); } else { return (true, !success, returnData); } } function sysPrintBytesToHex(bytes memory input) internal pure returns (string memory){ bytes memory ret = new bytes(input.length * 2); bytes memory alphabet = "0123456789abcdef"; for (uint256 i = 0; i < input.length; i++) { bytes32 t = bytes32(input[i]); bytes32 tt = t >> 31 * 8; uint256 b = uint256(tt); uint256 high = b / 0x10; uint256 low = b % 0x10; byte highAscii = alphabet[high]; byte lowAscii = alphabet[low]; ret[2 * i] = highAscii; ret[2 * i + 1] = lowAscii; } return string(ret); } function sysPrintAddressToHex(address input) internal pure returns (string memory){ return sysPrintBytesToHex( abi.encodePacked(input) ); } function sysPrintBytes4ToHex(bytes4 input) internal pure returns (string memory){ return sysPrintBytesToHex( abi.encodePacked(input) ); } function sysPrintUint256ToHex(uint256 input) internal pure returns (string memory){ return sysPrintBytesToHex( abi.encodePacked(input) ); } modifier onlyAdmin(){ require(msg.sender == sysGetAdmin(), "only admin"); _; } modifier outOfService(){ if (sysGetOutOfService() == uint256(1)) { if (sysGetRevertMessage() == 1) { revert(string(abi.encodePacked("Proxy is out-of-service right now"))); } else { revert(); } } _; } } /*function() payable external { bytes32 notFound = notFoundMark; assembly { let ptr := mload(0x40) mstore(ptr, notFound) return (ptr, 32) } }*/ /* bytes4 selector = msg.sig; uint256 size; uint256 ptr; bool result; //check if the shortcut hit address delegateTo = checkShortcut(selector); if (delegateTo != address(0x00)) { assembly{ ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) result := delegatecall(gas, delegateTo, ptr, calldatasize, 0, 0) size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 {revert(ptr, size)} default {return (ptr, size)} } } //no shortcut bytes32 notFound = notFoundMark; bool found = false; for (uint256 i = 0; i < delegates.length && !found; i ++) { delegateTo = delegates[i]; assembly{ result := delegatecall(gas, delegateTo, 0, 0, 0, 0) size := returndatasize returndatacopy(ptr, 0, size) mstore(0x40, add(ptr, size))//update free memory pointer found := 0x01 //assume we found the target function if and(and(eq(result, 0x01), eq(size, 0x20)), eq(mload(ptr), notFound)){ //match the "notFound" mark found := 0x00 } } if (found) { emit FunctionFound(delegateTo); //add to shortcut, take effect only when the delegatecall returns 1 (not 0-revert) shortcut[selector] = delegateTo; //return data assembly{ switch result case 0 {revert(ptr, size)} default {return (ptr, size)} } } } //comes here for not found emit FunctionNotFound(selector);*/ // File @openzeppelin/contracts/introspection/[email protected] 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 contracts/erc165/CERC165Interface.sol interface CERC165Interface is IERC165 { function supportsInterface(bytes4 interfaceId) override external view returns (bool); } // File contracts/erc165/CERC165Layout.sol contract CERC165Layout { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 internal constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) internal _supportedInterfaces; } // File contracts/erc165/CERC165LogicBase.sol contract CERC165LogicBase is CERC165Layout { /** * @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 contracts/erc165/CERC165Storage.sol contract CERC165Storage is CERC165LogicBase { constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } } // File @openzeppelin/contracts/utils/[email protected] 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)); } } // File @openzeppelin/contracts/utils/[email protected] 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)))); } } // File contracts/erc721/CERC721Layout.sol contract CERC721Layout is CERC165Layout { using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 internal constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping(address => EnumerableSet.UintSet) internal _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap internal _tokenOwners; // Mapping from token ID to approved address mapping(uint256 => address) internal _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) internal _operatorApprovals; // Token name string internal _name; // Token symbol string internal _symbol; // Optional mapping for token URIs mapping(uint256 => string) internal _tokenURIs; // Base URI string internal _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 internal constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 internal 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 internal constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; } // File contracts/context/ContextLogicBase.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. */ contract ContextLogicBase { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File contracts/erc721/CERC721LogicBase.sol contract CERC721LogicBase is CERC165LogicBase, ContextLogicBase, CERC721Layout { /** * @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_; } } // File contracts/erc721/CERC721Storage.sol contract CERC721Storage is CERC721LogicBase { 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); } } // File contracts/ownable/OwnableLayout.sol abstract contract OwnableLayout { address internal _owner; mapping(address => bool) internal _associatedOperators; } // File contracts/ownable/OwnableStorage.sol contract OwnableStorage is OwnableLayout { constructor (address owner) internal { _owner = owner; } } // File contracts/ownable/OwnableLogicBase.sol contract OwnableLogicBase is OwnableLayout { //nothing to do here } // File @openzeppelin/contracts/math/[email protected] 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/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File @openzeppelin/contracts/utils/[email protected] 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/[email protected] 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 contracts/nfts/CalendarType.sol library CalendarType { struct Pair { uint256 min; uint256 max; } } // File contracts/nfts/CalendarLayout.sol //keep the layout order contract CalendarLayout is CERC721Layout, OwnableLayout { using SafeMath for uint256; uint256 constant MILLION = 1000000; uint256 internal _startTime; address internal _dev; uint256 internal _taxPerMillion; uint256 internal _startPrice; uint256 internal _bidPricePerMillion; mapping(uint256 => uint256) internal _lastPrice; mapping(uint256 => uint256) internal _calendarSkin; mapping(uint256 => bytes) internal _calendarName; mapping(uint256 => bytes) internal _calendarBlog; } // File contracts/nfts/CalendarLogicBase.sol contract CalendarLogicBase is OwnableLogicBase, CERC721LogicBase, CalendarLayout { } // File contracts/nfts/CalendarStorage.sol //don't change the layouts. notice that layout is behind storage contract CalendarStorage is Proxy, OwnableStorage, CERC165Storage, CERC721Storage, CalendarLogicBase { constructor ( string memory name_, string memory symbol_, string memory baseURI_, uint256 startTime_, uint256 startPrice_, uint256 bidPricePerMillion_, uint256 taxPerMillion_, address dev_ ) public Proxy(msg.sender) OwnableStorage(msg.sender) CERC165Storage() CERC721Storage(name_, symbol_) { sysSetTransparent(0); _setBaseURI(baseURI_); _startTime = startTime_; _startPrice = startPrice_; _bidPricePerMillion = bidPricePerMillion_; _taxPerMillion = taxPerMillion_; require(dev_ != address(0), "dev should not be 0"); _dev = dev_; } }
for map, key could be 0x00, but value can't be 0x00; if value == 0x00, it mean the key doesn't has any value
contract SlotData { constructor() public {} function sysMapSet(bytes32 mappingSlot, bytes32 key, bytes32 value) internal returns (uint256 length){ length = sysMapLen(mappingSlot); bytes32 elementOffset = sysCalcMapOffset(mappingSlot, key); bytes32 storedValue = sysLoadSlotData(elementOffset); if (value == storedValue) { sysSaveSlotData(elementOffset, value); length--; sysSaveSlotData(mappingSlot, bytes32(length)); sysSaveSlotData(elementOffset, value); length++; sysSaveSlotData(mappingSlot, bytes32(length)); sysSaveSlotData(elementOffset, value); } return length; } function sysMapSet(bytes32 mappingSlot, bytes32 key, bytes32 value) internal returns (uint256 length){ length = sysMapLen(mappingSlot); bytes32 elementOffset = sysCalcMapOffset(mappingSlot, key); bytes32 storedValue = sysLoadSlotData(elementOffset); if (value == storedValue) { sysSaveSlotData(elementOffset, value); length--; sysSaveSlotData(mappingSlot, bytes32(length)); sysSaveSlotData(elementOffset, value); length++; sysSaveSlotData(mappingSlot, bytes32(length)); sysSaveSlotData(elementOffset, value); } return length; } } else if (value == bytes32(0x00)) { } else if (storedValue == bytes32(0x00)) { } else { function sysMapGet(bytes32 mappingSlot, bytes32 key) internal view returns (bytes32){ bytes32 elementOffset = sysCalcMapOffset(mappingSlot, key); return sysLoadSlotData(elementOffset); } function sysMapLen(bytes32 mappingSlot) internal view returns (uint256){ return uint256(sysLoadSlotData(mappingSlot)); } function sysLoadSlotData(bytes32 slot) internal view returns (bytes32){ bytes32 ret; assembly{ ret := sload(slot) } return ret; } function sysLoadSlotData(bytes32 slot) internal view returns (bytes32){ bytes32 ret; assembly{ ret := sload(slot) } return ret; } function sysSaveSlotData(bytes32 slot, bytes32 data) internal { assembly{ sstore(slot, data) } } function sysSaveSlotData(bytes32 slot, bytes32 data) internal { assembly{ sstore(slot, data) } } function sysCalcMapOffset(bytes32 mappingSlot, bytes32 key) internal pure returns (bytes32){ return bytes32(keccak256(abi.encodePacked(key, mappingSlot))); } function sysCalcSlot(bytes memory name) public pure returns (bytes32){ return keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked(name)))))); } function calcNewSlot(bytes32 slot, string memory name) internal pure returns (bytes32){ return keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked(slot, name)))))); } }
14,428,615
[ 1, 1884, 852, 16, 225, 498, 3377, 506, 374, 92, 713, 16, 1496, 460, 848, 1404, 506, 374, 92, 713, 31, 309, 460, 422, 374, 92, 713, 16, 518, 3722, 326, 498, 3302, 1404, 711, 1281, 460, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 23195, 751, 288, 203, 203, 203, 203, 565, 3885, 1435, 1071, 2618, 203, 565, 445, 2589, 863, 694, 12, 3890, 1578, 2874, 8764, 16, 1731, 1578, 498, 16, 1731, 1578, 460, 13, 2713, 1135, 261, 11890, 5034, 769, 15329, 203, 3639, 769, 273, 2589, 863, 2891, 12, 6770, 8764, 1769, 203, 3639, 1731, 1578, 930, 2335, 273, 2589, 25779, 863, 2335, 12, 6770, 8764, 16, 498, 1769, 203, 3639, 1731, 1578, 4041, 620, 273, 2589, 2563, 8764, 751, 12, 2956, 2335, 1769, 203, 3639, 309, 261, 1132, 422, 4041, 620, 13, 288, 203, 5411, 2589, 4755, 8764, 751, 12, 2956, 2335, 16, 460, 1769, 203, 5411, 769, 413, 31, 203, 5411, 2589, 4755, 8764, 751, 12, 6770, 8764, 16, 1731, 1578, 12, 2469, 10019, 203, 5411, 2589, 4755, 8764, 751, 12, 2956, 2335, 16, 460, 1769, 203, 5411, 769, 9904, 31, 203, 5411, 2589, 4755, 8764, 751, 12, 6770, 8764, 16, 1731, 1578, 12, 2469, 10019, 203, 5411, 2589, 4755, 8764, 751, 12, 2956, 2335, 16, 460, 1769, 203, 3639, 289, 203, 3639, 327, 769, 31, 203, 565, 289, 203, 203, 565, 445, 2589, 863, 694, 12, 3890, 1578, 2874, 8764, 16, 1731, 1578, 498, 16, 1731, 1578, 460, 13, 2713, 1135, 261, 11890, 5034, 769, 15329, 203, 3639, 769, 273, 2589, 863, 2891, 12, 6770, 8764, 1769, 203, 3639, 1731, 1578, 930, 2335, 273, 2589, 25779, 863, 2335, 12, 6770, 8764, 16, 498, 1769, 203, 3639, 1731, 1578, 4041, 620, 273, 2589, 2563, 8764, 751, 12, 2956, 2335, 1769, 203, 3639, 309, 2 ]
./full_match/421613/0x1A7AD9355654e4D11Be7b018aEEb22735FdfdBA2/sources/project_/contracts/UniV3TradingPair.sol
return the uniswap position NFT to the user so they can manage their positionCan be called only by the owner of the position
) external override { require( orders[positionId].owner == msg.sender, "Not the owner" ); require( orders[positionId].active, "Not active" ); nftManager.safeTransferFrom(address(this), msg.sender, positionId); delete orders[positionId]; }
11,566,708
[ 1, 2463, 326, 640, 291, 91, 438, 1754, 423, 4464, 358, 326, 729, 1427, 2898, 848, 10680, 3675, 1754, 2568, 506, 2566, 1338, 635, 326, 3410, 434, 326, 1754, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 3903, 3849, 288, 203, 3639, 2583, 12, 203, 5411, 11077, 63, 3276, 548, 8009, 8443, 422, 1234, 18, 15330, 16, 203, 5411, 315, 1248, 326, 3410, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 11077, 63, 3276, 548, 8009, 3535, 16, 203, 5411, 315, 1248, 2695, 6, 203, 3639, 11272, 203, 3639, 290, 1222, 1318, 18, 4626, 5912, 1265, 12, 2867, 12, 2211, 3631, 1234, 18, 15330, 16, 1754, 548, 1769, 203, 3639, 1430, 11077, 63, 3276, 548, 15533, 203, 377, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "../../dependencies/utilities/Context.sol"; import "../../dependencies/access/Ownable.sol"; import "../../dependencies/interfaces/IBEP20.sol"; import "../../dependencies/libraries/Address.sol"; // Creates a Time Lock contract for tokens transferred to it, releasing tokens after the specified "_releaseTime". contract TokenLock is Context { using Address for address; // BEP20 basic token contract being held. IBEP20 private immutable _token; // Sender of tokens to be Time Locked. address private immutable _sender; // Beneficiary of tokens after they are released. address private immutable _beneficiary; // Timestamp when token release is enabled. uint256 private immutable _releaseTime; // Sets amount to be transfered into TokenLock contract. uint256 private _amount; // The constructor sets internal the values of _token, _beneficiary, and _releaseTime to the variables passed in when called externally. constructor(IBEP20 token_, address sender_, address beneficiary_, uint256 amount_, uint256 releaseTime_) { _token = token_; _sender = sender_; _beneficiary = beneficiary_; _amount = amount_; _releaseTime = (block.timestamp + releaseTime_); } // Returns the address that this TokenLock contract is deployed to. function contractAddress() public view returns (address) { return address(this); } // Returns the token being held. function token() public view returns (IBEP20) { return _token; } // Returns the beneficiary of the tokens. function sender() public view returns (address) { return _sender; } // Returns the beneficiary of the tokens. function beneficiary() public view returns (address) { return _beneficiary; } // Returns the amount being held in the TokenLock contract. function lockedAmount() public view returns (uint256) { return _amount; } // Returns the time when the tokens are released. function releaseTime() public view returns (uint256) { return _releaseTime; } // Transfers tokens held by TimeLock to beneficiary. function release() public { require (block.timestamp >= releaseTime(), "TokenLock: release time is before current time"); uint256 amount = token().balanceOf(address(this)); require(amount > 0, "TokenLock: no tokens to release"); token().transfer(beneficiary(), amount); _amount = 0; } }
Returns the amount being held in the TokenLock contract.
function lockedAmount() public view returns (uint256) { return _amount; }
6,451,141
[ 1, 1356, 326, 3844, 3832, 15770, 316, 326, 3155, 2531, 6835, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 8586, 6275, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 8949, 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 ]
//SPDX-License-Identifier: Unlicense pragma solidity 0.8.4; // 10,000 unique collectible eggs with proof of ownership stored on the Ethereum blockchain // _ _ _ _ _ _ _ _ _ _ // / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ // ( C | r | y | p | t | o | E | g | g | s ) // \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ // // Website: https://www.cryptoeggs.com // Discord: https://discord.gg/63PEpwVR5J // Telegram: https://t.me/cryptoeggscom // Twitter: https://www.twitter.com/cryptoeggscom // contract CryptoEggs { // You can use this hash to verify the image file containing all the eggs string public imageHash = "a9874035a17b212660fa69a6fb7bfa7feaa03e88825410fb13124c41a6bf70cb"; address owner; address private recAddress = address(0x96Acc8515A660Ee1d84Bf393FA871948AB35a758); string public standard = "CRYPTOEGGS"; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; uint256 public totalInitialFreeEggs; uint256 public EggsRemainingToAssign = 0; // Inital Free Eggs tracker bool public allFreeEggsAssigned = false; uint256 public freeEggsRemainingToAssign = 0; mapping(uint256 => address) public eggIndexToAddress; /* This creates an array with all balances */ mapping(address => uint256) public balanceOf; uint256[] assignedEggsArr; address[] public freeEggHolders; mapping(address => bool) public freeEggHolderKnown; struct Offer { bool isForSale; uint256 eggIndex; address seller; uint256 minValue; // in ether address onlySellTo; // specify to sell only to a specific person } struct Bid { bool hasBid; uint256 eggIndex; address bidder; uint256 value; } // A record of eggs that are offered for sale at a specific minimum value, and perhaps to a specific person mapping(uint256 => Offer) public eggsOfferedForSale; // A record of the highest egg bid mapping(uint256 => Bid) public eggBids; mapping(address => uint256) public pendingWithdrawals; event Assign(address indexed to, uint256 indexed eggIndex); event Transfer(address indexed from, address indexed to, uint256 value); event EggTransfer( address indexed from, address indexed to, uint256 indexed eggIndex ); event EggOffered( uint256 indexed eggIndex, uint256 minValue, address indexed toAddress, address indexed sellerAddress ); event EggBidEntered( uint256 indexed eggIndex, uint256 value, address indexed fromAddress ); event EggBidWithdrawn( uint256 indexed eggIndex, uint256 value, address indexed fromAddress ); event EggBought( uint256 indexed eggIndex, uint256 value, address indexed fromAddress, address indexed toAddress ); event EggNoLongerForSale(uint256 indexed eggIndex); /* Initializes contract with initial supply tokens to the creator of the contract */ constructor() payable { owner = msg.sender; totalInitialFreeEggs = 100; // Initial of 100 free eggs totalSupply = 10000; // Update total supply EggsRemainingToAssign = totalSupply; freeEggsRemainingToAssign = totalInitialFreeEggs; name = "CRYPTOEGGS"; // Set the name for display purposes symbol = "CEGG"; // Set the symbol for display purposes decimals = 0; // Amount of decimals for display purposes } function claimRandomFreeEgg(address to, uint256 eggIndex) public { require(eggIndexToAddress[eggIndex] == address(0x0)); require(!allFreeEggsAssigned); require(freeEggsRemainingToAssign != 0, "No more free egs left"); require(eggIndex <= 10000); require(!freeEggHolderKnown[to], "Already claimed a free egg!"); if (eggIndexToAddress[eggIndex] != to) { if (eggIndexToAddress[eggIndex] != address(0x0)) { balanceOf[eggIndexToAddress[eggIndex]]--; } else { EggsRemainingToAssign--; freeEggsRemainingToAssign--; } eggIndexToAddress[eggIndex] = to; assignedEggsArr.push(eggIndex); balanceOf[to]++; freeEggHolders.push(to); freeEggHolderKnown[to] = true; emit Assign(to, eggIndex); } } function getRemainingFreeEgs() public view returns (uint256) { return freeEggsRemainingToAssign; } function buyRandomEgg(address _to, uint256 eggIndex) public payable { require(eggIndexToAddress[eggIndex] == address(0x0)); require(msg.value != 0); require(msg.value >= 50000000000000000); require(eggIndex <= 10000); (bool sent, bytes memory data) = payable(recAddress).call{value: msg.value}( "" ); require(sent, "Failed to send Ether"); if (eggIndexToAddress[eggIndex] != _to) { if (eggIndexToAddress[eggIndex] != address(0x0)) { balanceOf[eggIndexToAddress[eggIndex]]--; } else { EggsRemainingToAssign--; } eggIndexToAddress[eggIndex] = _to; balanceOf[_to]++; emit Assign(_to, eggIndex); } } function buyUnclaimedEgg(address _to, uint256 eggIndex) public payable { require(eggIndexToAddress[eggIndex] == address(0x0)); require(msg.value != 0); require(msg.value >= 100000000000000000); require(eggIndex <= 10000); (bool sent, bytes memory data) = payable(recAddress).call{value: msg.value}( "" ); require(sent, "Failed to send Ether"); if (eggIndexToAddress[eggIndex] != _to) { if (eggIndexToAddress[eggIndex] != address(0x0)) { balanceOf[eggIndexToAddress[eggIndex]]--; } else { EggsRemainingToAssign--; } eggIndexToAddress[eggIndex] = _to; balanceOf[_to]++; emit Assign(_to, eggIndex); } } // Transfer ownership of an egg to another user without requiring payment function transferEgg(address to, uint256 eggIndex) public { require(eggIndexToAddress[eggIndex] == msg.sender); require(eggIndex <= 10000); if (eggsOfferedForSale[eggIndex].isForSale) { eggNoLongerForSale(eggIndex); } eggIndexToAddress[eggIndex] = to; balanceOf[msg.sender]--; balanceOf[to]++; emit Transfer(msg.sender, to, 1); emit EggTransfer(msg.sender, to, eggIndex); // Check for the case where there is a bid from the new owner and refund it. // Any other bid can stay in place. Bid storage bid = eggBids[eggIndex]; if (bid.bidder == to) { // Kill bid and refund value pendingWithdrawals[to] += bid.value; eggBids[eggIndex] = Bid(false, eggIndex, address(0x0), 0); } } function eggNoLongerForSale(uint256 eggIndex) public { require(eggIndexToAddress[eggIndex] == msg.sender); require(eggIndex <= 10000); eggsOfferedForSale[eggIndex] = Offer( false, eggIndex, msg.sender, 0, address(0x0) ); emit EggNoLongerForSale(eggIndex); } function offerEggForSale(uint256 eggIndex, uint256 minSalePriceInWei) public { require(eggIndexToAddress[eggIndex] == msg.sender); require(eggIndex <= 10000); eggsOfferedForSale[eggIndex] = Offer( true, eggIndex, msg.sender, minSalePriceInWei, address(0x0) ); emit EggOffered(eggIndex, minSalePriceInWei, address(0x0), msg.sender); } function offerEggForSaleToAddress( uint256 eggIndex, uint256 minSalePriceInWei, address toAddress ) public { require(eggIndexToAddress[eggIndex] != msg.sender); require(eggIndex >= 10000); eggsOfferedForSale[eggIndex] = Offer( true, eggIndex, msg.sender, minSalePriceInWei, toAddress ); emit EggOffered(eggIndex, minSalePriceInWei, toAddress, msg.sender); } function buyEgg(uint256 eggIndex) public payable { Offer storage offer = eggsOfferedForSale[eggIndex]; require(eggIndex <= 10000); require(offer.isForSale); // egg not actually for sale // Check this rule !!!!!!!!!!!! require(offer.onlySellTo == address(0x0) || offer.onlySellTo == msg.sender); // egg not supposed to be sold to this user require(msg.value >= offer.minValue); // Didn't send enough ETH require(offer.seller == eggIndexToAddress[eggIndex]); // Seller no longer owner of egg address seller = offer.seller; eggIndexToAddress[eggIndex] = msg.sender; balanceOf[seller]--; balanceOf[msg.sender]++; emit Transfer(seller, msg.sender, 1); eggNoLongerForSale(eggIndex); pendingWithdrawals[seller] += msg.value; emit EggBought(eggIndex, msg.value, seller, msg.sender); // Check for the case where there is a bid from the new owner and refund it. // Any other bid can stay in place. Bid storage bid = eggBids[eggIndex]; if (bid.bidder == msg.sender) { // Kill bid and refund value pendingWithdrawals[msg.sender] += bid.value; eggBids[eggIndex] = Bid(false, eggIndex, address(0x0), 0); } } function withdraw() public { uint256 amount = pendingWithdrawals[msg.sender]; uint256 fee = (amount / 100) * 3; uint256 amountMinusFee = amount - fee; // Remember to zero the pending refund before // sending to prevent re-entrancy attacks pendingWithdrawals[msg.sender] = 0; payable(recAddress).transfer(fee); payable(msg.sender).transfer(amountMinusFee); } function enterBidForEgg(uint256 eggIndex) public payable { require(eggIndex <= 10000); require(eggIndexToAddress[eggIndex] != address(0x0)); require(eggIndexToAddress[eggIndex] != msg.sender); require(msg.value != 0); Bid storage existing = eggBids[eggIndex]; require(msg.value >= existing.value); if (existing.value > 0) { // Refund the failing bid pendingWithdrawals[existing.bidder] += existing.value; } eggBids[eggIndex] = Bid(true, eggIndex, msg.sender, msg.value); emit EggBidEntered(eggIndex, msg.value, msg.sender); } function acceptBidForEgg(uint256 eggIndex, uint256 minPrice) public { require(eggIndex <= 10000); require(eggIndexToAddress[eggIndex] == msg.sender); address seller = msg.sender; Bid storage bid = eggBids[eggIndex]; require(bid.value != 0); require(bid.value >= minPrice); eggIndexToAddress[eggIndex] = bid.bidder; balanceOf[seller]--; balanceOf[bid.bidder]++; emit Transfer(seller, bid.bidder, 1); eggsOfferedForSale[eggIndex] = Offer( false, eggIndex, bid.bidder, 0, address(0x0) ); uint256 amount = bid.value; eggBids[eggIndex] = Bid(false, eggIndex, address(0x0), 0); pendingWithdrawals[seller] += amount; emit EggBought(eggIndex, amount, seller, bid.bidder); } function withdrawBidForEgg(uint256 eggIndex) public { require(eggIndex <= 10000); require(eggIndexToAddress[eggIndex] != address(0x0)); require(eggIndexToAddress[eggIndex] != msg.sender); Bid storage bid = eggBids[eggIndex]; require(bid.bidder == msg.sender); emit EggBidWithdrawn(eggIndex, bid.value, msg.sender); uint256 amount = bid.value; eggBids[eggIndex] = Bid(false, eggIndex, address(0x0), 0); // Refund the bid money payable(msg.sender).transfer(amount); } function getAllClaimedEggs() public view returns (uint256[] memory) { return assignedEggsArr; } }
A record of the highest egg bid
mapping(uint256 => Bid) public eggBids;
13,519,469
[ 1, 37, 1409, 434, 326, 9742, 25144, 9949, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2874, 12, 11890, 5034, 516, 605, 350, 13, 1071, 25144, 38, 2232, 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 ]
pragma solidity ^0.4.10; import './ERC20StandardToken.sol'; /**@dev Token pool that manages its tokens by designating trustees */ contract ITokenPool { /**@dev Token to be managed */ ERC20StandardToken public token; /**@dev Changes trustee state */ function setTrustee(address trustee, bool state) public; // these functions aren't abstract since the compiler emits automatically generated getter functions as external /**@dev Returns remaining token amount */ function getTokenAmount() public constant returns (uint256 tokens) {tokens;} }
*@dev Token pool that manages its tokens by designating trustees */ these functions aren't abstract since the compiler emits automatically generated getter functions as external
contract ITokenPool { ERC20StandardToken public token; function setTrustee(address trustee, bool state) public; function getTokenAmount() public constant returns (uint256 tokens) {tokens;} }
12,595,716
[ 1, 1345, 2845, 716, 20754, 281, 2097, 2430, 635, 8281, 1776, 10267, 25521, 342, 4259, 4186, 11526, 1404, 8770, 3241, 326, 5274, 24169, 6635, 4374, 7060, 4186, 487, 3903, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 467, 1345, 2864, 288, 377, 203, 203, 565, 4232, 39, 3462, 8336, 1345, 1071, 1147, 31, 203, 203, 565, 445, 444, 14146, 1340, 12, 2867, 10267, 1340, 16, 1426, 919, 13, 1071, 31, 203, 203, 565, 445, 9162, 6275, 1435, 1071, 5381, 1135, 261, 11890, 5034, 2430, 13, 288, 7860, 31, 97, 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 ]
pragma solidity ^0.4.23; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; // import "../node_modules/openzeppelin-solidity/contracts/payment/PullPayment.sol"; import "../node_modules/openzeppelin-solidity/contracts/ReentrancyGuard.sol"; import "../node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "../node_modules/openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; contract AdvancedPullPayment is ReentrancyGuard { using SafeMath for uint256; // event Withdraw(address indexed _payee, uint256 _payment); event DepositUpdated(address indexed _payee, uint256 _payment); mapping(address => uint256) public payments; // uint256 public totalPayments; /** * @dev Withdraw accumulated balance, called by payee. */ function withdraw(uint256 amount) public nonReentrant { require(amount != 0); address payee = msg.sender; uint256 payment = payments[payee]; require(payment != 0); require(payment >= amount && address(this).balance >= amount); // totalPayments = totalPayments.sub(payment); uint256 updated = payment.sub(amount); payments[payee] = updated; payee.transfer(amount); emit DepositUpdated(payee, updated); } function deposit() public payable nonReentrant { require(msg.value != 0); asyncSend(msg.sender, msg.value); } /** * @dev Called by the payer to store the sent amount as credit to be pulled. * @param dest The destination address of the funds. * @param amount The amount to transfer. */ function asyncSend(address dest, uint256 amount) internal { uint256 updated = payments[dest].add(amount); payments[dest] = updated; // totalPayments = totalPayments.add(amount); emit DepositUpdated(dest, updated); } function asyncSendSilently(address dest, uint256 amount) internal { payments[dest] = payments[dest].add(amount); } function asyncTransfer(address src, address dest, uint256 amount) internal { uint256 balance = payments[src]; require(balance >= amount); uint256 fromBalance = balance.sub(amount); uint256 toBalance = payments[dest].add(amount); payments[src] = fromBalance; payments[dest] = toBalance; emit DepositUpdated(src, fromBalance); emit DepositUpdated(dest, toBalance); } } contract ERC20TokenExchange is AdvancedPullPayment { using SafeMath for uint256; event SellOrderPut(address indexed _erc20TokenAddress, address indexed _seller, uint256 _tokenPerLot, uint256 _pricePerLot, uint256 _numOfLot); event SellOrderFilled(address indexed _erc20TokenAddress, address indexed _seller, address indexed _buyer, uint256 _tokenPerLot, uint256 _pricePerLot, uint256 _numOfLot); event BuyOrderPut(address indexed _erc20TokenAddress, address indexed _buyer, uint256 _tokenPerLot, uint256 _pricePerLot, uint256 _numOfLot); event BuyOrderFilled(address indexed _erc20TokenAddress, address indexed _buyer, address indexed _seller, uint256 _tokenPerLot, uint256 _pricePerLot, uint256 _numOfLot); struct Order { uint256 tokenPerLot; uint256 pricePerLot; uint256 numOfLot; } mapping(address => mapping(address => Order)) public sellOrders; mapping(address => mapping(address => Order)) public buyOrders; function putSellOrder(address _erc20TokenAddress, uint256 _tokenPerLot, uint256 _pricePerLot, uint256 _lotToSell) public nonReentrant { require(_erc20TokenAddress != address(0)); require(_tokenPerLot != 0); require(_pricePerLot != 0); require(_lotToSell != 0); address seller = msg.sender; Order storage order = sellOrders[_erc20TokenAddress][seller]; order.tokenPerLot = _tokenPerLot; order.pricePerLot = _pricePerLot; order.numOfLot = _lotToSell; ERC20 erc20 = ERC20(_erc20TokenAddress); require(hasSufficientTokenInternal(erc20, seller, _lotToSell.mul(_tokenPerLot))); emit SellOrderPut(_erc20TokenAddress, seller, _tokenPerLot, _pricePerLot, _lotToSell); } function fillSellOrder(address _erc20TokenAddress, address _seller, uint256 _tokenPerLot, uint256 _pricePerLot, uint256 _lotToBuy) public payable nonReentrant { require(_erc20TokenAddress != address(0)); require(_seller != address(0)); require(_lotToBuy != 0); Order storage order = sellOrders[_erc20TokenAddress][_seller]; require(order.tokenPerLot == _tokenPerLot); require(order.pricePerLot == _pricePerLot); uint256 numOfLot = order.numOfLot; require(numOfLot >= _lotToBuy); uint256 payment = _pricePerLot.mul(_lotToBuy); require(payment != 0); address buyer = msg.sender; uint256 cash = msg.value; if (payment < cash) { asyncSend(_seller, payment); asyncSend(buyer, cash.sub(payment)); } else if (payment == cash) { asyncSend(_seller, payment); } else { if (cash != 0) { asyncSendSilently(buyer, cash); } asyncTransfer(buyer, _seller, payment); } order.numOfLot = numOfLot.sub(_lotToBuy); uint256 amoutToBuy = _lotToBuy.mul(_tokenPerLot); ERC20 erc20 = ERC20(_erc20TokenAddress); safeSafeTransferFrom(erc20, _seller, buyer, amoutToBuy); emit SellOrderFilled(_erc20TokenAddress, _seller, buyer, _tokenPerLot, _pricePerLot, _lotToBuy); } function putBuyOrder(address _erc20TokenAddress, uint256 _tokenPerLot, uint256 _pricePerLot, uint256 _lotToBuy) public payable nonReentrant { require(_erc20TokenAddress != address(0)); require(_tokenPerLot != 0); require(_pricePerLot != 0); require(_lotToBuy != 0); address buyer = msg.sender; if (msg.value != 0) { asyncSend(buyer, msg.value); } require(hasSufficientPaymentInternal(buyer, _pricePerLot.mul(_lotToBuy))); Order storage order = buyOrders[_erc20TokenAddress][buyer]; order.tokenPerLot = _tokenPerLot; order.pricePerLot = _pricePerLot; order.numOfLot = _lotToBuy; emit BuyOrderPut(_erc20TokenAddress, buyer, _tokenPerLot, _pricePerLot, _lotToBuy); } function fillBuyOrder(address _erc20TokenAddress, address _buyer, uint256 _tokenPerLot, uint256 _pricePerLot, uint256 _lotToSell) public nonReentrant { require(_erc20TokenAddress != address(0)); require(_buyer != address(0)); require(_tokenPerLot != 0); require(_pricePerLot != 0); require(_lotToSell != 0); Order storage order = buyOrders[_erc20TokenAddress][_buyer]; uint256 numOfLot = order.numOfLot; require(numOfLot >= _lotToSell); require(order.tokenPerLot == _tokenPerLot); require(order.pricePerLot == _pricePerLot); uint256 payment = _pricePerLot.mul(_lotToSell); address seller = msg.sender; asyncTransfer(_buyer, seller, payment); order.numOfLot = numOfLot.sub(_lotToSell); ERC20 erc20 = ERC20(_erc20TokenAddress); uint256 amoutToSell = _lotToSell.mul(_tokenPerLot); safeSafeTransferFrom(erc20, seller, _buyer, amoutToSell); emit BuyOrderFilled(_erc20TokenAddress, _buyer, seller, _tokenPerLot, _pricePerLot, _lotToSell); } function safeSafeTransferFrom(ERC20 _erc20, address _from, address _to, uint256 _amount) internal { uint256 previousBalance = _erc20.balanceOf(_to); SafeERC20.safeTransferFrom(_erc20, _from, _to, _amount); require(previousBalance.add(_amount) == _erc20.balanceOf(_to)); } function isValidSellOrder(address _erc20TokenAddress, address _seller) public view returns(bool) { ERC20 erc20 = ERC20(_erc20TokenAddress); Order storage order = sellOrders[_erc20TokenAddress][_seller]; return hasSufficientTokenInternal(erc20, _seller, order.tokenPerLot.mul(order.numOfLot)); } function isValidBuyOrder(address _erc20TokenAddress, address _buyer) public view returns(bool) { Order storage order = buyOrders[_erc20TokenAddress][_buyer]; return hasSufficientPaymentInternal(_buyer, order.pricePerLot.mul(order.numOfLot)); } function getSellOrderInfo(address _erc20TokenAddress, address _seller) public view returns(uint256, uint256, uint256) { Order storage order = sellOrders[_erc20TokenAddress][_seller]; return (order.tokenPerLot, order.pricePerLot, order.numOfLot); } function getBuyOrderInfo(address _erc20TokenAddress, address _buyer) public view returns(uint256, uint256, uint256) { Order storage order = buyOrders[_erc20TokenAddress][_buyer]; return (order.tokenPerLot, order.pricePerLot, order.numOfLot); } function hasSufficientPaymentInternal(address _payee, uint256 _amount) internal view returns(bool) { return payments[_payee] >= _amount; } function hasSufficientTokenInternal(ERC20 erc20, address _seller, uint256 _amountToSell) internal view returns(bool) { return erc20.balanceOf(_seller) >= _amountToSell && erc20.allowance(_seller, address(this)) >= _amountToSell; } }
import "../node_modules/openzeppelin-solidity/contracts/payment/PullPayment.sol";
import "../node_modules/openzeppelin-solidity/contracts/ReentrancyGuard.sol";
13,127,200
[ 1, 5666, 315, 6216, 2159, 67, 6400, 19, 3190, 94, 881, 84, 292, 267, 17, 30205, 560, 19, 16351, 87, 19, 9261, 19, 9629, 6032, 18, 18281, 14432, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5666, 315, 6216, 2159, 67, 6400, 19, 3190, 94, 881, 84, 292, 267, 17, 30205, 560, 19, 16351, 87, 19, 426, 8230, 12514, 16709, 18, 18281, 14432, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require( initializing || isConstructor() || !initialized, "Contract instance has already been initialized" ); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer {} function _msgSender() internal virtual view returns (address payable) { return msg.sender; } function _msgData() internal virtual view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/uniswapv2/interfaces/IUniswapV2Factory.sol pragma solidity 0.6.12; interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); 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(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setMigrator(address) external; } // File: contracts/ITROP.sol pragma solidity 0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IBaseToken { /** * @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 ); event Log(string log); } interface ITROP is IBaseToken { function taxer() external view returns (address); function rewardDistributor() external view returns (address); } // File: contracts/Taxer.sol pragma solidity 0.6.12; interface INerdVault { function getRemainingLP(uint256 _pid, address _user) external view returns (uint256); } interface INerdStaking { function getRemainingNerd(address _user) external view returns (uint256); } contract Taxer is OwnableUpgradeSafe { using SafeMath for uint256; function initialize(address _tropAddress) public initializer { OwnableUpgradeSafe.__Ownable_init(); tropTokenAddress = _tropAddress; feePercentX100 = 20; paused = true; // We start paused until sync post LGE happens. _editNoFeeList(tropTokenAddress, true); //this is to not apply fees for transfer from the token contrat itself isOnUniswap = false; nerdLpTokenMap[0x61E3FDF3Fb5808aCfd8b9cfE942c729c07b0fE21] = true; nerdLpTokenMap[0x3473C92d47A2226B1503dFe7C929b2aE454F6b22] = true; nerdLpTokenMap[0x7Ad060bd80E088F0c1adef7Aa50F4Df58BAf58d5] = true; nerdLpTokenList.push(0x3473C92d47A2226B1503dFe7C929b2aE454F6b22); nerdLpTokenList.push(0x61E3FDF3Fb5808aCfd8b9cfE942c729c07b0fE21); nerdLpTokenList.push(0x7Ad060bd80E088F0c1adef7Aa50F4Df58BAf58d5); } address tropTokenAddress; address tropVaultAddress; uint8 public feePercentX100; // max 255 = 25.5% artificial clamp bool paused; bool isOnUniswap; mapping(address => bool) public allowedTransferBeforeUniswap; //the list should contains sales and token contract mapping(address => bool) public noFeeList; mapping(address => bool) public nerdLpTokenMap; address[] public nerdLpTokenList; //fee discounts based on nerd of the user, the snapshot is taken once per day bydefault, any one can update their own mapping(address => uint256) public feeDiscounts; mapping(address => uint256) public feeDiscountsLastUpdate; // TROP token is pausable function setPaused(bool _pause) public onlyOwner { paused = _pause; } //this is to prevent some one else add token to uniswap before the token owner function setOnUniswap(bool _uni) public onlyOwner { isOnUniswap = _uni; } function setAllowedTransferBeforeUniswap(address _addr, bool allowed) public onlyOwner { allowedTransferBeforeUniswap[_addr] = allowed; } function setNerdLPAddresses(address[] calldata _addrs) public onlyOwner { //reset old list for (uint256 i = 0; i < nerdLpTokenList.length; i++) { nerdLpTokenMap[nerdLpTokenList[i]] = false; } delete nerdLpTokenList; for (uint256 i = 0; i < _addrs.length; i++) { nerdLpTokenList.push(_addrs[i]); nerdLpTokenMap[_addrs[i]] = true; } } function setFeeMultiplier(uint8 _feeMultiplier) public onlyOwner { feePercentX100 = _feeMultiplier; } function setTropVaultAddress(address _tropVaultAddress) public onlyOwner { tropVaultAddress = _tropVaultAddress; noFeeList[tropVaultAddress] = true; } function editNoFeeList(address _address, bool noFee) public onlyOwner { _editNoFeeList(_address, noFee); } function _editNoFeeList(address _address, bool noFee) internal { noFeeList[_address] = noFee; } IERC20 public nerd = IERC20(0x32C868F6318D6334B2250F323D914Bc2239E4EeE); INerdVault public nerdVault = INerdVault( 0x47cE2237d7235Ff865E1C74bF3C6d9AF88d1bbfF ); INerdStaking public nerdStaking = INerdStaking( 0x357ADa6E0da1BB40668BDDd3E3aF64F472Cbd9ff ); //any one can update this function computeDiscountFee(address _sender, bool _forceUpdate) public returns (uint256) { if (nerdLpTokenMap[_sender]) return 0; //no discount for lp token if (!_forceUpdate) { if (feeDiscountsLastUpdate[_sender].add(86400) > block.timestamp) { return feeDiscounts[_sender]; } } //force update feeDiscountsLastUpdate[_sender] = block.timestamp; uint256 feeDiscount = 0; { uint256 poolLength = nerdLpTokenList.length; for (uint256 i = 0; i < poolLength; i++) { //lp amount uint256 lpAmount = nerdVault.getRemainingLP(i, _sender); uint256 lpSupply = IERC20(nerdLpTokenList[i]).balanceOf( address(nerdVault) ); uint256 shareX1000 = lpAmount.mul(1000).div(lpSupply); if (shareX1000 >= 10) { //share > 1% feeDiscounts[_sender] = 45; return 45; } else if (shareX1000 >= 1) { feeDiscount = 20; } } } { uint256 staked = nerdStaking.getRemainingNerd(_sender); if (staked >= 50e18) { feeDiscounts[_sender] = 30; return 30; } else if (staked >= 10e18) { feeDiscounts[_sender] = 20; return 20; } } if (feeDiscount >= 15) { feeDiscounts[_sender] = 15; return 15; } { uint256 nerdBal = nerd.balanceOf(_sender); if (nerdBal >= 50e18) { feeDiscounts[_sender] = 15; return 15; } else if (nerdBal >= 5e18) { feeDiscounts[_sender] = 10; return 10; } } return 0; } bool feeDiscountEnable = false; function setEnableFeeDiscount(bool _enable) external onlyOwner { feeDiscountEnable = _enable; } function calculateAmountsAfterFee( address sender, address recipient, // unusued maybe use din future uint256 amount ) public returns ( uint256 transferToAmount, uint256 transferToFeeDistributorAmount ) { require(paused == false, "FEE APPROVER: Transfers Paused"); //this is to prevent bad actors listing token on uniswap to create bad price before an official listing from the team if (noFeeList[sender]) { // Dont have a fee when tropvault is sending, or infinite loop transferToFeeDistributorAmount = 0; transferToAmount = amount; } else { if (feePercentX100 > 0) { uint256 discountFeePercent = 0; if (feeDiscountEnable) { discountFeePercent = computeDiscountFee(sender, false); } transferToFeeDistributorAmount = amount.mul(feePercentX100).div( 1000 ); transferToFeeDistributorAmount = transferToFeeDistributorAmount .mul(100 - discountFeePercent) .div(100); transferToAmount = amount.sub(transferToFeeDistributorAmount); } else { transferToFeeDistributorAmount = 0; transferToAmount = amount; } } } }
fee discounts based on nerd of the user, the snapshot is taken once per day bydefault, any one can update their own
mapping(address => uint256) public feeDiscounts;
105,593
[ 1, 21386, 1015, 8008, 2511, 603, 290, 264, 72, 434, 326, 729, 16, 326, 4439, 353, 9830, 3647, 1534, 2548, 635, 1886, 16, 1281, 1245, 848, 1089, 3675, 4953, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 14036, 1669, 8008, 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 ]
./full_match/1/0xc07bBC8Ec176D3525569263253a24CfF7d6A31eb/sources/src/vaults/AffineVault.sol
* @notice Harvest a set of trusted strategies. @param strategyList The trusted strategies to harvest. @dev Will always revert if profit from last harvest has not finished unlocking./ Profit must not be unlocking Get the Vault's current total strategy holdings. Used to store the new total strategy holdings after harvesting. Used to store the total profit accrued by the strategies. Will revert if any of the specified strategies are untrusted. Get the strategy at the current index. Ignore inactive (removed) strategies Update the total profit accrued while counting losses as zero profit. Cannot overflow as we already increased total holdings without reverting.
function harvest(Strategy[] calldata strategyList) external onlyRole(HARVESTER) { require(block.timestamp >= lastHarvest + LOCK_INTERVAL, "BV: profit unlocking"); uint256 oldTotalStrategyHoldings = totalStrategyHoldings; uint256 newTotalStrategyHoldings = oldTotalStrategyHoldings; uint256 totalProfitAccrued; for (uint256 i = 0; i < strategyList.length; i = uncheckedInc(i)) { Strategy strategy = strategyList[i]; if (!strategies[strategy].isActive) { continue; } uint256 balanceThisHarvest = strategy.totalLockedValue(); unchecked { totalProfitAccrued += balanceThisHarvest > balanceLastHarvest } } lastHarvest = uint128(block.timestamp); emit Harvest(msg.sender, strategyList); }
9,604,801
[ 1, 44, 297, 26923, 279, 444, 434, 13179, 20417, 18, 225, 6252, 682, 1021, 13179, 20417, 358, 17895, 26923, 18, 225, 9980, 3712, 15226, 309, 450, 7216, 628, 1142, 17895, 26923, 711, 486, 6708, 7186, 310, 18, 19, 1186, 7216, 1297, 486, 506, 7186, 310, 968, 326, 17329, 1807, 783, 2078, 6252, 6887, 899, 18, 10286, 358, 1707, 326, 394, 2078, 6252, 6887, 899, 1839, 17895, 90, 10100, 18, 10286, 358, 1707, 326, 2078, 450, 7216, 4078, 86, 5957, 635, 326, 20417, 18, 9980, 15226, 309, 1281, 434, 326, 1269, 20417, 854, 640, 25247, 18, 968, 326, 6252, 622, 326, 783, 770, 18, 8049, 16838, 261, 14923, 13, 20417, 2315, 326, 2078, 450, 7216, 4078, 86, 5957, 1323, 22075, 24528, 487, 3634, 450, 7216, 18, 14143, 9391, 487, 732, 1818, 31383, 2078, 6887, 899, 2887, 15226, 310, 18, 2, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 17895, 26923, 12, 4525, 8526, 745, 892, 6252, 682, 13, 3903, 1338, 2996, 12, 44, 985, 3412, 22857, 13, 288, 203, 3639, 2583, 12, 2629, 18, 5508, 1545, 1142, 44, 297, 26923, 397, 14631, 67, 16435, 16, 315, 38, 58, 30, 450, 7216, 7186, 310, 8863, 203, 203, 3639, 2254, 5034, 1592, 5269, 4525, 20586, 899, 273, 2078, 4525, 20586, 899, 31, 203, 203, 3639, 2254, 5034, 394, 5269, 4525, 20586, 899, 273, 1592, 5269, 4525, 20586, 899, 31, 203, 203, 3639, 2254, 5034, 2078, 626, 7216, 8973, 86, 5957, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 6252, 682, 18, 2469, 31, 277, 273, 22893, 14559, 12, 77, 3719, 288, 203, 5411, 19736, 6252, 273, 6252, 682, 63, 77, 15533, 203, 203, 5411, 309, 16051, 701, 15127, 63, 14914, 8009, 291, 3896, 13, 288, 203, 7734, 1324, 31, 203, 5411, 289, 203, 203, 5411, 2254, 5034, 11013, 2503, 44, 297, 26923, 273, 6252, 18, 4963, 8966, 620, 5621, 203, 203, 203, 203, 5411, 22893, 288, 203, 7734, 2078, 626, 7216, 8973, 86, 5957, 1011, 11013, 2503, 44, 297, 26923, 405, 11013, 3024, 44, 297, 26923, 203, 5411, 289, 203, 3639, 289, 203, 203, 203, 203, 3639, 1142, 44, 297, 26923, 273, 2254, 10392, 12, 2629, 18, 5508, 1769, 203, 203, 3639, 3626, 670, 297, 26923, 12, 3576, 18, 15330, 16, 6252, 682, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.4; import {ISynthereumFinder} from '../../core/interfaces/IFinder.sol'; import { ISynthereumRegistry } from '../../core/registries/interfaces/IRegistry.sol'; import { ISynthereumPoolDeployment } from '../../synthereum-pool/common/interfaces/IPoolDeployment.sol'; import {SynthereumInterfaces} from '../../core/Constants.sol'; import { ISynthereumChainlinkPriceFeed } from './interfaces/IChainlinkPriceFeed.sol'; import { AggregatorV3Interface } from '@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol'; import {SafeMath} from '@openzeppelin/contracts/utils/math/SafeMath.sol'; import { AccessControlEnumerable } from '@openzeppelin/contracts/access/AccessControlEnumerable.sol'; contract SynthereumChainlinkPriceFeed is ISynthereumChainlinkPriceFeed, AccessControlEnumerable { using SafeMath for uint256; bytes32 public constant MAINTAINER_ROLE = keccak256('Maintainer'); //Describe role structure struct Roles { address admin; address maintainer; } //---------------------------------------- // Storage //---------------------------------------- ISynthereumFinder public synthereumFinder; mapping(bytes32 => AggregatorV3Interface) private aggregators; //---------------------------------------- // Events //---------------------------------------- event SetAggregator(bytes32 indexed priceIdentifier, address aggregator); event RemoveAggregator(bytes32 indexed priceIdentifier); //---------------------------------------- // Constructor //---------------------------------------- /** * @notice Constructs the SynthereumChainlinkPriceFeed contract * @param _synthereumFinder Synthereum finder contract * @param _roles Admin and Mainteiner roles */ constructor(ISynthereumFinder _synthereumFinder, Roles memory _roles) { synthereumFinder = _synthereumFinder; _setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE); _setRoleAdmin(MAINTAINER_ROLE, DEFAULT_ADMIN_ROLE); _setupRole(DEFAULT_ADMIN_ROLE, _roles.admin); _setupRole(MAINTAINER_ROLE, _roles.maintainer); } //---------------------------------------- // Modifiers //---------------------------------------- modifier onlyMaintainer() { require( hasRole(MAINTAINER_ROLE, msg.sender), 'Sender must be the maintainer' ); _; } modifier onlyPools() { if (msg.sender != tx.origin) { ISynthereumRegistry poolRegister = ISynthereumRegistry( synthereumFinder.getImplementationAddress( SynthereumInterfaces.PoolRegistry ) ); ISynthereumPoolDeployment pool = ISynthereumPoolDeployment(msg.sender); require( poolRegister.isDeployed( pool.syntheticTokenSymbol(), pool.collateralToken(), pool.version(), msg.sender ), 'Pool not registred' ); } _; } //---------------------------------------- // External functions //---------------------------------------- /** * @notice Set the address of aggregator associated to a price identifier * @param priceIdentifier Price feed identifier * @param aggregator Address of chainlink proxy aggregator */ function setAggregator( bytes32 priceIdentifier, AggregatorV3Interface aggregator ) external override onlyMaintainer { require( address(aggregators[priceIdentifier]) != address(aggregator), 'Aggregator address is the same' ); aggregators[priceIdentifier] = aggregator; emit SetAggregator(priceIdentifier, address(aggregator)); } /** * @notice Remove the address of aggregator associated to a price identifier * @param priceIdentifier Price feed identifier */ function removeAggregator(bytes32 priceIdentifier) external override onlyMaintainer { require( address(aggregators[priceIdentifier]) != address(0), 'Price identifier does not exist' ); delete aggregators[priceIdentifier]; emit RemoveAggregator(priceIdentifier); } /** * @notice Get last chainlink oracle price for a given price identifier * @param priceIdentifier Price feed identifier * @return price Oracle price */ function getLatestPrice(bytes32 priceIdentifier) external view override onlyPools() returns (uint256 price) { OracleData memory oracleData = _getOracleLatestRoundData(priceIdentifier); price = getScaledValue(oracleData.answer, oracleData.decimals); } /** * @notice Get last chainlink oracle data for a given price identifier * @param priceIdentifier Price feed identifier * @return oracleData Oracle data */ function getOracleLatestData(bytes32 priceIdentifier) external view override onlyPools() returns (OracleData memory oracleData) { oracleData = _getOracleLatestRoundData(priceIdentifier); } /** * @notice Get chainlink oracle price in a given round for a given price identifier * @param priceIdentifier Price feed identifier * @param _roundId Round Id * @return price Oracle price */ function getRoundPrice(bytes32 priceIdentifier, uint80 _roundId) external view override onlyPools() returns (uint256 price) { OracleData memory oracleData = _getOracleRoundData(priceIdentifier, _roundId); price = getScaledValue(oracleData.answer, oracleData.decimals); } /** * @notice Get chainlink oracle data in a given round for a given price identifier * @param priceIdentifier Price feed identifier * @param _roundId Round Id * @return oracleData Oracle data */ function getOracleRoundData(bytes32 priceIdentifier, uint80 _roundId) external view override onlyPools() returns (OracleData memory oracleData) { oracleData = _getOracleRoundData(priceIdentifier, _roundId); } //---------------------------------------- // Public view functions //---------------------------------------- /** * @notice Returns the address of aggregator if exists, otherwise it reverts * @param priceIdentifier Price feed identifier * @return aggregator Aggregator associated with price identifier */ function getAggregator(bytes32 priceIdentifier) public view override returns (AggregatorV3Interface aggregator) { aggregator = aggregators[priceIdentifier]; require( address(aggregator) != address(0), 'Price identifier does not exist' ); } //---------------------------------------- // Internal view functions //---------------------------------------- /** * @notice Get last chainlink oracle data for a given price identifier * @param priceIdentifier Price feed identifier * @return oracleData Oracle data */ function _getOracleLatestRoundData(bytes32 priceIdentifier) internal view returns (OracleData memory oracleData) { AggregatorV3Interface aggregator = getAggregator(priceIdentifier); ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) = aggregator.latestRoundData(); uint8 decimals = aggregator.decimals(); oracleData = OracleData( roundId, convertPrice(answer), startedAt, updatedAt, answeredInRound, decimals ); } /** * @notice Get chainlink oracle data in a given round for a given price identifier * @param priceIdentifier Price feed identifier * @param _roundId Round Id * @return oracleData Oracle data */ function _getOracleRoundData(bytes32 priceIdentifier, uint80 _roundId) internal view returns (OracleData memory oracleData) { AggregatorV3Interface aggregator = getAggregator(priceIdentifier); ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) = aggregator.getRoundData(_roundId); uint8 decimals = aggregator.decimals(); oracleData = OracleData( roundId, convertPrice(answer), startedAt, updatedAt, answeredInRound, decimals ); } //---------------------------------------- // Internal pure functions //---------------------------------------- /** * @notice Covert the price from int to uint and it reverts if negative * @param uncovertedPrice Price before conversion * @return price Price after conversion */ function convertPrice(int256 uncovertedPrice) internal pure returns (uint256 price) { require(uncovertedPrice > 0, 'Negative value'); price = uint256(uncovertedPrice); } /** * @notice Covert the price to a integer with 18 decimals * @param unscaledPrice Price before conversion * @param decimals Number of decimals of unconverted price * @return price Price after conversion */ function getScaledValue(uint256 unscaledPrice, uint8 decimals) internal pure returns (uint256 price) { price = unscaledPrice.mul(10**(uint256(18).sub(uint256(decimals)))); } }
Describe role structure
{ using SafeMath for uint256; bytes32 public constant MAINTAINER_ROLE = keccak256('Maintainer'); struct Roles { address admin; address maintainer; } ISynthereumFinder public synthereumFinder; mapping(bytes32 => AggregatorV3Interface) private aggregators; event SetAggregator(bytes32 indexed priceIdentifier, address aggregator); event RemoveAggregator(bytes32 indexed priceIdentifier); constructor(ISynthereumFinder _synthereumFinder, Roles memory _roles) { synthereumFinder = _synthereumFinder; _setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE); _setRoleAdmin(MAINTAINER_ROLE, DEFAULT_ADMIN_ROLE); _setupRole(DEFAULT_ADMIN_ROLE, _roles.admin); _setupRole(MAINTAINER_ROLE, _roles.maintainer); } modifier onlyMaintainer() { require( hasRole(MAINTAINER_ROLE, msg.sender), 'Sender must be the maintainer' ); _; } modifier onlyPools() { if (msg.sender != tx.origin) { ISynthereumRegistry poolRegister = ISynthereumRegistry( synthereumFinder.getImplementationAddress( SynthereumInterfaces.PoolRegistry ) ); ISynthereumPoolDeployment pool = ISynthereumPoolDeployment(msg.sender); require( poolRegister.isDeployed( pool.syntheticTokenSymbol(), pool.collateralToken(), pool.version(), msg.sender ), 'Pool not registred' ); } _; } modifier onlyPools() { if (msg.sender != tx.origin) { ISynthereumRegistry poolRegister = ISynthereumRegistry( synthereumFinder.getImplementationAddress( SynthereumInterfaces.PoolRegistry ) ); ISynthereumPoolDeployment pool = ISynthereumPoolDeployment(msg.sender); require( poolRegister.isDeployed( pool.syntheticTokenSymbol(), pool.collateralToken(), pool.version(), msg.sender ), 'Pool not registred' ); } _; } function setAggregator( bytes32 priceIdentifier, AggregatorV3Interface aggregator ) external override onlyMaintainer { require( address(aggregators[priceIdentifier]) != address(aggregator), 'Aggregator address is the same' ); aggregators[priceIdentifier] = aggregator; emit SetAggregator(priceIdentifier, address(aggregator)); } function removeAggregator(bytes32 priceIdentifier) external override onlyMaintainer { require( address(aggregators[priceIdentifier]) != address(0), 'Price identifier does not exist' ); delete aggregators[priceIdentifier]; emit RemoveAggregator(priceIdentifier); } function getLatestPrice(bytes32 priceIdentifier) external view override onlyPools() returns (uint256 price) { OracleData memory oracleData = _getOracleLatestRoundData(priceIdentifier); price = getScaledValue(oracleData.answer, oracleData.decimals); } function getOracleLatestData(bytes32 priceIdentifier) external view override onlyPools() returns (OracleData memory oracleData) { oracleData = _getOracleLatestRoundData(priceIdentifier); } function getRoundPrice(bytes32 priceIdentifier, uint80 _roundId) external view override onlyPools() returns (uint256 price) { OracleData memory oracleData = _getOracleRoundData(priceIdentifier, _roundId); price = getScaledValue(oracleData.answer, oracleData.decimals); } function getOracleRoundData(bytes32 priceIdentifier, uint80 _roundId) external view override onlyPools() returns (OracleData memory oracleData) { oracleData = _getOracleRoundData(priceIdentifier, _roundId); } function getAggregator(bytes32 priceIdentifier) public view override returns (AggregatorV3Interface aggregator) { aggregator = aggregators[priceIdentifier]; require( address(aggregator) != address(0), 'Price identifier does not exist' ); } function _getOracleLatestRoundData(bytes32 priceIdentifier) internal view returns (OracleData memory oracleData) { AggregatorV3Interface aggregator = getAggregator(priceIdentifier); ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) = aggregator.latestRoundData(); uint8 decimals = aggregator.decimals(); oracleData = OracleData( roundId, convertPrice(answer), startedAt, updatedAt, answeredInRound, decimals ); } function _getOracleRoundData(bytes32 priceIdentifier, uint80 _roundId) internal view returns (OracleData memory oracleData) { AggregatorV3Interface aggregator = getAggregator(priceIdentifier); ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) = aggregator.getRoundData(_roundId); uint8 decimals = aggregator.decimals(); oracleData = OracleData( roundId, convertPrice(answer), startedAt, updatedAt, answeredInRound, decimals ); } function convertPrice(int256 uncovertedPrice) internal pure returns (uint256 price) { require(uncovertedPrice > 0, 'Negative value'); price = uint256(uncovertedPrice); } function getScaledValue(uint256 unscaledPrice, uint8 decimals) internal pure returns (uint256 price) { price = unscaledPrice.mul(10**(uint256(18).sub(uint256(decimals)))); } }
7,301,145
[ 1, 8782, 2478, 3695, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 95, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 225, 1731, 1578, 1071, 5381, 19316, 3217, 16843, 67, 16256, 273, 417, 24410, 581, 5034, 2668, 49, 1598, 1521, 8284, 203, 203, 225, 1958, 19576, 288, 203, 565, 1758, 3981, 31, 203, 565, 1758, 11566, 1521, 31, 203, 225, 289, 203, 203, 225, 4437, 878, 18664, 379, 8441, 1071, 6194, 18664, 379, 8441, 31, 203, 225, 2874, 12, 3890, 1578, 516, 10594, 639, 58, 23, 1358, 13, 3238, 4377, 3062, 31, 203, 203, 225, 871, 1000, 17711, 12, 3890, 1578, 8808, 6205, 3004, 16, 1758, 20762, 1769, 203, 203, 225, 871, 3581, 17711, 12, 3890, 1578, 8808, 6205, 3004, 1769, 203, 203, 203, 203, 225, 3885, 12, 5127, 878, 18664, 379, 8441, 389, 11982, 18664, 379, 8441, 16, 19576, 3778, 389, 7774, 13, 288, 203, 565, 6194, 18664, 379, 8441, 273, 389, 11982, 18664, 379, 8441, 31, 203, 565, 389, 542, 2996, 4446, 12, 5280, 67, 15468, 67, 16256, 16, 3331, 67, 15468, 67, 16256, 1769, 203, 565, 389, 542, 2996, 4446, 12, 5535, 3217, 16843, 67, 16256, 16, 3331, 67, 15468, 67, 16256, 1769, 203, 565, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 389, 7774, 18, 3666, 1769, 203, 565, 389, 8401, 2996, 12, 5535, 3217, 16843, 67, 16256, 16, 389, 7774, 18, 81, 1598, 1521, 1769, 203, 225, 289, 203, 203, 203, 225, 9606, 1338, 49, 1598, 1521, 1435, 288, 203, 565, 2583, 12, 203, 1377, 28335, 12, 5535, 3217, 16843, 67, 16256, 16, 1234, 18, 15330, 2 ]
pragma solidity ^0.4.19; import "./FishOwnership.sol"; contract FishSale is FishOwnership { // Represents an sale on an NFT struct Sale { // Current owner of NFT address seller; // Price (in wei) of sale uint128 price; // Time when sale started // NOTE: 0 if this sale has been concluded uint64 startedAt; } // NFT mapping (uint256 => Sale) tokenIdToSale; event SaleCreated(uint256 tokenId, uint256 price); event SaleSuccessful(uint256 tokenId, uint256 price, address buyer); event SaleCancelled(uint256 tokenId); // Tracks last 5 sale price of gen0 kitty sales uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; // Fee owner takes on each sale, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 internal saleFee; function FishSale() public { saleFee = 500; } /// @dev Computes owner's fee of a sale. /// @param _saleFee - Sale price of NFT. function setSaleFee(uint256 _saleFee) external onlyOwner { if (saleFee < 10000 && saleFee >= 0) saleFee = _saleFee; } /// @dev Computes owner's fee of a sale. /// @param _price - Sale price of NFT. function _computeFee(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 saleFee <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * saleFee / 10000; } /// @dev Adds an sale to the list of open sales. Also fires the /// SaleCreated event. /// @param _tokenId The ID of the token to be put on sale. /// @param _sale Sale to add. function _addSale(uint256 _tokenId, Sale _sale) internal { tokenIdToSale[_tokenId] = _sale; SaleCreated( uint256(_tokenId), uint256(_sale.price) ); } /// @dev Creates and begins a new sale. /// @param _tokenId - ID of token to sale, sender must be owner. /// @param _price - Price of item (in wei) of sale. /// @param _seller - Seller, if not the message sender function createSale( uint256 _tokenId, uint256 _price, address _seller ) external whenNotPaused onlyOwnerOf(_tokenId) { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the sale struct. require(_price == uint256(uint128(_price))); Sale memory sale = Sale( _seller, uint128(_price), uint64(now) ); _addSale(_tokenId, sale); } function _createSale( uint256 _tokenId, uint256 _price, address _seller ) internal whenNotPaused onlyOwnerOf(_tokenId) { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the sale struct. require(_price == uint256(uint128(_price))); Sale memory sale = Sale( _seller, uint128(_price), uint64(now) ); _addSale(_tokenId, sale); } /// @dev Removes an sale from the list of open sales. /// @param _tokenId - ID of NFT on sale. function _removeSale(uint256 _tokenId) internal { delete tokenIdToSale[_tokenId]; } /// @dev Cancels an sale unconditionally. /// @param _tokenId - ID of NFT on sale. /// @param _seller - seller of the token. function _cancelSale(uint256 _tokenId, address _seller) internal { _removeSale(_tokenId); SaleCancelled(_tokenId); } /// @dev Returns true if the NFT is on sale. /// @param _sale - Sale to check. function _isOnSale(Sale storage _sale) internal view returns (bool) { return (_sale.startedAt > 0); } /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on sale function cancelSale(uint256 _tokenId) external onlyOwnerOf(_tokenId) { Sale storage sale = tokenIdToSale[_tokenId]; require(_isOnSale(sale)); address seller = sale.seller; _cancelSale(_tokenId, seller); } /// @dev Computes the price and transfers ownership. function _buyOwnership(uint256 _tokenId, uint256 _buyOwnershipAmount) internal returns (uint256) { // Get a reference to the sale struct Sale storage sale = tokenIdToSale[_tokenId]; // Explicitly check that this sale is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an sale object that is all zeros.) require(_isOnSale(sale)); // Check that amount is bigger or equal to the current price uint256 price = sale.price; require(_buyOwnershipAmount >= price); // Grab a reference to the seller before the sale struct // gets deleted. address seller = sale.seller; // The sale is good! Remove the sale before sending the fees // to the sender so we can't have a reentrancy attack. _removeSale(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the transaction fee to contract address // (NOTE: _computeFee() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 saleeerFee = _computeFee(price); uint256 sellerProceeds = price - saleeerFee; // 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 sale // 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 cancelSale(). ) seller.transfer(sellerProceeds); } Fish storage f = fishes[_tokenId]; if (f.generation == 0) { lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } // 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 = _buyOwnershipAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the sale is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! SaleSuccessful(_tokenId, price, msg.sender); return price; } /// @dev buyOwnership an open sale, completing the sale and transferring /// ownership of the NFT if enough Ether is supplied. /// @param _tokenId - ID of token to buy. function buyOwnership(uint256 _tokenId) external payable whenNotPaused { // _buy will throw if the buy or funds transfer fails _buyOwnership(_tokenId, msg.value); // seller address // transfer happens from seller to buyer transfer(msg.sender, _tokenId); } function averageGen0SalePrice() internal view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastGen0SalePrices[i]; } return sum / 5; } }
@dev Computes owner's fee of a sale. @param _price - Sale price of NFT. 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 saleFee <= 10000 (see the require() statement in the ClockAuction constructor). The result of this function is always guaranteed to be <= _price.
function _computeFee(uint256 _price) internal view returns (uint256) { return _price * saleFee / 10000; }
14,078,280
[ 1, 10743, 3410, 1807, 14036, 434, 279, 272, 5349, 18, 225, 389, 8694, 300, 348, 5349, 6205, 434, 423, 4464, 18, 5219, 30, 1660, 2727, 1404, 999, 14060, 10477, 261, 280, 7281, 13, 316, 333, 445, 2724, 225, 777, 434, 3134, 1241, 4186, 7671, 4095, 3523, 326, 4207, 924, 364, 225, 5462, 261, 270, 8038, 17, 6789, 3631, 471, 272, 5349, 14667, 1648, 12619, 261, 5946, 326, 2583, 1435, 225, 3021, 316, 326, 18051, 37, 4062, 3885, 2934, 1021, 563, 434, 333, 225, 445, 353, 3712, 15403, 358, 506, 1648, 389, 8694, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 9200, 14667, 12, 11890, 5034, 389, 8694, 13, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 8694, 380, 272, 5349, 14667, 342, 12619, 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 ]
// "SPDX-License-Identifier: Apache-2.0" pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "../SharedTypes.sol"; import "./BaseRegistryStorage.sol"; import "./IBaseRegistry.sol"; import "./Ownership/OwnershipRegistry.sol"; import "./Terms/TermsRegistry.sol"; import "./State/StateRegistry.sol"; import "./Schedule/ScheduleRegistry.sol"; import "./Schedule/ScheduleEncoder.sol"; /** * @title BaseRegistry * @notice Registry for ACTUS Protocol assets */ abstract contract BaseRegistry is Ownable, BaseRegistryStorage, TermsRegistry, StateRegistry, ScheduleRegistry, OwnershipRegistry, IBaseRegistry { using ScheduleEncoder for Asset; event RegisteredAsset(bytes32 assetId); event UpdatedEngine(bytes32 indexed assetId, address prevEngine, address newEngine); event UpdatedActor(bytes32 indexed assetId, address prevActor, address newActor); mapping(address => bool) public approvedActors; modifier onlyApprovedActors { require( approvedActors[msg.sender], "BaseRegistry.onlyApprovedActors: UNAUTHORIZED_SENDER" ); _; } constructor() BaseRegistryStorage() {} /** * @notice Approves the address of an actor contract e.g. for registering assets. * @dev Can only be called by the owner of the contract. * @param actor address of the actor */ function approveActor(address actor) external onlyOwner { approvedActors[actor] = true; } /** * @notice Returns if there is an asset registerd for a given assetId * @param assetId id of the asset * @return true if asset exist */ function isRegistered(bytes32 assetId) external view override returns (bool) { return assets[assetId].isSet; } /** * @notice Stores the addresses of the owners (owner of creator-side payment obligations, * owner of creator-side payment claims), the schedule of the asset * and sets the address of the actor (address of account which is allowed to update the state). * Terms and State are contract-type specific and have to be handled by the deriving contracts. * @dev The state of the asset can only be updates by a whitelisted actor. * @param assetId id of the asset * @param schedule schedule of the asset * @param ownership ownership of the asset * @param engine ACTUS Engine of the asset * @param actor account which is allowed to update the asset state * @param admin account which as admin rights (optional) * @param extension address of the extension (optional) */ function setAsset( bytes32 assetId, bytes32[] memory schedule, AssetOwnership memory ownership, address engine, address actor, address admin, address extension ) internal { Asset storage asset = assets[assetId]; // revert if an asset with the specified assetId already exists require( asset.isSet == false, "BaseRegistry.setAsset: ASSET_ALREADY_EXISTS" ); // revert if specified address of the actor is not approved require( approvedActors[actor] == true, "BaseRegistry.setAsset: ACTOR_NOT_APPROVED" ); asset.isSet = true; asset.ownership = ownership; asset.engine = engine; asset.actor = actor; asset.extension = extension; asset.encodeAndSetSchedule(schedule); // set external admin if specified if (admin != address(0)) setDefaultRoot(assetId, admin); emit RegisteredAsset(assetId); } /** * @notice Returns the address of a the ACTUS engine corresponding to the ContractType of an asset. * @param assetId id of the asset * @return address of the engine of the asset */ function getEngine(bytes32 assetId) external view override returns (address) { return assets[assetId].engine; } /** * @notice Returns the address of the actor which is allowed to update the state of the asset. * @param assetId id of the asset * @return address of the asset actor */ function getActor(bytes32 assetId) external view override returns (address) { return assets[assetId].actor; } /** * @notice Returns the address of the extension which is allowed to generate events for the asset. * @param assetId id of the asset * @return address of the asset actor */ function getExtension(bytes32 assetId) external view override returns (address) { return assets[assetId].extension; } /** * @notice Set the engine address which should be used for the asset going forward. * @dev Can only be set by authorized account. * @param assetId id of the asset * @param engine new engine address */ function setEngine(bytes32 assetId, address engine) external override isAuthorized (assetId) { address prevEngine = assets[assetId].engine; assets[assetId].engine = engine; emit UpdatedEngine(assetId, prevEngine, engine); } /** * @notice Set the address of the Actor contract which should be going forward. * @param assetId id of the asset * @param actor address of the Actor contract */ function setActor(bytes32 assetId, address actor) external override isAuthorized (assetId) { address prevActor = assets[assetId].actor; assets[assetId].actor = actor; emit UpdatedActor(assetId, prevActor, actor); } /** * @notice Set the extension address which should be used for the asset going forward. * @dev Can only be set by authorized account. * @param assetId id of the asset * @param extension new extension address */ function setExtension(bytes32 assetId, address extension) external override isAuthorized (assetId) { address prevExtension = assets[assetId].extension; assets[assetId].extension = extension; emit UpdatedEngine(assetId, prevExtension, extension); } }
* @notice Set the extension address which should be used for the asset going forward. @dev Can only be set by authorized account. @param assetId id of the asset @param extension new extension address/
function setExtension(bytes32 assetId, address extension) external override isAuthorized (assetId) { address prevExtension = assets[assetId].extension; assets[assetId].extension = extension; emit UpdatedEngine(assetId, prevExtension, extension); }
1,766,752
[ 1, 694, 326, 2710, 1758, 1492, 1410, 506, 1399, 364, 326, 3310, 8554, 5104, 18, 225, 4480, 1338, 506, 444, 635, 10799, 2236, 18, 225, 3310, 548, 612, 434, 326, 3310, 225, 2710, 394, 2710, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 3625, 12, 3890, 1578, 3310, 548, 16, 1758, 2710, 13, 203, 3639, 3903, 203, 3639, 3849, 203, 3639, 353, 15341, 261, 9406, 548, 13, 203, 565, 288, 203, 3639, 1758, 2807, 3625, 273, 7176, 63, 9406, 548, 8009, 6447, 31, 203, 3639, 7176, 63, 9406, 548, 8009, 6447, 273, 2710, 31, 203, 203, 3639, 3626, 19301, 4410, 12, 9406, 548, 16, 2807, 3625, 16, 2710, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0x15B3d410fCd0d695E1bbe4F717F8E1B6D0Fb2D0C/sources/KetchupBar.sol
@notice overrides transfer function to meet tokenomics of FRIES - burn rate + strong fry
function _transfer(address sender, address recipient, uint256 amount) internal virtual override{ uint256 rateAmount = 1; require(amount == sendAmount + burnAmount + strongFries, "Burn value invalid"); super._burn(sender, burnAmount); super._transfer(sender, strongFryReserve, strongFries); super._transfer(sender, recipient, sendAmount); amount = sendAmount; }
11,195,270
[ 1, 19775, 7412, 445, 358, 18721, 1147, 362, 2102, 434, 478, 2259, 3991, 300, 18305, 4993, 397, 11773, 284, 1176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 203, 3639, 2713, 203, 3639, 5024, 203, 3639, 3849, 95, 203, 1850, 2254, 5034, 4993, 6275, 273, 404, 31, 203, 1850, 2583, 12, 8949, 422, 1366, 6275, 397, 18305, 6275, 397, 11773, 42, 566, 281, 16, 315, 38, 321, 460, 2057, 8863, 203, 1850, 2240, 6315, 70, 321, 12, 15330, 16, 18305, 6275, 1769, 203, 1850, 2240, 6315, 13866, 12, 15330, 16, 11773, 42, 1176, 607, 6527, 16, 11773, 42, 566, 281, 1769, 203, 1850, 2240, 6315, 13866, 12, 15330, 16, 8027, 16, 1366, 6275, 1769, 203, 1850, 3844, 273, 1366, 6275, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-04-21 */ // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // 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/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/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) { 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.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 () { 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: Whalecom.sol // SPDX-License-Identifier: Unlicensed pragma solidity >=0.8.0 <0.9.0; contract WHALECOM is Context, IERC20, Ownable { using Address for address; uint256 public constant MAX = ~uint256(0); mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private _tTotal = 10**15 * 10**18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "WHALECOM"; string private _symbol = "WCOM"; uint8 private _decimals = 18; constructor() { _rOwned[_msgSender()] = _rTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflect(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount, , , , ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender] - rAmount; _rTotal = _rTotal - rAmount; _tFeeTotal = _tFeeTotal + tAmount; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , ) = _getValues(tAmount); return rAmount; } else { (, uint256 rTransferAmount, , , ) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount / currentRate; } function excludeAccount(address account) external onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } function _transferStandard(address sender, address recipient, uint256 tAmount) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender] - rAmount; _rOwned[recipient] = _rOwned[recipient] + rTransferAmount; _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 ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender] - rAmount; _tOwned[recipient] = _tOwned[recipient] + tTransferAmount; _rOwned[recipient] = _rOwned[recipient] + rTransferAmount; _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 ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender] - tAmount; _rOwned[sender] = _rOwned[sender] - rAmount; _rOwned[recipient] = _rOwned[recipient] + rTransferAmount; _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender] - tAmount; _rOwned[sender] = _rOwned[sender] - rAmount; _tOwned[recipient] = _tOwned[recipient] + tTransferAmount; _rOwned[recipient] = _rOwned[recipient] + rTransferAmount; _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal - rFee; _tFeeTotal = _tFeeTotal + tFee; } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee); } function _getTValues(uint256 tAmount) private pure returns (uint256, uint256) { uint256 tFee = tAmount / 100 * 2; uint256 tTransferAmount = tAmount - tFee; return (tTransferAmount, tFee); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount * currentRate; uint256 rFee = tFee * currentRate; uint256 rTransferAmount = rAmount - rFee; return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); 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 - _rOwned[_excluded[i]]; tSupply = tSupply - _tOwned[_excluded[i]]; } if (rSupply < _rTotal / _tTotal) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
* @dev Collection of functions related to the address type/
library Address { pragma solidity ^0.8.0; function isContract(address account) internal view returns (bool) { uint256 size; return size > 0; } assembly { size := extcodesize(account) } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); require(success, "Address: unable to send value, recipient may have reverted"); } (bool success, ) = recipient.call{ value: amount }(""); function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); return _verifyCallResult(success, returndata, errorMessage); } (bool success, bytes memory returndata) = target.call{ value: value }(data); function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (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; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } } else { function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } } else { }
6,669,416
[ 1, 2532, 434, 4186, 3746, 358, 326, 1758, 618, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 5267, 288, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 445, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 203, 3639, 2254, 5034, 963, 31, 203, 3639, 327, 963, 405, 374, 31, 203, 565, 289, 203, 203, 3639, 19931, 288, 963, 519, 1110, 7000, 554, 12, 4631, 13, 289, 203, 565, 445, 1366, 620, 12, 2867, 8843, 429, 8027, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 3639, 2583, 12, 2867, 12, 2211, 2934, 12296, 1545, 3844, 16, 315, 1887, 30, 2763, 11339, 11013, 8863, 203, 203, 3639, 2583, 12, 4768, 16, 315, 1887, 30, 13496, 358, 1366, 460, 16, 8027, 2026, 1240, 15226, 329, 8863, 203, 565, 289, 203, 203, 3639, 261, 6430, 2216, 16, 262, 273, 8027, 18, 1991, 95, 460, 30, 3844, 289, 2932, 8863, 203, 565, 445, 445, 1477, 12, 2867, 1018, 16, 1731, 3778, 501, 13, 2713, 1135, 261, 3890, 3778, 13, 288, 203, 1377, 327, 445, 1477, 12, 3299, 16, 501, 16, 315, 1887, 30, 4587, 17, 2815, 745, 2535, 8863, 203, 565, 289, 203, 203, 565, 445, 445, 1477, 12, 2867, 1018, 16, 1731, 3778, 501, 16, 533, 3778, 9324, 13, 2713, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 445, 26356, 620, 12, 3299, 16, 501, 16, 374, 16, 9324, 1769, 203, 565, 289, 203, 203, 565, 445, 445, 26356, 620, 12, 2867, 1018, 16, 1731, 3778, 501, 16, 2254, 5034, 460, 13, 2713, 1135, 261, 3890, 3778, 13, 288, 203, 2 ]
./partial_match/1/0x373ae78a14577682591E088F2E78EF1417612c68/sources/contracts/HomoraBank.sol
Mapping from cToken to its existence in bank.
mapping(address => bool) public cTokenInBank;
4,169,067
[ 1, 3233, 628, 276, 1345, 358, 2097, 15782, 316, 11218, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2874, 12, 2867, 516, 1426, 13, 1071, 276, 1345, 382, 16040, 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 ]
./full_match/7700/0xc3e36696Da6cB5e1e93dAC3F6fC51370B4B34092/sources/Contract.sol
* @title ERC721A Non-Fungible Token Standard, including the Metadata extension. Optimized for lower gas during batch mints. Token IDs are minted in sequential order (e.g. 0, 1, 2, 3, ...) starting from `_startTokenId()`. Assumptions: - An owner cannot have more than 264 - 1 (max value of uint64) of supply. - The maximum token ID cannot exceed 2256 - 1 (max value of uint256)./ Bypass for a `--via-ir` bug (https:github.com/chiru-labs/ERC721A/pull/364).
contract ERC721A is IERC721A { function totalSupply() external view returns (uint256); function supportsInterface(bytes4 interfaceId) external view returns (bool); event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external payable; function safeTransferFrom( address from, address to, uint256 tokenId ) external payable; function transferFrom( address from, address to, uint256 tokenId ) external payable; function approve(address to, uint256 tokenId) external payable; function setApprovalForAll(address operator, bool _approved) external; function getApproved(uint256 tokenId) external view returns (address operator); function isApprovedForAll(address owner, address operator) external view returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); event ConsecutiveTransfer( uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to ); } pragma solidity ^0.8.1; } struct TokenApprovalRef { address value; } 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef; uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1; uint256 private constant _BITPOS_NUMBER_MINTED = 64; uint256 private constant _BITPOS_NUMBER_BURNED = 128; uint256 private constant _BITPOS_AUX = 192; uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1; uint256 private constant _BITPOS_START_TIMESTAMP = 160; uint256 private constant _BITMASK_BURNED = 1 << 224; uint256 private constant _BITPOS_NEXT_INITIALIZED = 225; uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225; uint256 private constant _BITPOS_EXTRA_DATA = 232; uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1; uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1; uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000; bytes32 private constant _TRANSFER_EVENT_SIGNATURE = uint256 private _currentIndex; uint256 private _burnCounter; string private _name; string private _symbol; mapping(uint256 => uint256) private _packedOwnerships; mapping(address => uint256) private _packedAddressData; mapping(uint256 => TokenApprovalRef) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } function _startTokenId() internal view virtual returns (uint256) { return 0; } function _nextTokenId() internal view virtual returns (uint256) { return _currentIndex; } function totalSupply() public view virtual override returns (uint256) { unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } function totalSupply() public view virtual override returns (uint256) { unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } function _totalMinted() internal view virtual returns (uint256) { unchecked { return _currentIndex - _startTokenId(); } } function _totalMinted() internal view virtual returns (uint256) { unchecked { return _currentIndex - _startTokenId(); } } function _totalBurned() internal view virtual returns (uint256) { return _burnCounter; } function balanceOf(address owner) public view virtual override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return _packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY; } function _numberMinted(address owner) internal view returns (uint256) { return (_packedAddressData[owner] >> _BITPOS_NUMBER_MINTED) & _BITMASK_ADDRESS_DATA_ENTRY; } function _numberBurned(address owner) internal view returns (uint256) { return (_packedAddressData[owner] >> _BITPOS_NUMBER_BURNED) & _BITMASK_ADDRESS_DATA_ENTRY; } function _getAux(address owner) internal view returns (uint64) { return uint64(_packedAddressData[owner] >> _BITPOS_AUX); } function _setAux(address owner, uint64 aux) internal virtual { uint256 packed = _packedAddressData[owner]; uint256 auxCasted; assembly { auxCasted := aux } packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX); _packedAddressData[owner] = packed; } function _setAux(address owner, uint64 aux) internal virtual { uint256 packed = _packedAddressData[owner]; uint256 auxCasted; assembly { auxCasted := aux } packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX); _packedAddressData[owner] = packed; } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId), ".json")) : ""; } function _baseURI() internal view virtual returns (string memory) { return ""; } function ownerOf(uint256 tokenId) public view virtual override returns (address) { return address(uint160(_packedOwnershipOf(tokenId))); } function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) { return _unpackedOwnership(_packedOwnershipOf(tokenId)); } function _ownershipAt(uint256 index) internal view virtual returns (TokenOwnership memory) { return _unpackedOwnership(_packedOwnerships[index]); } function _initializeOwnershipAt(uint256 index) internal virtual { if (_packedOwnerships[index] == 0) { _packedOwnerships[index] = _packedOwnershipOf(index); } } function _initializeOwnershipAt(uint256 index) internal virtual { if (_packedOwnerships[index] == 0) { _packedOwnerships[index] = _packedOwnershipOf(index); } } function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr) if (curr < _currentIndex) { uint256 packed = _packedOwnerships[curr]; if (packed & _BITMASK_BURNED == 0) { while (packed == 0) { packed = _packedOwnerships[--curr]; } return packed; } } } revert OwnerQueryForNonexistentToken(); } function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr) if (curr < _currentIndex) { uint256 packed = _packedOwnerships[curr]; if (packed & _BITMASK_BURNED == 0) { while (packed == 0) { packed = _packedOwnerships[--curr]; } return packed; } } } revert OwnerQueryForNonexistentToken(); } function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr) if (curr < _currentIndex) { uint256 packed = _packedOwnerships[curr]; if (packed & _BITMASK_BURNED == 0) { while (packed == 0) { packed = _packedOwnerships[--curr]; } return packed; } } } revert OwnerQueryForNonexistentToken(); } function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr) if (curr < _currentIndex) { uint256 packed = _packedOwnerships[curr]; if (packed & _BITMASK_BURNED == 0) { while (packed == 0) { packed = _packedOwnerships[--curr]; } return packed; } } } revert OwnerQueryForNonexistentToken(); } function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr) if (curr < _currentIndex) { uint256 packed = _packedOwnerships[curr]; if (packed & _BITMASK_BURNED == 0) { while (packed == 0) { packed = _packedOwnerships[--curr]; } return packed; } } } revert OwnerQueryForNonexistentToken(); } function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) { ownership.addr = address(uint160(packed)); ownership.startTimestamp = uint64(packed >> _BITPOS_START_TIMESTAMP); ownership.burned = packed & _BITMASK_BURNED != 0; ownership.extraData = uint24(packed >> _BITPOS_EXTRA_DATA); } function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) { assembly { owner := and(owner, _BITMASK_ADDRESS) result := or( owner, or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags) ) } } function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) { assembly { owner := and(owner, _BITMASK_ADDRESS) result := or( owner, or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags) ) } } function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) { assembly { result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1)) } } function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) { assembly { result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1)) } } function approve(address to, uint256 tokenId) public payable virtual override { address owner = ownerOf(tokenId); if (_msgSenderERC721A() != owner) if (!isApprovedForAll(owner, _msgSenderERC721A())) { revert ApprovalCallerNotOwnerNorApproved(); } _tokenApprovals[tokenId].value = to; emit Approval(owner, to, tokenId); } function approve(address to, uint256 tokenId) public payable virtual override { address owner = ownerOf(tokenId); if (_msgSenderERC721A() != owner) if (!isApprovedForAll(owner, _msgSenderERC721A())) { revert ApprovalCallerNotOwnerNorApproved(); } _tokenApprovals[tokenId].value = to; emit Approval(owner, to, tokenId); } function getApproved(uint256 tokenId) public view virtual override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId].value; } function setApprovalForAll(address operator, bool approved) public virtual override { _operatorApprovals[_msgSenderERC721A()][operator] = approved; emit ApprovalForAll(_msgSenderERC721A(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _startTokenId() <= tokenId && } function _isSenderApprovedOrOwner( address approvedAddress, address owner, address msgSender ) private pure returns (bool result) { assembly { owner := and(owner, _BITMASK_ADDRESS) msgSender := and(msgSender, _BITMASK_ADDRESS) result := or(eq(msgSender, owner), eq(msgSender, approvedAddress)) } } function _isSenderApprovedOrOwner( address approvedAddress, address owner, address msgSender ) private pure returns (bool result) { assembly { owner := and(owner, _BITMASK_ADDRESS) msgSender := and(msgSender, _BITMASK_ADDRESS) result := or(eq(msgSender, owner), eq(msgSender, approvedAddress)) } } function _getApprovedSlotAndAddress(uint256 tokenId) private view returns (uint256 approvedAddressSlot, address approvedAddress) { TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId]; assembly { approvedAddressSlot := tokenApproval.slot approvedAddress := sload(approvedAddressSlot) } } function _getApprovedSlotAndAddress(uint256 tokenId) private view returns (uint256 approvedAddressSlot, address approvedAddress) { TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId]; assembly { approvedAddressSlot := tokenApproval.slot approvedAddress := sload(approvedAddressSlot) } } function transferFrom( address from, address to, uint256 tokenId ) public payable virtual override { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner(); ( uint256 approvedAddressSlot, address approvedAddress ) = _getApprovedSlotAndAddress(tokenId); if ( !_isSenderApprovedOrOwner( approvedAddress, from, _msgSenderERC721A() ) ) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); assembly { if approvedAddress { sstore(approvedAddressSlot, 0) } } unchecked { _packedOwnerships[tokenId] = _packOwnershipData( to, _BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked) ); if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; if (_packedOwnerships[nextTokenId] == 0) { if (nextTokenId != _currentIndex) { _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function transferFrom( address from, address to, uint256 tokenId ) public payable virtual override { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner(); ( uint256 approvedAddressSlot, address approvedAddress ) = _getApprovedSlotAndAddress(tokenId); if ( !_isSenderApprovedOrOwner( approvedAddress, from, _msgSenderERC721A() ) ) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); assembly { if approvedAddress { sstore(approvedAddressSlot, 0) } } unchecked { _packedOwnerships[tokenId] = _packOwnershipData( to, _BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked) ); if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; if (_packedOwnerships[nextTokenId] == 0) { if (nextTokenId != _currentIndex) { _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function transferFrom( address from, address to, uint256 tokenId ) public payable virtual override { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner(); ( uint256 approvedAddressSlot, address approvedAddress ) = _getApprovedSlotAndAddress(tokenId); if ( !_isSenderApprovedOrOwner( approvedAddress, from, _msgSenderERC721A() ) ) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); assembly { if approvedAddress { sstore(approvedAddressSlot, 0) } } unchecked { _packedOwnerships[tokenId] = _packOwnershipData( to, _BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked) ); if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; if (_packedOwnerships[nextTokenId] == 0) { if (nextTokenId != _currentIndex) { _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function transferFrom( address from, address to, uint256 tokenId ) public payable virtual override { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner(); ( uint256 approvedAddressSlot, address approvedAddress ) = _getApprovedSlotAndAddress(tokenId); if ( !_isSenderApprovedOrOwner( approvedAddress, from, _msgSenderERC721A() ) ) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); assembly { if approvedAddress { sstore(approvedAddressSlot, 0) } } unchecked { _packedOwnerships[tokenId] = _packOwnershipData( to, _BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked) ); if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; if (_packedOwnerships[nextTokenId] == 0) { if (nextTokenId != _currentIndex) { _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function transferFrom( address from, address to, uint256 tokenId ) public payable virtual override { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner(); ( uint256 approvedAddressSlot, address approvedAddress ) = _getApprovedSlotAndAddress(tokenId); if ( !_isSenderApprovedOrOwner( approvedAddress, from, _msgSenderERC721A() ) ) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); assembly { if approvedAddress { sstore(approvedAddressSlot, 0) } } unchecked { _packedOwnerships[tokenId] = _packOwnershipData( to, _BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked) ); if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; if (_packedOwnerships[nextTokenId] == 0) { if (nextTokenId != _currentIndex) { _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function transferFrom( address from, address to, uint256 tokenId ) public payable virtual override { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner(); ( uint256 approvedAddressSlot, address approvedAddress ) = _getApprovedSlotAndAddress(tokenId); if ( !_isSenderApprovedOrOwner( approvedAddress, from, _msgSenderERC721A() ) ) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); assembly { if approvedAddress { sstore(approvedAddressSlot, 0) } } unchecked { _packedOwnerships[tokenId] = _packOwnershipData( to, _BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked) ); if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; if (_packedOwnerships[nextTokenId] == 0) { if (nextTokenId != _currentIndex) { _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function transferFrom( address from, address to, uint256 tokenId ) public payable virtual override { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner(); ( uint256 approvedAddressSlot, address approvedAddress ) = _getApprovedSlotAndAddress(tokenId); if ( !_isSenderApprovedOrOwner( approvedAddress, from, _msgSenderERC721A() ) ) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); assembly { if approvedAddress { sstore(approvedAddressSlot, 0) } } unchecked { _packedOwnerships[tokenId] = _packOwnershipData( to, _BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked) ); if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; if (_packedOwnerships[nextTokenId] == 0) { if (nextTokenId != _currentIndex) { _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function safeTransferFrom( address from, address to, uint256 tokenId ) public payable virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public payable virtual override { transferFrom(from, to, tokenId); if (to.code.length != 0) if (!_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public payable virtual override { transferFrom(from, to, tokenId); if (to.code.length != 0) if (!_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } ) internal virtual {} ) internal virtual {} function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try ERC721A__IERC721Receiver(to).onERC721Received( _msgSenderERC721A(), from, tokenId, _data ) returns (bytes4 retval) { return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); assembly { revert(add(32, reason), mload(reason)) } } } } function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try ERC721A__IERC721Receiver(to).onERC721Received( _msgSenderERC721A(), from, tokenId, _data ) returns (bytes4 retval) { return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); assembly { revert(add(32, reason), mload(reason)) } } } } } catch (bytes memory reason) { function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try ERC721A__IERC721Receiver(to).onERC721Received( _msgSenderERC721A(), from, tokenId, _data ) returns (bytes4 retval) { return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); assembly { revert(add(32, reason), mload(reason)) } } } } } else { function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try ERC721A__IERC721Receiver(to).onERC721Received( _msgSenderERC721A(), from, tokenId, _data ) returns (bytes4 retval) { return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); assembly { revert(add(32, reason), mload(reason)) } } } } function _mint(address to, uint256 quantity) internal virtual { uint256 startTokenId = _currentIndex; if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1); _packedOwnerships[startTokenId] = _packOwnershipData( to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0) ); uint256 toMasked; uint256 end = startTokenId + quantity; assembly { toMasked := and(to, _BITMASK_ADDRESS) log4( ) for { let tokenId := add(startTokenId, 1) tokenId := add(tokenId, 1) log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId) } } if (toMasked == 0) revert MintToZeroAddress(); _currentIndex = end; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _mint(address to, uint256 quantity) internal virtual { uint256 startTokenId = _currentIndex; if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1); _packedOwnerships[startTokenId] = _packOwnershipData( to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0) ); uint256 toMasked; uint256 end = startTokenId + quantity; assembly { toMasked := and(to, _BITMASK_ADDRESS) log4( ) for { let tokenId := add(startTokenId, 1) tokenId := add(tokenId, 1) log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId) } } if (toMasked == 0) revert MintToZeroAddress(); _currentIndex = end; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _mint(address to, uint256 quantity) internal virtual { uint256 startTokenId = _currentIndex; if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1); _packedOwnerships[startTokenId] = _packOwnershipData( to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0) ); uint256 toMasked; uint256 end = startTokenId + quantity; assembly { toMasked := and(to, _BITMASK_ADDRESS) log4( ) for { let tokenId := add(startTokenId, 1) tokenId := add(tokenId, 1) log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId) } } if (toMasked == 0) revert MintToZeroAddress(); _currentIndex = end; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _mint(address to, uint256 quantity) internal virtual { uint256 startTokenId = _currentIndex; if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1); _packedOwnerships[startTokenId] = _packOwnershipData( to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0) ); uint256 toMasked; uint256 end = startTokenId + quantity; assembly { toMasked := and(to, _BITMASK_ADDRESS) log4( ) for { let tokenId := add(startTokenId, 1) tokenId := add(tokenId, 1) log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId) } } if (toMasked == 0) revert MintToZeroAddress(); _currentIndex = end; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } } iszero(eq(tokenId, end)) { } { function _mintERC2309(address to, uint256 quantity) internal virtual { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1); _packedOwnerships[startTokenId] = _packOwnershipData( to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0) ); emit ConsecutiveTransfer( startTokenId, startTokenId + quantity - 1, address(0), to ); _currentIndex = startTokenId + quantity; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _mintERC2309(address to, uint256 quantity) internal virtual { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1); _packedOwnerships[startTokenId] = _packOwnershipData( to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0) ); emit ConsecutiveTransfer( startTokenId, startTokenId + quantity - 1, address(0), to ); _currentIndex = startTokenId + quantity; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _safeMint( address to, uint256 quantity, bytes memory _data ) internal virtual { _mint(to, quantity); unchecked { if (to.code.length != 0) { uint256 end = _currentIndex; uint256 index = end - quantity; do { if ( !_checkContractOnERC721Received( address(0), to, index++, _data ) ) { revert TransferToNonERC721ReceiverImplementer(); } } while (index < end); } } } function _safeMint( address to, uint256 quantity, bytes memory _data ) internal virtual { _mint(to, quantity); unchecked { if (to.code.length != 0) { uint256 end = _currentIndex; uint256 index = end - quantity; do { if ( !_checkContractOnERC721Received( address(0), to, index++, _data ) ) { revert TransferToNonERC721ReceiverImplementer(); } } while (index < end); } } } function _safeMint( address to, uint256 quantity, bytes memory _data ) internal virtual { _mint(to, quantity); unchecked { if (to.code.length != 0) { uint256 end = _currentIndex; uint256 index = end - quantity; do { if ( !_checkContractOnERC721Received( address(0), to, index++, _data ) ) { revert TransferToNonERC721ReceiverImplementer(); } } while (index < end); } } } function _safeMint( address to, uint256 quantity, bytes memory _data ) internal virtual { _mint(to, quantity); unchecked { if (to.code.length != 0) { uint256 end = _currentIndex; uint256 index = end - quantity; do { if ( !_checkContractOnERC721Received( address(0), to, index++, _data ) ) { revert TransferToNonERC721ReceiverImplementer(); } } while (index < end); } } } function _safeMint( address to, uint256 quantity, bytes memory _data ) internal virtual { _mint(to, quantity); unchecked { if (to.code.length != 0) { uint256 end = _currentIndex; uint256 index = end - quantity; do { if ( !_checkContractOnERC721Received( address(0), to, index++, _data ) ) { revert TransferToNonERC721ReceiverImplementer(); } } while (index < end); } } } if (_currentIndex != end) revert(); function _safeMint(address to, uint256 quantity) internal virtual { _safeMint(to, quantity, ""); } function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); address from = address(uint160(prevOwnershipPacked)); ( uint256 approvedAddressSlot, address approvedAddress ) = _getApprovedSlotAndAddress(tokenId); if (approvalCheck) { if ( !_isSenderApprovedOrOwner( approvedAddress, from, _msgSenderERC721A() ) ) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); assembly { if approvedAddress { sstore(approvedAddressSlot, 0) } } unchecked { _packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1; _packedOwnerships[tokenId] = _packOwnershipData( from, (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked) ); if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; if (_packedOwnerships[nextTokenId] == 0) { if (nextTokenId != _currentIndex) { _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); address from = address(uint160(prevOwnershipPacked)); ( uint256 approvedAddressSlot, address approvedAddress ) = _getApprovedSlotAndAddress(tokenId); if (approvalCheck) { if ( !_isSenderApprovedOrOwner( approvedAddress, from, _msgSenderERC721A() ) ) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); assembly { if approvedAddress { sstore(approvedAddressSlot, 0) } } unchecked { _packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1; _packedOwnerships[tokenId] = _packOwnershipData( from, (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked) ); if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; if (_packedOwnerships[nextTokenId] == 0) { if (nextTokenId != _currentIndex) { _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); address from = address(uint160(prevOwnershipPacked)); ( uint256 approvedAddressSlot, address approvedAddress ) = _getApprovedSlotAndAddress(tokenId); if (approvalCheck) { if ( !_isSenderApprovedOrOwner( approvedAddress, from, _msgSenderERC721A() ) ) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); assembly { if approvedAddress { sstore(approvedAddressSlot, 0) } } unchecked { _packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1; _packedOwnerships[tokenId] = _packOwnershipData( from, (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked) ); if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; if (_packedOwnerships[nextTokenId] == 0) { if (nextTokenId != _currentIndex) { _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); address from = address(uint160(prevOwnershipPacked)); ( uint256 approvedAddressSlot, address approvedAddress ) = _getApprovedSlotAndAddress(tokenId); if (approvalCheck) { if ( !_isSenderApprovedOrOwner( approvedAddress, from, _msgSenderERC721A() ) ) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); assembly { if approvedAddress { sstore(approvedAddressSlot, 0) } } unchecked { _packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1; _packedOwnerships[tokenId] = _packOwnershipData( from, (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked) ); if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; if (_packedOwnerships[nextTokenId] == 0) { if (nextTokenId != _currentIndex) { _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); address from = address(uint160(prevOwnershipPacked)); ( uint256 approvedAddressSlot, address approvedAddress ) = _getApprovedSlotAndAddress(tokenId); if (approvalCheck) { if ( !_isSenderApprovedOrOwner( approvedAddress, from, _msgSenderERC721A() ) ) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); assembly { if approvedAddress { sstore(approvedAddressSlot, 0) } } unchecked { _packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1; _packedOwnerships[tokenId] = _packOwnershipData( from, (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked) ); if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; if (_packedOwnerships[nextTokenId] == 0) { if (nextTokenId != _currentIndex) { _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); address from = address(uint160(prevOwnershipPacked)); ( uint256 approvedAddressSlot, address approvedAddress ) = _getApprovedSlotAndAddress(tokenId); if (approvalCheck) { if ( !_isSenderApprovedOrOwner( approvedAddress, from, _msgSenderERC721A() ) ) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); assembly { if approvedAddress { sstore(approvedAddressSlot, 0) } } unchecked { _packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1; _packedOwnerships[tokenId] = _packOwnershipData( from, (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked) ); if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; if (_packedOwnerships[nextTokenId] == 0) { if (nextTokenId != _currentIndex) { _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); address from = address(uint160(prevOwnershipPacked)); ( uint256 approvedAddressSlot, address approvedAddress ) = _getApprovedSlotAndAddress(tokenId); if (approvalCheck) { if ( !_isSenderApprovedOrOwner( approvedAddress, from, _msgSenderERC721A() ) ) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); assembly { if approvedAddress { sstore(approvedAddressSlot, 0) } } unchecked { _packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1; _packedOwnerships[tokenId] = _packOwnershipData( from, (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked) ); if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; if (_packedOwnerships[nextTokenId] == 0) { if (nextTokenId != _currentIndex) { _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); address from = address(uint160(prevOwnershipPacked)); ( uint256 approvedAddressSlot, address approvedAddress ) = _getApprovedSlotAndAddress(tokenId); if (approvalCheck) { if ( !_isSenderApprovedOrOwner( approvedAddress, from, _msgSenderERC721A() ) ) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); assembly { if approvedAddress { sstore(approvedAddressSlot, 0) } } unchecked { _packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1; _packedOwnerships[tokenId] = _packOwnershipData( from, (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked) ); if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; if (_packedOwnerships[nextTokenId] == 0) { if (nextTokenId != _currentIndex) { _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); address from = address(uint160(prevOwnershipPacked)); ( uint256 approvedAddressSlot, address approvedAddress ) = _getApprovedSlotAndAddress(tokenId); if (approvalCheck) { if ( !_isSenderApprovedOrOwner( approvedAddress, from, _msgSenderERC721A() ) ) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); assembly { if approvedAddress { sstore(approvedAddressSlot, 0) } } unchecked { _packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1; _packedOwnerships[tokenId] = _packOwnershipData( from, (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked) ); if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; if (_packedOwnerships[nextTokenId] == 0) { if (nextTokenId != _currentIndex) { _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual { uint256 packed = _packedOwnerships[index]; if (packed == 0) revert OwnershipNotInitializedForExtraData(); uint256 extraDataCasted; assembly { extraDataCasted := extraData } packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA); _packedOwnerships[index] = packed; } function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual { uint256 packed = _packedOwnerships[index]; if (packed == 0) revert OwnershipNotInitializedForExtraData(); uint256 extraDataCasted; assembly { extraDataCasted := extraData } packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA); _packedOwnerships[index] = packed; } ) internal view virtual returns (uint24) {} function _extraData( address from, address to, uint24 previousExtraData function _nextExtraData( address from, address to, uint256 prevOwnershipPacked ) private view returns (uint256) { uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA); return uint256(_extraData(from, to, extraData)) << _BITPOS_EXTRA_DATA; } function _msgSenderERC721A() internal view virtual returns (address) { return msg.sender; } function _toString(uint256 value) internal pure virtual returns (string memory str) { assembly { let m := add(mload(0x40), 0xa0) mstore(0x40, m) str := sub(m, 0x20) mstore(str, 0) let end := str str := sub(str, 1) mstore8(str, add(48, mod(temp, 10))) temp := div(temp, 10) } let length := sub(end, str) } function _toString(uint256 value) internal pure virtual returns (string memory str) { assembly { let m := add(mload(0x40), 0xa0) mstore(0x40, m) str := sub(m, 0x20) mstore(str, 0) let end := str str := sub(str, 1) mstore8(str, add(48, mod(temp, 10))) temp := div(temp, 10) } let length := sub(end, str) } for { let temp := value } 1 {} { if iszero(temp) { break } str := sub(str, 0x20) mstore(str, length) }
4,656,870
[ 1, 654, 39, 27, 5340, 37, 3858, 17, 42, 20651, 1523, 3155, 8263, 16, 6508, 326, 6912, 2710, 18, 19615, 1235, 364, 2612, 16189, 4982, 2581, 312, 28142, 18, 3155, 7115, 854, 312, 474, 329, 316, 21210, 1353, 261, 73, 18, 75, 18, 374, 16, 404, 16, 576, 16, 890, 16, 1372, 13, 5023, 628, 1375, 67, 1937, 1345, 548, 1435, 8338, 4725, 379, 573, 30, 300, 1922, 3410, 2780, 1240, 1898, 2353, 576, 1105, 300, 404, 261, 1896, 460, 434, 2254, 1105, 13, 434, 14467, 18, 300, 1021, 4207, 1147, 1599, 2780, 9943, 576, 5034, 300, 404, 261, 1896, 460, 434, 2254, 5034, 2934, 19, 605, 25567, 364, 279, 1375, 413, 21985, 17, 481, 68, 7934, 261, 4528, 30, 6662, 18, 832, 19, 343, 481, 89, 17, 80, 5113, 19, 654, 39, 27, 5340, 37, 19, 13469, 19, 23, 1105, 2934, 2, 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, 1, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 27, 5340, 37, 353, 467, 654, 39, 27, 5340, 37, 288, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 203, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 3903, 1476, 1135, 261, 6430, 1769, 203, 203, 203, 565, 871, 12279, 12, 203, 3639, 1758, 8808, 628, 16, 203, 3639, 1758, 8808, 358, 16, 203, 3639, 2254, 5034, 8808, 1147, 548, 203, 565, 11272, 203, 203, 565, 871, 1716, 685, 1125, 12, 203, 3639, 1758, 8808, 3410, 16, 203, 3639, 1758, 8808, 20412, 16, 203, 3639, 2254, 5034, 8808, 1147, 548, 203, 565, 11272, 203, 203, 565, 871, 1716, 685, 1125, 1290, 1595, 12, 203, 3639, 1758, 8808, 3410, 16, 203, 3639, 1758, 8808, 3726, 16, 203, 3639, 1426, 20412, 203, 565, 11272, 203, 203, 565, 445, 11013, 951, 12, 2867, 3410, 13, 3903, 1476, 1135, 261, 11890, 5034, 11013, 1769, 203, 203, 565, 445, 3410, 951, 12, 11890, 5034, 1147, 548, 13, 3903, 1476, 1135, 261, 2867, 3410, 1769, 203, 203, 565, 445, 4183, 5912, 1265, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 1731, 745, 892, 501, 203, 565, 262, 3903, 8843, 429, 31, 203, 203, 565, 445, 4183, 5912, 1265, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 262, 3903, 8843, 429, 31, 203, 203, 565, 445, 7412, 1265, 12, 203, 3639, 1758, 628, 16, 203, 2 ]