file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
./partial_match/1/0x1Fb94559BAe9D113b53bd5E0f55782a250A340a9/sources/Orangutan.sol
SPDX-License-Identifier: UNLICENSED
abstract contract Context { Orangutan 🦧 function _msgSender() internal view virtual returns (address) { return msg.sender; } }
9,325,822
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 5019, 6065, 1157, 18204, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 1772, 288, 203, 1162, 539, 322, 304, 225, 177, 258, 104, 105, 203, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 1476, 5024, 1135, 261, 2867, 13, 288, 203, 3639, 327, 1234, 18, 15330, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x157ED4Dcd657d17Aa2c3dCA31f30043e8Eff4f2E/sources/contracts/base/StrategyBase.sol
instance of manager contract
IStrategyManager public override manager;
3,598,218
[ 1, 1336, 434, 3301, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 467, 4525, 1318, 1071, 3849, 3301, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xB40E270C98d2F3D966A03DA5F56C034303645FA0/sources/contracts/Acrocalypse.sol
* @notice It allows the admin to set the contract address of V1 NFT @dev Only callable by owner./
function setAcrocalypseV1Address(address newV1Address) external onlyOwner { if (address(newV1Address) != address(0)) { acrocalypseV1Address = newV1Address; } }
4,915,838
[ 1, 7193, 5360, 326, 3981, 358, 444, 326, 6835, 1758, 434, 776, 21, 423, 4464, 225, 5098, 4140, 635, 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, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 9988, 30101, 879, 307, 58, 21, 1887, 12, 2867, 394, 58, 21, 1887, 13, 3903, 1338, 5541, 288, 203, 3639, 309, 261, 2867, 12, 2704, 58, 21, 1887, 13, 480, 1758, 12, 20, 3719, 288, 203, 5411, 1721, 30101, 879, 307, 58, 21, 1887, 273, 394, 58, 21, 1887, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xe2fD02741bcbf34723320Fb80b77AB4Ff82D7979/sources/BCEToken.sol
assert(b > 0); Solidity automatically throws when dividing by 0 assert(a == b * c + a % b); There is no case in which this doesn't hold
function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; }
2,676,173
[ 1, 11231, 12, 70, 405, 374, 1769, 225, 348, 7953, 560, 6635, 1216, 1347, 3739, 10415, 635, 374, 1815, 12, 69, 422, 324, 225, 276, 397, 279, 738, 324, 1769, 225, 6149, 353, 1158, 648, 316, 1492, 333, 3302, 1404, 6887, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3739, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 342, 324, 31, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 21281, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/Address.sol"; import "../TokenPaymaster.sol"; import "./ProxyFactory.sol"; contract ProxyDeployingPaymaster is TokenPaymaster { using Address for address; string public override versionPaymaster = "2.2.0+opengsn.proxydeploying.ipaymaster"; ProxyFactory public proxyFactory; constructor(IUniswap[] memory _uniswaps, ProxyFactory _proxyFactory) TokenPaymaster(_uniswaps) { proxyFactory = _proxyFactory; } function getPayer(GsnTypes.RelayRequest calldata relayRequest) public override virtual view returns (address) { // TODO: if (rr.paymasterData != '') return address(rr.paymasterData) // this is to support pre-existing proxies/proxies with changed owner return proxyFactory.calculateAddress(relayRequest.request.from); } function preRelayedCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external override virtual returns (bytes memory, bool revertOnRecipientRevert) { (relayRequest, signature, approvalData, maxPossibleGas); (IERC20 token, IUniswap uniswap) = _getToken(relayRequest.relayData.paymasterData); (address payer, uint256 tokenPrecharge) = _calculatePreCharge(token, uniswap, relayRequest, maxPossibleGas); if (!payer.isContract()) { deployProxy(relayRequest.request.from); } token.transferFrom(payer, address(this), tokenPrecharge); //solhint-disable-next-line uniswap.tokenToEthSwapOutput(relayRequest.request.value, uint256(-1), block.timestamp+60*15); payable(relayRequest.relayData.forwarder).transfer(relayRequest.request.value); return (abi.encode(payer, relayRequest.request.from, tokenPrecharge, relayRequest.request.value, relayRequest.relayData.forwarder, token, uniswap), false); } function deployProxy(address owner) public returns (ProxyIdentity) { ProxyIdentity proxy = proxyFactory.deployProxy(owner); proxy.initialize(address(trustedForwarder), tokens); return proxy; } function postRelayedCall( bytes calldata context, bool, uint256 gasUseWithoutPost, GsnTypes.RelayData calldata relayData ) external override virtual { (address payer,, uint256 tokenPrecharge, uint256 valueRequested,,IERC20 token, IUniswap uniswap) = abi.decode(context, (address, address, uint256, uint256, address, IERC20, IUniswap)); _postRelayedCallInternal(payer, tokenPrecharge, valueRequested, gasUseWithoutPost, relayData, token, uniswap); } // TODO: calculate precise values for these params uint256 constant private PRE_RELAYED_CALL_GAS_LIMIT_OVERRIDE = 2000000; uint256 constant public PAYMASTER_ACCEPTANCE_BUDGET_OVERRIDE = PRE_RELAYED_CALL_GAS_LIMIT_OVERRIDE + FORWARDER_HUB_OVERHEAD; function getGasAndDataLimits() public override pure returns ( GasAndDataLimits memory limits ) { return GasAndDataLimits( PAYMASTER_ACCEPTANCE_BUDGET_OVERRIDE, PRE_RELAYED_CALL_GAS_LIMIT_OVERRIDE, POST_RELAYED_CALL_GAS_LIMIT, CALLDATA_SIZE_LIMIT ); } }
solhint-disable-next-line
uniswap.tokenToEthSwapOutput(relayRequest.request.value, uint256(-1), block.timestamp+60*15);
6,434,500
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 640, 291, 91, 438, 18, 2316, 774, 41, 451, 12521, 1447, 12, 2878, 528, 691, 18, 2293, 18, 1132, 16, 2254, 5034, 19236, 21, 3631, 1203, 18, 5508, 15, 4848, 14, 3600, 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 ]
./full_match/1/0xE45Ca57cdc67EEA9F60c2190402630944f9303b1/sources/AVENGERS/utils/Withdrawable.sol
* @dev Withdraw asset. @param _assetAddress Asset to be withdrawn./
function withdraw(address _assetAddress) public onlyOwner { uint assetBalance; if (_assetAddress == ETHER) { assetBalance = self.balance; msg.sender.transfer(assetBalance); assetBalance = ERC20(_assetAddress).balanceOf(address(this)); ERC20(_assetAddress).safeTransfer(msg.sender, assetBalance); } emit LogWithdraw(msg.sender, _assetAddress, assetBalance); }
2,937,222
[ 1, 1190, 9446, 3310, 18, 225, 389, 9406, 1887, 10494, 358, 506, 598, 9446, 82, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 2867, 389, 9406, 1887, 13, 1071, 1338, 5541, 288, 203, 3639, 2254, 3310, 13937, 31, 203, 3639, 309, 261, 67, 9406, 1887, 422, 512, 19905, 13, 288, 203, 5411, 3310, 13937, 273, 365, 18, 12296, 31, 203, 5411, 1234, 18, 15330, 18, 13866, 12, 9406, 13937, 1769, 203, 5411, 3310, 13937, 273, 4232, 39, 3462, 24899, 9406, 1887, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 5411, 4232, 39, 3462, 24899, 9406, 1887, 2934, 4626, 5912, 12, 3576, 18, 15330, 16, 3310, 13937, 1769, 203, 3639, 289, 203, 3639, 3626, 1827, 1190, 9446, 12, 3576, 18, 15330, 16, 389, 9406, 1887, 16, 3310, 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 ]
./partial_match/42/0x8fe80F7CA77dAA68b059f8B3e29e1c5d962f01E7/sources/Uni.sol
* @notice Mint new tokens @param dst The address of the destination account @param rawAmount The number of tokens to be minted/ record the mint mint the amount transfer the amount to the recipient move delegates
function mint(address dst, uint256 rawAmount) external { require(msg.sender == minter, "Uni::mint: only the minter can mint"); require( block.timestamp >= mintingAllowedAfter, "Uni::mint: minting not allowed yet" ); require( dst != address(0), "Uni::mint: cannot transfer to the zero address" ); mintingAllowedAfter = SafeMath.add( block.timestamp, minimumTimeBetweenMints ); uint96 amount = safe96(rawAmount, "Uni::mint: amount exceeds 96 bits"); require( amount <= SafeMath.div(SafeMath.mul(totalSupply, mintCap), 100), "Uni::mint: exceeded mint cap" ); totalSupply = safe96( SafeMath.add(totalSupply, amount), "Uni::mint: totalSupply exceeds 96 bits" ); balances[dst] = add96( balances[dst], amount, "Uni::mint: transfer amount overflows" ); emit Transfer(address(0), dst, amount); _moveDelegates(address(0), delegates[dst], amount); }
8,844,714
[ 1, 49, 474, 394, 2430, 225, 3046, 1021, 1758, 434, 326, 2929, 2236, 225, 1831, 6275, 1021, 1300, 434, 2430, 358, 506, 312, 474, 329, 19, 1409, 326, 312, 474, 312, 474, 326, 3844, 7412, 326, 3844, 358, 326, 8027, 3635, 22310, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 2867, 3046, 16, 2254, 5034, 1831, 6275, 13, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 1131, 387, 16, 315, 984, 77, 2866, 81, 474, 30, 1338, 326, 1131, 387, 848, 312, 474, 8863, 203, 3639, 2583, 12, 203, 5411, 1203, 18, 5508, 1545, 312, 474, 310, 5042, 4436, 16, 203, 5411, 315, 984, 77, 2866, 81, 474, 30, 312, 474, 310, 486, 2935, 4671, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 3046, 480, 1758, 12, 20, 3631, 203, 5411, 315, 984, 77, 2866, 81, 474, 30, 2780, 7412, 358, 326, 3634, 1758, 6, 203, 3639, 11272, 203, 203, 3639, 312, 474, 310, 5042, 4436, 273, 14060, 10477, 18, 1289, 12, 203, 5411, 1203, 18, 5508, 16, 203, 5411, 5224, 950, 11831, 49, 28142, 203, 3639, 11272, 203, 203, 3639, 2254, 10525, 3844, 273, 4183, 10525, 12, 1899, 6275, 16, 315, 984, 77, 2866, 81, 474, 30, 3844, 14399, 19332, 4125, 8863, 203, 3639, 2583, 12, 203, 5411, 3844, 1648, 14060, 10477, 18, 2892, 12, 9890, 10477, 18, 16411, 12, 4963, 3088, 1283, 16, 312, 474, 4664, 3631, 2130, 3631, 203, 5411, 315, 984, 77, 2866, 81, 474, 30, 12428, 312, 474, 3523, 6, 203, 3639, 11272, 203, 3639, 2078, 3088, 1283, 273, 4183, 10525, 12, 203, 5411, 14060, 10477, 18, 1289, 12, 4963, 3088, 1283, 16, 3844, 3631, 203, 5411, 315, 984, 77, 2866, 81, 474, 30, 2078, 3088, 1283, 14399, 19332, 4125, 6, 203, 3639, 11272, 203, 203, 3639, 324, 26488, 63, 2 ]
pragma solidity ^0.4.23; import "./erc721.sol"; import "./SafeMath.sol"; import "./Random.sol"; import "./Database.sol"; contract WarriorBase is ERC721 { using SafeMath for uint256; using SafeMath for uint64; Random private randomContract; Database private databaseContract; /// @dev This emits when the token ownership changed event Transfer(address indexed from, address indexed to, uint256 tokenId); /// @dev This emits when user charged his warrior event NewFund(uint _value); /// @dev This emits when a new warrior is created(adopted) by user event CreateWarrior(address _owner, uint newWarriorId, uint _val); event Consequence(uint winnerId, uint loserId, address winnerAddr, address loserAddr, uint valToTransfer, uint ceToTransfer, uint winnerTitle, uint loserTitle); event KillWarrior(uint _id, address owner, uint tokenToOwnerIndex); event AddPrestige(uint _id, uint winningPrestige, uint title); event SubPrestige(uint _id, uint winningPrestige); event SetCoachCoolDownTime(uint coachId, uint attackId, uint curTime); event SwitchRetirementStatus(uint tokenId, uint retirementStatus); mapping (uint => address) internal tokenApprovals; mapping (uint => address) internal tokenIndexToOwner; mapping (address => uint) internal ownerToTokenCount; mapping (address => uint[]) internal ownerToTokenArray; /// the id of the given token in owner's token list. mapping (uint => uint) internal tokenIndexToOwnerIndex; string public constant name = "SpartaxWarrior"; string public constant symbol = "SW"; uint constant greenhandProtection = 30 minutes; uint constant miniValue = 10 ** 16; struct Warrior { uint val; /// 0 uint winCount; /// 1 uint lossCount; /// 2 uint combo; /// 3 uint title; /// 4 title: default--0 primary coach--7 intermediate coach--8 advanced coach--9 master--10 uint prestige; /// 5 uint ce; /// 6 comat effectiveness uint createTime; /// 7 uint destroyTime; /// 8 uint lastAttackCoach1; /// 9 uint lastAttackCoach2; /// 10 uint lastAttackCoach3; /// 11 uint lastAttackCoach4; /// 12 uint isRetired; /// 13 } Warrior[] private WarriorList; uint private ActiveWarriorListLength; /// @dev check the given tokenId is in the tokenList and its owner is not null. modifier tokenExist(uint256 _id) { require(_id >= 1 && _id <= WarriorList.length); require(tokenIndexToOwner[_id] != address(0)); _; } /// @dev construction method. constructor( address _randomContract, address _databaseContract) public{ randomContract = Random(_randomContract); databaseContract = Database(_databaseContract); /// warrior list contains the 4 coaches at the very beginning ActiveWarriorListLength = 4; /// drop index 0 WarriorList.length += 1; /// primary coach : value 0.01ether comat effectiveness 10 title 7 uint newWarriorId = WarriorList.length; WarriorList.length += 1; Warrior storage war = WarriorList[newWarriorId]; war.val = miniValue; /// 0.01 ether in Wei war.winCount = 0; war.lossCount = 0; war.combo = 0; war.title = 7; war.prestige = 0; war.ce = 10; _transfer(0, msg.sender, newWarriorId); databaseContract.addAccountEth(msg.sender, war.val); /// primary coach : value 0.01ether comat effectiveness 10 title 8 newWarriorId = WarriorList.length; WarriorList.length += 1; war = WarriorList[newWarriorId]; war.val = miniValue * 5; /// 0.05 ether in Wei war.winCount = 0; war.lossCount = 0; war.combo = 0; war.title = 8; war.prestige = 0; war.ce = 50; _transfer(0, msg.sender, newWarriorId); databaseContract.addAccountEth(msg.sender, war.val); /// primary coach : value 0.01ether comat effectiveness 10 title 9 newWarriorId = WarriorList.length; WarriorList.length += 1; war = WarriorList[newWarriorId]; war.val = miniValue * 10; /// 0.1 ether in Wei war.winCount = 0; war.lossCount = 0; war.combo = 0; war.title = 9; war.prestige = 0; war.ce = 100; _transfer(0, msg.sender, newWarriorId); databaseContract.addAccountEth(msg.sender, war.val); /// primary coach : value 0.01ether comat effectiveness 10 title 10 newWarriorId = WarriorList.length; WarriorList.length += 1; war = WarriorList[newWarriorId]; war.val = miniValue * 50; /// 0.5 ether in Wei; war.winCount = 0; war.lossCount = 0; war.combo = 0; war.title = 10; war.prestige = 0; war.ce = 500; _transfer(0, msg.sender, newWarriorId); databaseContract.addAccountEth(msg.sender, war.val); } /// @dev adopt a level 1 warrior (0.01 eth) function adoptLvOne() external payable returns(uint256) { require(msg.sender != address(0)); require(msg.value >= 0.01 ether); uint newWarriorId = WarriorList.length; WarriorList.length += 1; Warrior storage war = WarriorList[newWarriorId]; war.val = msg.value; war.winCount = 0; war.lossCount = 0; war.combo = 0; war.title = 0; war.prestige = 0; war.ce = 10; war.createTime = now; war.destroyTime = 0; war.lastAttackCoach1 = 0; war.lastAttackCoach2 = 0; war.lastAttackCoach3 = 0; war.lastAttackCoach4 = 0; _transfer(0,msg.sender, newWarriorId); databaseContract.addAccountEth(msg.sender, msg.value); ActiveWarriorListLength = ActiveWarriorListLength.add(1); CreateWarrior(msg.sender,newWarriorId, msg.value); return newWarriorId; } /// @dev adopt a level 2 warrior (0.05 eth) function adoptLvTwo() external payable returns(uint256) { require(msg.sender != address(0)); require(msg.value >= 0.05 ether); uint newWarriorId = WarriorList.length; WarriorList.length += 1; Warrior storage war = WarriorList[newWarriorId]; war.val = msg.value; war.winCount = 0; war.lossCount = 0; war.combo = 0; war.title = 0; war.prestige = 0; war.ce = 50; war.createTime = now; war.destroyTime = 0; war.lastAttackCoach1 = 0; war.lastAttackCoach2 = 0; war.lastAttackCoach3 = 0; war.lastAttackCoach4 = 0; _transfer(0,msg.sender, newWarriorId); databaseContract.addAccountEth(msg.sender, msg.value); ActiveWarriorListLength = ActiveWarriorListLength.add(1); CreateWarrior(msg.sender, newWarriorId, msg.value); return newWarriorId; } /// @dev adopt a level 3 warrior (0.1 eth) function adoptLvThree() external payable returns(uint256) { require(msg.sender != address(0)); require(msg.value >= 0.1 ether); uint newWarriorId = WarriorList.length; WarriorList.length += 1; Warrior storage war = WarriorList[newWarriorId]; war.val = msg.value; war.winCount = 0; war.lossCount = 0; war.combo = 0; war.title = 0; war.prestige = 0; war.ce = 100; war.createTime = now; war.destroyTime = 0; war.lastAttackCoach1 = 0; war.lastAttackCoach2 = 0; war.lastAttackCoach3 = 0; war.lastAttackCoach4 = 0; _transfer(0,msg.sender, newWarriorId); databaseContract.addAccountEth(msg.sender, msg.value); ActiveWarriorListLength = ActiveWarriorListLength.add(1); CreateWarrior(msg.sender, newWarriorId, msg.value); return newWarriorId; } /// @dev adopt a level 4 warrior (0.5 eth) function adoptLvFour() external payable returns(uint256) { require(msg.sender != address(0)); require(msg.value >= 0.5 ether); uint newWarriorId = WarriorList.length; WarriorList.length += 1; Warrior storage war = WarriorList[newWarriorId]; war.val = msg.value; war.winCount = 0; war.lossCount = 0; war.combo = 0; war.title = 0; war.prestige = 0; war.ce = 500; war.createTime = now; war.destroyTime = 0; war.lastAttackCoach1 = 0; war.lastAttackCoach2 = 0; war.lastAttackCoach3 = 0; war.lastAttackCoach4 = 0; _transfer(0,msg.sender, newWarriorId); databaseContract.addAccountEth(msg.sender, msg.value); ActiveWarriorListLength = ActiveWarriorListLength.add(1); CreateWarrior(msg.sender, newWarriorId, msg.value); return newWarriorId; } function setRandomAddr(address _randomContract) external { randomContract = Random(_randomContract); } /// @dev return the total number of tokens in the game function getTokenNum() external view returns(uint) { return WarriorList.length - 1; } /// @dev return the owner address of the token(warrior) function getTokenOwner(uint _id) external view tokenExist(_id) returns(address) { require(tokenIndexToOwner[_id] != address(0)); return tokenIndexToOwner[_id]; } /// @dev Ruturn token details by tokenId function getToken(uint256 _id) external view tokenExist(_id) returns (uint[14] datas) { Warrior storage warrior = WarriorList[_id]; datas[0] = warrior.val; datas[1] = warrior.winCount; datas[2] = warrior.lossCount; datas[3] = warrior.combo; datas[4] = warrior.title; datas[5] = warrior.prestige; datas[6] = warrior.ce; datas[7] = warrior.createTime; datas[8] = warrior.destroyTime; datas[9] = warrior.lastAttackCoach1; datas[10] = warrior.lastAttackCoach2; datas[11] = warrior.lastAttackCoach3; datas[12] = warrior.lastAttackCoach4; datas[13] = warrior.isRetired; } /// @dev return all tokens owned by owner function getOwnTokens(address _owner) external view returns(uint256[] tokens){ require(_owner != address(0)); uint256[] memory tokenArray = ownerToTokenArray[_owner]; uint256 length = (uint256)(tokenArray.length); tokens = new uint256[](length); for (uint256 i = 0; i < length; ++i) { tokens[i] = tokenArray[i]; } } /// @dev return all tokens not belong to owner function getEnemyTokens(address _owner) external view returns(uint[] tokens) { require(_owner != address(0)); uint length = WarriorList.length - 1 - ownerToTokenArray[_owner].length; tokens = new uint256[](length); uint index = 0; for (uint256 i = 1; i < WarriorList.length; ++i) { if (tokenIndexToOwner[i] != _owner && tokenIndexToOwner[i] != address(0)) { tokens[index] = i; index += 1; } } } /// @dev return active warrior numbers for now function getActiveWarriorListLength() external view returns(uint) { return ActiveWarriorListLength; } /// @dev set the timestamp of attacking each coach, you cannot attack them twice within an hour function setCoachCoolDownTime(uint coachId, uint attackId) external tokenExist(attackId){ Warrior storage attacker = WarriorList[attackId]; if (coachId == 1) attacker.lastAttackCoach1 = uint(now); else if (coachId == 2) attacker.lastAttackCoach2 = uint(now); else if (coachId == 3) attacker.lastAttackCoach3 = uint(now); else if (coachId == 4) attacker.lastAttackCoach4 = uint(now); emit SetCoachCoolDownTime(coachId, attackId, now); } /// @dev calculate the consequece of a finished battle function consequence( uint winnerId, uint loserId, address winnerAddr, address loserAddr) external tokenExist(winnerId) tokenExist(loserId) returns(uint){ require(tokenIndexToOwner[winnerId] == winnerAddr); require(tokenIndexToOwner[loserId] == loserAddr); uint valToTransfer; uint ceToTransfer; if (WarriorList[loserId].ce <= 2) { valToTransfer = WarriorList[loserId].val; ceToTransfer = WarriorList[loserId].ce; } else { valToTransfer = WarriorList[loserId].val.div(2); ceToTransfer = WarriorList[loserId].ce.div(2); } Warrior storage winner = WarriorList[winnerId]; winner.winCount = winner.winCount.add(1); winner.combo = winner.combo.add(1); Warrior storage loser = WarriorList[loserId]; loser.lossCount = loser.lossCount.add(1); loser.combo = 0; if (loser.title < 7 || loser.title > 10) /// if the loser is a coach, his value shall not be reduced. { loser.val = loser.val.sub(valToTransfer); loser.title = 0; loser.ce = loser.ce.sub(ceToTransfer); } if (winner.title < 7 || winner.title > 10) { winner.val = winner.val.add(valToTransfer); winner.ce = winner.ce.add(ceToTransfer); if (winner.title < 7) { if (winner.combo < 1) winner.title = 0; else if (winner.combo < 2) winner.title = 1; else if (winner.combo < 4) winner.title = 2; else if (winner.combo < 8) winner.title = 3; else if (winner.combo < 12) winner.title = 4; else if (winner.combo < 20) winner.title = 5; else winner.title = 6; } } emit Consequence(winnerId,loserId, winnerAddr, loserAddr, valToTransfer, ceToTransfer, winner.title, loser.title); return valToTransfer; } function addPrestige(uint tokenId, uint prestigeAmt) tokenExist(tokenId) external { WarriorList[tokenId].prestige = WarriorList[tokenId].prestige.add(prestigeAmt); if ( WarriorList[tokenId].prestige >= 30 ) WarriorList[tokenId].title = 11; if ( WarriorList[tokenId].prestige >= 40 ) WarriorList[tokenId].title = 12; emit AddPrestige(tokenId, prestigeAmt, WarriorList[tokenId].title); } function subPrestige(uint tokenId, uint prestigeAmt) tokenExist(tokenId) external { WarriorList[tokenId].prestige = WarriorList[tokenId].prestige.sub(prestigeAmt); WarriorList[tokenId].title = 0; if ( WarriorList[tokenId].prestige >= 30 ) WarriorList[tokenId].title = 11; if ( WarriorList[tokenId].prestige >= 40 ) WarriorList[tokenId].title = 12; emit SubPrestige(tokenId, prestigeAmt); } function switchRetirementStatus(uint tokenId) tokenExist(tokenId) external { require(WarriorList[tokenId].title == 12); WarriorList[tokenId].isRetired = 1 - WarriorList[tokenId].isRetired; emit SwitchRetirementStatus(tokenId, WarriorList[tokenId].isRetired); } /// @dev "feed" the token with msg.value function feedWarrior(uint _id) public tokenExist(_id) payable returns(uint) { require(tokenIndexToOwner[_id] == msg.sender); WarriorList[_id].val = WarriorList[_id].val.add(msg.value); databaseContract.addAccountEth(msg.sender, msg.value); NewFund(this.balance); return this.balance; } function _removeFromList(uint _id, address _owner) private { for (uint i = 0; i < ownerToTokenArray[_owner].length; i++) { if (ownerToTokenArray[_owner][i] == _id) { for (uint j = i; j < ownerToTokenArray[_owner].length - 1; j++) ownerToTokenArray[_owner][j] = ownerToTokenArray[_owner][j + 1]; ownerToTokenArray[_owner].length -= 1; return; } } } /// @dev "kill" the token and sent its ether value back to owner's wallet function killWarrior(uint _id) external tokenExist(_id) returns(uint) { require(tokenIndexToOwner[_id] == msg.sender); uint valToTransfer = WarriorList[_id].val; uint tokenToOwnerIndex = tokenIndexToOwnerIndex[_id]; _removeFromList(_id, msg.sender); tokenIndexToOwner[_id] = address(0); ownerToTokenCount[msg.sender] = ownerToTokenCount[msg.sender].sub(1); tokenIndexToOwnerIndex[_id] = 0; databaseContract.reduceAccountEth(msg.sender,valToTransfer); ActiveWarriorListLength = ActiveWarriorListLength.sub(1); msg.sender.transfer(valToTransfer); emit KillWarrior(_id, msg.sender, tokenToOwnerIndex); return tokenToOwnerIndex; } function addFund() public payable returns(uint) { require(msg.value > 0); emit NewFund(this.balance); return this.balance; } function getBalance() external returns(uint){ return this.balance; } function _transfer(address _from, address _to, uint256 _tokenId) internal { if (_from != address(0)){ uint256 indexFrom = tokenIndexToOwnerIndex[_tokenId]; uint256[] storage tokenArray = ownerToTokenArray[_from]; require(tokenArray[indexFrom] == _tokenId); if (indexFrom != tokenArray.length - 1){ uint256 lastTokenId = tokenArray[tokenArray.length - 1]; tokenArray[indexFrom] = lastTokenId; tokenIndexToOwnerIndex[lastTokenId] = indexFrom; } tokenArray.length.sub(1); } /// Transfer the token to address '_to' tokenIndexToOwner[_tokenId] = _to; if (ownerToTokenArray[_to].length == 0){ ownerToTokenCount[_to] = 0; } ownerToTokenArray[_to].push(_tokenId); ownerToTokenCount[_to] = ownerToTokenCount[_to].add(1); tokenIndexToOwnerIndex[_tokenId] = (uint256)(ownerToTokenArray[_to].length.sub(1)); emit Transfer(_from, _to, _tokenId); } ///@dev The function is to be called by former owner to tranfer the token to the new owner himself. function transfer(address _to, uint256 _tokenId) external{ require(msg.sender == tokenIndexToOwner[_tokenId]); require(_to != 0x0); _transfer(msg.sender, _to, _tokenId); } function transferFrom(address _from, address _to, uint256 _tokenId) external{ // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); require(_to != address(this)); // Check for approval and valid ownership //require(_approvedFor(msg.sender, _tokenId)); require(ownerOf(_tokenId) == _from); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return WarriorList.length - 1; } function balanceOf(address _owner) public view returns (uint256 balance) { return ownerToTokenCount[_owner]; } function ownerOf(uint256 _tokenId) public view returns (address _owner) { _owner = tokenIndexToOwner[_tokenId]; require(_owner != address(0)); } ///@dev The function is to be called by new owner to get the token from the former owner himself. function takeOwnership(uint256 _tokenId) public { require(tokenApprovals[_tokenId] == msg.sender); address owner = ownerOf(_tokenId); _transfer(owner, msg.sender, _tokenId); } ///@dev The function is to be called by former owner to assign the token ownership to the new owner. function approve(address _to, uint256 _tokenId) external{ require(msg.sender == tokenIndexToOwner[_tokenId]); tokenApprovals[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } function destroyWeaponById(uint256 _tokenId) public { require(msg.sender == tokenIndexToOwner[_tokenId]); } // ERC721 function supportsInterface(bytes4 _interfaceId) external view returns(bool) { // ERC165 || ERC721 || ERC165^ERC721 return (_interfaceId == 0x01ffc9a7 || _interfaceId == 0x80ac58cd || _interfaceId == 0x8153916a) && (_interfaceId != 0xffffffff); } }
@dev adopt a level 3 warrior (0.1 eth)
function adoptLvThree() external payable returns(uint256) { require(msg.sender != address(0)); require(msg.value >= 0.1 ether); uint newWarriorId = WarriorList.length; WarriorList.length += 1; Warrior storage war = WarriorList[newWarriorId]; war.val = msg.value; war.winCount = 0; war.lossCount = 0; war.combo = 0; war.title = 0; war.prestige = 0; war.ce = 100; war.createTime = now; war.destroyTime = 0; war.lastAttackCoach1 = 0; war.lastAttackCoach2 = 0; war.lastAttackCoach3 = 0; war.lastAttackCoach4 = 0; _transfer(0,msg.sender, newWarriorId); databaseContract.addAccountEth(msg.sender, msg.value); ActiveWarriorListLength = ActiveWarriorListLength.add(1); CreateWarrior(msg.sender, newWarriorId, msg.value); return newWarriorId; }
1,821,251
[ 1, 361, 3838, 279, 1801, 890, 21983, 2432, 261, 20, 18, 21, 13750, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1261, 3838, 48, 90, 28019, 1435, 7010, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 1135, 12, 11890, 5034, 13, 203, 3639, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 374, 18, 21, 225, 2437, 1769, 203, 203, 203, 3639, 2254, 394, 30634, 2432, 548, 273, 678, 297, 2432, 682, 18, 2469, 31, 203, 3639, 678, 297, 2432, 682, 18, 2469, 1011, 404, 31, 203, 3639, 678, 297, 2432, 2502, 21983, 273, 678, 297, 2432, 682, 63, 2704, 30634, 2432, 548, 15533, 203, 3639, 21983, 18, 1125, 273, 1234, 18, 1132, 31, 203, 3639, 21983, 18, 8082, 1380, 273, 374, 31, 203, 3639, 21983, 18, 7873, 1380, 273, 374, 31, 203, 3639, 21983, 18, 25053, 273, 374, 31, 203, 3639, 21983, 18, 2649, 273, 374, 31, 203, 3639, 21983, 18, 1484, 334, 360, 73, 273, 374, 31, 203, 3639, 21983, 18, 311, 273, 2130, 31, 203, 3639, 21983, 18, 2640, 950, 273, 2037, 31, 203, 3639, 21983, 18, 11662, 950, 273, 374, 31, 203, 3639, 21983, 18, 2722, 3075, 484, 4249, 497, 21, 273, 374, 31, 203, 3639, 21983, 18, 2722, 3075, 484, 4249, 497, 22, 273, 374, 31, 203, 3639, 21983, 18, 2722, 3075, 484, 4249, 497, 23, 273, 374, 31, 203, 3639, 21983, 18, 2722, 3075, 484, 4249, 497, 24, 273, 374, 31, 203, 203, 3639, 389, 13866, 12, 20, 16, 3576, 18, 15330, 16, 394, 30634, 2432, 548, 1769, 203, 3639, 2063, 8924, 18, 1289, 3032, 2 ]
pragma solidity ^0.4.16; import "./RefundVault.sol"; /** * @title Owned * @dev The Owned contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Owned { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Owned constructor sets the original `owner` of the contract to the sender * account. */ function Owned() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } interface token { function mint(address receiver, uint amount) external; } contract FCCCrowdsale is RefundVault, Owned{ address public beneficiary; uint256 public fundingGoal; uint256 public amountRaised; uint256 public openingTime; uint256 public closingTime; uint256 public initialRate; uint256 public finalRate; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; token public tokenReward; mapping(address => uint256) public balanceOf; bool fundingGoalReached = false; bool crowdsaleClosed = false; bool public isFinalized = false; event GoalReached(address recipient, uint totalAmountRaised); event FundTransfer(address backer, uint amount, bool isContribution); event Finalized(); /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(now >= openingTime && now <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public { require(_openingTime >= now); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { return now > closingTime; } /** * Constrctor function * * Setup the owner */ function Crowdsale( address ifSuccessfulSendTo, uint256 fundingGoalInEthers, address addressOfTokenUsedAsReward ) public { beneficiary = ifSuccessfulSendTo; fundingGoal = fundingGoalInEthers * 1 ether; closingTime; tokenReward = token(addressOfTokenUsedAsReward); } /** * @dev Constructor, takes intial and final rates of tokens received per wei contributed. * @param _initialRate Number of tokens a buyer gets per wei at the start of the crowdsale * @param _finalRate Number of tokens a buyer gets per wei at the end of the crowdsale */ function IncreasingPriceCrowdsale(uint256 _initialRate, uint256 _finalRate) public { require(_initialRate >= _finalRate); require(_finalRate > 0); initialRate = _initialRate; finalRate = _finalRate; } /** * @dev Returns the rate of tokens per wei at the present time. * Note that, as price _increases_ with time, the rate _decreases_. * @return The number of tokens a buyer gets per wei at a given time */ function getCurrentRate() public view returns (uint256) { uint256 elapsedTime = now.sub(openingTime); uint256 timeRange = closingTime.sub(openingTime); uint256 rateRange = initialRate.sub(finalRate); return initialRate.sub(elapsedTime.mul(rateRange).div(timeRange)); } /** * @dev Overrides parent method taking into account variable rate. * @param _weiAmount The value in wei to be converted into tokens * @return The number of tokens _weiAmount wei will buy at present time */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 currentRate = getCurrentRate(); return currentRate.mul(_weiAmount); } /** * Fallback function * * The function without name is the default function that is called whenever anyone sends funds to a contract */ function () payable public { require(!crowdsaleClosed); uint256 rateAmount = getCurrentRate(); uint256 amount = msg.value; balanceOf[msg.sender] += amount; amountRaised += amount; tokenReward.mint(msg.sender, amount / rateAmount); tokenReward.mint(beneficiary, amount / rateAmount); emit FundTransfer(msg.sender, amount, true); } modifier afterDeadline() { if (now >= closingTime) _; } /** * @dev Constructor, creates RefundVault. * @param _goal Funding goal */ function RefundableCrowdsale(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(goal < amountRaised); vault.refund(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return amountRaised >= goal; } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public onlyOwner { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev vault finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } }
* @dev Overrides parent method taking into account variable rate. @param _weiAmount The value in wei to be converted into tokens @return The number of tokens _weiAmount wei will buy at present time/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 currentRate = getCurrentRate(); return currentRate.mul(_weiAmount); }
12,743,136
[ 1, 13084, 982, 707, 13763, 1368, 2236, 2190, 4993, 18, 225, 389, 1814, 77, 6275, 1021, 460, 316, 732, 77, 358, 506, 5970, 1368, 2430, 327, 1021, 1300, 434, 2430, 389, 1814, 77, 6275, 732, 77, 903, 30143, 622, 3430, 813, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 588, 1345, 6275, 12, 11890, 5034, 389, 1814, 77, 6275, 13, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2254, 5034, 783, 4727, 273, 5175, 4727, 5621, 203, 565, 327, 783, 4727, 18, 16411, 24899, 1814, 77, 6275, 1769, 203, 225, 289, 203, 21281, 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 ]
//Address: 0xd16c5175c90c8730d365d3616d36148ff43c110c //Contract name: BearCoin //Balance: 0 Ether //Verification Date: 10/12/2017 //Transacion Count: 2 // CODE STARTS HERE pragma solidity ^0.4.13; 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; } } contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); owner = newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ function HasNoEther() payable { require(msg.value == 0); } /** * @dev Disallows direct send by settings a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { assert(owner.send(this.balance)); } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { 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) constant returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract LimitedTransferToken is ERC20 { /** * @dev Checks whether it can transfer or otherwise throws. */ modifier canTransfer(address _sender, uint256 _value) { require(_value <= transferableTokens(_sender, uint64(now))); _; } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _to The address that will recieve the tokens. * @param _value The amount of tokens to be transferred. */ function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) returns (bool) { return super.transfer(_to, _value); } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _from The address that will send the tokens. * @param _to The address that will recieve the tokens. * @param _value The amount of tokens to be transferred. */ function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Default transferable tokens function returns all tokens for a holder (no limit). * @dev Overwriting transferableTokens(address holder, uint64 time) is the way to provide the * specific logic for limiting token transferability for a holder over time. */ function transferableTokens(address holder, uint64 time) constant public returns (uint256) { return balanceOf(holder); } } 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) returns (bool) { var _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) returns (bool) { // 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 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) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract BurnableToken is StandardToken { /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint _value) public { require(_value > 0); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } event Burn(address indexed burner, uint indexed value); } 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) onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract BearCoin is BurnableToken, MintableToken, LimitedTransferToken, Pausable, HasNoEther { struct Tether { bytes5 currency; uint32 amount; uint32 price; uint32 startBlock; uint32 endBlock; } address[] public addressById; mapping (string => uint256) idByName; mapping (address => string) nameByAddress; // Ether/Wei have the same conversion as Bear/Cub uint256 public constant INITIAL_SUPPLY = 2000000 ether; string public constant symbol = "BEAR"; uint256 public constant decimals = 18; string public constant name = "BearCoin"; string constant genesis = "CR30001"; uint256 public genesisBlock = 0; mapping (address => Tether[]) public currentTethers; address public controller; event Tethered(address indexed holder, string holderName, string currency, uint256 amount, uint32 price, uint256 indexed tetherID, uint timestamp, string message); event Untethered(address indexed holder,string holderName, string currency, uint256 amount, uint32 price, uint32 finalPrice, uint256 outcome, uint256 indexed tetherID, uint timestamp); event NameRegistered(address indexed a, uint256 id, string userName, uint timestamp); event NameChanged(address indexed a, uint256 id, string newUserName, string oldUserName, uint timestamp); function BearCoin() { balances[msg.sender] = INITIAL_SUPPLY; totalSupply = INITIAL_SUPPLY; addressById.push(0x0); idByName[genesis] = 0; nameByAddress[0x0] = genesis; genesisBlock = block.number; } // Non-upgradable function required for LimitedTransferToken function transferableTokens(address holder, uint64 time) constant public returns (uint256) { uint256 count = tetherCount(holder); if (count == 0) return super.transferableTokens(holder, time); uint256 tetheredTokens = 0; for (uint256 i = 0; i < count; i++) { // All tethers are initialized with an endBlock of 0 if (currentTethers[holder][i].endBlock == 0) { tetheredTokens = tetheredTokens.add(_finneyToWei(currentTethers[holder][i].amount)); } } return balances[holder].sub(tetheredTokens); } // only x modifiers modifier onlyController() { require(msg.sender == controller); _; } // Set roles function setController(address a) onlyOwner { controller = a; } // Controller-only functions function addTether(address a, string _currency, uint256 amount, uint32 price, string m) external onlyController whenNotPaused { // Make sure there are enough BearCoins to tether require(transferableTokens(a, 0) >= amount); bytes5 currency = _stringToBytes5(_currency); uint256 count = currentTethers[a].push(Tether(currency, _weiToFinney(amount), price, uint32(block.number.sub(genesisBlock)), 0)); Tethered(a, nameByAddress[a], _currency, amount, price, count - 1, now, m); } function setTether(address a, uint256 tetherID, uint32 finalPrice, uint256 outcome) external onlyController whenNotPaused { currentTethers[a][tetherID].endBlock = uint32(block.number.sub(genesisBlock)); Tether memory tether = currentTethers[a][tetherID]; Untethered(a, nameByAddress[a], _bytes5ToString(tether.currency), tether.amount, tether.price, finalPrice, outcome, tetherID, now); } function controlledMint(address _to, uint256 _amount) external onlyController whenNotPaused returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } function controlledBurn(address _from, uint256 _value) external onlyController whenNotPaused returns (bool) { require(_value > 0); balances[_from] = balances[_from].sub(_value); totalSupply = totalSupply.sub(_value); Burn(_from, _value); return true; } function registerName(address a, string n) external onlyController whenNotPaused { require(!isRegistered(a)); require(getIdByName(n) == 0); require(a != 0x0); require(_nameValid(n)); uint256 length = addressById.push(a); uint256 id = length - 1; idByName[_toLower(n)] = id; nameByAddress[a] = n; NameRegistered(a, id, n, now); } function changeName(address a, string n) external onlyController whenNotPaused { require(isRegistered(a)); require(getIdByName(n) == 0); require(a != 0x0); require(_nameValid(n)); string memory old = nameByAddress[a]; uint256 id = getIdByName(old); idByName[_toLower(old)] = 0; idByName[_toLower(n)] = id; nameByAddress[a] = n; NameChanged(a, id, n, old, now); } // Getters function getTether(address a, uint256 tetherID) public constant returns (string, uint256, uint32, uint256, uint256) { Tether storage tether = currentTethers[a][tetherID]; return (_bytes5ToString(tether.currency), _finneyToWei(tether.amount), tether.price, uint256(tether.startBlock).add(genesisBlock), uint256(tether.endBlock).add(genesisBlock)); } function getTetherInts(address a, uint256 tetherID) public constant returns (uint256, uint32, uint32, uint32) { Tether memory tether = currentTethers[a][tetherID]; return (_finneyToWei(tether.amount), tether.price, tether.startBlock, tether.endBlock); } function tetherCount(address a) public constant returns (uint256) { return currentTethers[a].length; } function getAddressById(uint256 id) returns (address) { return addressById[id]; } function getIdByName(string n) returns (uint256) { return idByName[_toLower(n)]; } function getNameByAddress(address a) returns (string) { return nameByAddress[a]; } function getAddressCount() returns (uint256) { return addressById.length; } // Utility functions function verifyTetherCurrency(address a, uint256 tetherID, string currency) public constant returns (bool) { return currentTethers[a][tetherID].currency == _stringToBytes5(currency); } function verifyTetherLoss(address a, uint256 tetherID, uint256 price) public constant returns (bool) { return currentTethers[a][tetherID].price < uint32(price); } function isRegistered(address a) returns (bool) { return keccak256(nameByAddress[a]) != keccak256(''); } // Internal helper functions function _nameValid(string s) internal returns (bool) { return bytes(s).length != 0 && keccak256(s) != keccak256(genesis) && bytes(s).length <= 32; } function _bytes5ToString(bytes5 b) internal returns (string memory s) { bytes memory bs = new bytes(5); for (uint8 i = 0; i < 5; i++) { bs[i] = b[i]; } s = string(bs); } function _stringToBytes5(string memory s) internal returns (bytes5 b) { assembly { b := mload(add(s, 32)) } } function _toLower(string str) internal returns (string) { bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character... if ((bStr[i] >= 65) && (bStr[i] <= 90)) { // So we add 32 to make it lowercase bLower[i] = bytes1(int(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } function _finneyToWei(uint32 _n) returns (uint256) { uint256 n = uint256(_n); uint256 f = 1 finney; return n.mul(f); } function _weiToFinney(uint256 n) returns (uint32) { uint256 f = 1 finney; uint256 p = n.div(f); return uint32(p); } }
Internal helper functions
function _nameValid(string s) internal returns (bool) { return bytes(s).length != 0 && keccak256(s) != keccak256(genesis) && bytes(s).length <= 32; }
12,739,750
[ 1, 3061, 4222, 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, 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, 202, 915, 389, 529, 1556, 12, 1080, 272, 13, 2713, 1135, 261, 6430, 13, 288, 203, 202, 202, 2463, 1731, 12, 87, 2934, 2469, 480, 374, 597, 417, 24410, 581, 5034, 12, 87, 13, 480, 417, 24410, 581, 5034, 12, 4507, 16786, 13, 597, 1731, 12, 87, 2934, 2469, 1648, 3847, 31, 203, 202, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** @title Onasander Token Contract * * @author: Andrzej Wegrzyn * Contact: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e6828390838a89968b838892a6898887958788828394c885898b">[email&#160;protected]</a> * Date: May 5, 2018 * Location: New York, USA * Token: Onasander * Symbol: ONA * * @notice This is a simple contract due to solidity bugs and complications. * * @notice Owner has the option to burn all the remaining tokens after the ICO. That way Owners will not end up with majority of the tokens. * @notice Onasander would love to give every user the option to burn the remaining tokens, but due to Solidity VM bugs and risk, we will process * @notice all coin burns and refunds manually. * * @notice How to run the contract: * * Requires: * Wallet Address * * Run: * 1. Create Contract * 2. Set Minimum Goal * 3. Set Tokens Per ETH * 4. Create PRE ICO Sale (can have multiple PRE-ICOs) * 5. End PRE ICO Sale * 6. Create ICO Sale * 7. End ICO Sale * 8. END ICO * 9. Burn Remaining Tokens * * e18 for every value except tokens per ETH * * @dev This contract allows you to configure as many Pre-ICOs as you need. It&#39;s a very simple contract written to give contract admin lots of dynamic options. * @dev Here, most features except for total supply, max tokens for sale, company reserves, and token standard features, are dynamic. You can configure your contract * @dev however you want to. * * @dev IDE: Remix with Mist 0.10 * @dev Token supply numbers are provided in 0e18 format in MIST in order to bypass MIST number format errors. */ pragma solidity ^0.4.23; contract OnasanderToken { using SafeMath for uint; address private wallet; // Address where funds are collected address public owner; // contract owner string constant public name = "Onasander"; string constant public symbol = "ONA"; uint8 constant public decimals = 18; uint public totalSupply = 88000000e18; uint public totalTokensSold = 0e18; // total number of tokens sold to date uint public totalTokensSoldInThisSale = 0e18; // total number of tokens sold in this sale uint public maxTokensForSale = 79200000e18; // 90% max tokens we can ever sale uint public companyReserves = 8800000e18; // 10% company reserves. this is what we end up with after eco ends and burns the rest if any uint public minimumGoal = 0e18; // hold minimum goal uint public tokensForSale = 0e18; // total number of tokens we are selling in the current sale (ICO, preICO) bool public saleEnabled = false; // enables all sales: ICO and tokensPreICO bool public ICOEnded = false; // flag checking if the ICO has completed bool public burned = false; // Excess tokens burned flag after ICO ends uint public tokensPerETH = 800; // amount of Onasander tokens you get for 1 ETH bool public wasGoalReached = false; // checks if minimum goal was reached address private lastBuyer; uint private singleToken = 1e18; constructor(address icoWallet) public { require(icoWallet != address(0), "ICO Wallet address is required."); owner = msg.sender; wallet = icoWallet; balances[owner] = totalSupply; // give initial full balance to contract owner emit TokensMinted(owner, totalSupply); } event ICOHasEnded(); event SaleEnded(); event OneTokenBugFixed(); event ICOConfigured(uint minimumGoal); event TokenPerETHReset(uint amount); event ICOCapReached(uint amount); event SaleCapReached(uint amount); event GoalReached(uint amount); event Burned(uint amount); event BuyTokens(address buyer, uint tokens); event SaleStarted(uint tokensForSale); event TokensMinted(address targetAddress, uint tokens); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner, uint tokens); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); mapping(address => uint) balances; mapping(address => mapping (address => uint)) allowances; function balanceOf(address accountAddress) public constant returns (uint balance) { return balances[accountAddress]; } function allowance(address sender, address spender) public constant returns (uint remainingAllowedAmount) { return allowances[sender][spender]; } function transfer(address to, uint tokens) public returns (bool success) { require (ICOEnded, "ICO has not ended. Can not transfer."); require (balances[to] + tokens > balances[to], "Overflow is not allowed."); // actual transfer // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns(bool success) { require (ICOEnded, "ICO has not ended. Can not transfer."); require (balances[to] + tokens > balances[to], "Overflow is not allowed."); // actual transfer balances[from] = balances[from].sub(tokens); allowances[from][msg.sender] = allowances[from][msg.sender].sub(tokens); // lower the allowance by the amount of tokens balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function approve(address spender, uint tokens) public returns(bool success) { require (ICOEnded, "ICO has not ended. Can not transfer."); allowances[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // in case some investor pays by wire or credit card we will transfer him the tokens manually. function wirePurchase(address to, uint numberOfTokenPurchased) onlyOwner public { require (saleEnabled, "Sale must be enabled."); require (!ICOEnded, "ICO already ended."); require (numberOfTokenPurchased > 0, "Tokens must be greater than 0."); require (tokensForSale > totalTokensSoldInThisSale, "There is no more tokens for sale in this sale."); // calculate amount uint buyAmount = numberOfTokenPurchased; uint tokens = 0e18; // this check is not perfect as someone may want to buy more than we offer for sale and we lose a sale. // the best would be to calclate and sell you only the amout of tokens that is left and refund the rest of money if (totalTokensSoldInThisSale.add(buyAmount) >= tokensForSale) { tokens = tokensForSale.sub(totalTokensSoldInThisSale); // we allow you to buy only up to total tokens for sale, and refund the rest // need to program the refund for the rest,or do it manually. } else { tokens = buyAmount; } // transfer only as we do not need to take the payment since we already did in wire require (balances[to].add(tokens) > balances[to], "Overflow is not allowed."); balances[to] = balances[to].add(tokens); balances[owner] = balances[owner].sub(tokens); lastBuyer = to; // update counts totalTokensSold = totalTokensSold.add(tokens); totalTokensSoldInThisSale = totalTokensSoldInThisSale.add(tokens); emit BuyTokens(to, tokens); emit Transfer(owner, to, tokens); isGoalReached(); isMaxCapReached(); } function buyTokens() payable public { require (saleEnabled, "Sale must be enabled."); require (!ICOEnded, "ICO already ended."); require (tokensForSale > totalTokensSoldInThisSale, "There is no more tokens for sale in this sale."); require (msg.value > 0, "Must send ETH"); // calculate amount uint buyAmount = SafeMath.mul(msg.value, tokensPerETH); uint tokens = 0e18; // this check is not perfect as someone may want to buy more than we offer for sale and we lose a sale. // the best would be to calclate and sell you only the amout of tokens that is left and refund the rest of money if (totalTokensSoldInThisSale.add(buyAmount) >= tokensForSale) { tokens = tokensForSale.sub(totalTokensSoldInThisSale); // we allow you to buy only up to total tokens for sale, and refund the rest // need to program the refund for the rest } else { tokens = buyAmount; } // buy require (balances[msg.sender].add(tokens) > balances[msg.sender], "Overflow is not allowed."); balances[msg.sender] = balances[msg.sender].add(tokens); balances[owner] = balances[owner].sub(tokens); lastBuyer = msg.sender; // take the money out right away wallet.transfer(msg.value); // update counts totalTokensSold = totalTokensSold.add(tokens); totalTokensSoldInThisSale = totalTokensSoldInThisSale.add(tokens); emit BuyTokens(msg.sender, tokens); emit Transfer(owner, msg.sender, tokens); isGoalReached(); isMaxCapReached(); } // Fallback function. Used for buying tokens from contract owner by simply // sending Ethers to contract. function() public payable { // we buy tokens using whatever ETH was sent in buyTokens(); } // Called when ICO is closed. Burns the remaining tokens except the tokens reserved // Must be called by the owner to trigger correct transfer event function burnRemainingTokens() public onlyOwner { require (!burned, "Remaining tokens have been burned already."); require (ICOEnded, "ICO has not ended yet."); uint difference = balances[owner].sub(companyReserves); if (wasGoalReached) { totalSupply = totalSupply.sub(difference); balances[owner] = companyReserves; } else { // in case we did not reach the goal, we burn all tokens except tokens purchased. totalSupply = totalTokensSold; balances[owner] = 0e18; } burned = true; emit Transfer(owner, address(0), difference); // this is run in order to update token holders in the website emit Burned(difference); } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { address preOwner = owner; owner = newOwner; uint previousBalance = balances[preOwner]; // transfer balance balances[newOwner] = balances[newOwner].add(previousBalance); balances[preOwner] = 0; //emit Transfer(preOwner, newOwner, previousBalance); // required to update the Token Holders on the network emit OwnershipTransferred(preOwner, newOwner, previousBalance); } // Set the number of ONAs sold per ETH function setTokensPerETH(uint newRate) onlyOwner public { require (!ICOEnded, "ICO already ended."); require (newRate > 0, "Rate must be higher than 0."); tokensPerETH = newRate; emit TokenPerETHReset(newRate); } // Minimum goal is based on USD, not on ETH. Since we will have different dynamic prices based on the daily pirce of ETH, we // will need to be able to adjust our minimum goal in tokens sold, as our goal is set in tokens, not USD. function setMinimumGoal(uint goal) onlyOwner public { require(goal > 0e18,"Minimum goal must be greater than 0."); minimumGoal = goal; // since we can edit the goal, we want to check if we reached the goal before in case we lowered the goal number. isGoalReached(); emit ICOConfigured(goal); } function createSale(uint numberOfTokens) onlyOwner public { require (!saleEnabled, "Sale is already going on."); require (!ICOEnded, "ICO already ended."); require (totalTokensSold < maxTokensForSale, "We already sold all our tokens."); totalTokensSoldInThisSale = 0e18; uint tryingToSell = totalTokensSold.add(numberOfTokens); // in case we are trying to create a sale with too many tokens, we subtract and sell only what&#39;s left if (tryingToSell > maxTokensForSale) { tokensForSale = maxTokensForSale.sub(totalTokensSold); } else { tokensForSale = numberOfTokens; } tryingToSell = 0e18; saleEnabled = true; emit SaleStarted(tokensForSale); } function endSale() public { if (saleEnabled) { saleEnabled = false; tokensForSale = 0e18; emit SaleEnded(); } } function endICO() onlyOwner public { if (!ICOEnded) { // run this before end of ICO and end of last sale fixTokenCalcBug(); endSale(); ICOEnded = true; lastBuyer = address(0); emit ICOHasEnded(); } } function isGoalReached() internal { // check if we reached the goal if (!wasGoalReached) { if (totalTokensSold >= minimumGoal) { wasGoalReached = true; emit GoalReached(minimumGoal); } } } function isMaxCapReached() internal { if (totalTokensSoldInThisSale >= tokensForSale) { emit SaleCapReached(totalTokensSoldInThisSale); endSale(); } if (totalTokensSold >= maxTokensForSale) { emit ICOCapReached(maxTokensForSale); endICO(); } } // This is a hack to add the lost token during final full sale. function fixTokenCalcBug() internal { require(!burned, "Fix lost token can only run before the burning of the tokens."); if (maxTokensForSale.sub(totalTokensSold) == singleToken) { totalTokensSold = totalTokensSold.add(singleToken); totalTokensSoldInThisSale = totalTokensSoldInThisSale.add(singleToken); balances[lastBuyer] = balances[lastBuyer].add(singleToken); balances[owner] = balances[owner].sub(singleToken); emit Transfer(owner, lastBuyer, singleToken); emit OneTokenBugFixed(); } } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
amount of Onasander tokens you get for 1 ETH
uint public tokensPerETH = 800;
2,073,844
[ 1, 8949, 434, 2755, 345, 464, 264, 2430, 1846, 336, 364, 404, 512, 2455, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 1071, 2430, 2173, 1584, 44, 273, 1725, 713, 31, 7682, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; interface IERC20 { // brief interface for erc20 token tx function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } library Address { // helper for address type - see openzeppelin-contracts/blob/master/contracts/utils/Address.sol function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } } library SafeERC20 { // wrapper around erc20 token tx for non-standard contract - see openzeppelin-contracts/blob/master/contracts/token/ERC20/SafeERC20.sol using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function _callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); (bool success, bytes memory returnData) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returnData.length > 0) { // return data is optional require(abi.decode(returnData, (bool)), "SafeERC20: erc20 operation did not succeed"); } } } library SafeMath { // arithmetic wrapper for unit under/overflow check function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } } contract ReentrancyGuard { // call wrapper for reentrancy check uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() internal { _status = _NOT_ENTERED; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } } contract MSTX is ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; /*************** GLOBAL CONSTANTS ***************/ address public depositToken; // deposit token contract reference - default = wETH address public stakeToken; // stake token contract reference for guild voting shares address public constant wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // canonical ether token wrapper contract reference uint256 public proposalDeposit; // default = 10 deposit token uint256 public processingReward; // default = 0.1 - amount of deposit token to give to whoever processes a proposal uint256 public periodDuration; // default = 17280 = 4.8 hours in seconds (5 periods per day) uint256 public votingPeriodLength; // default = 35 periods (7 days) uint256 public gracePeriodLength; // default = 35 periods (7 days) uint256 public dilutionBound; // default = 3 - maximum multiplier a YES voter will be obligated to pay in case of mass ragequit uint256 public summoningTime; // needed to determine the current period bool private initialized; // internally tracks deployment under eip-1167 proxy pattern // HARD-CODED LIMITS uint256 constant MAX_GUILD_BOUND = 10**36; // maximum bound for guild member accounting uint256 constant MAX_TOKEN_WHITELIST_COUNT = 400; // maximum number of whitelisted tokens uint256 constant MAX_TOKEN_GUILDBANK_COUNT = 200; // maximum number of tokens with non-zero balance in guildbank // GUILD TOKEN DETAILS uint8 public constant decimals = 18; string public constant name = "MSTX"; string public constant symbol = "MSTX"; // ******************* // INTERNAL ACCOUNTING // ******************* address public constant GUILD = address(0xdead); address public constant ESCROW = address(0xdeaf); address public constant TOTAL = address(0xdeed); uint256 public proposalCount; // total proposals submitted uint256 public totalShares; // total shares across all members uint256 public totalLoot; // total loot across all members uint256 public totalSupply; // total shares & loot across all members (total guild tokens) uint256 public totalGuildBankTokens; // total tokens with non-zero balance in guild bank mapping(uint256 => bytes) public actions; // proposalId => action data mapping(address => uint256) public balanceOf; // guild token balances mapping(address => mapping(address => uint256)) public allowance; // guild token (loot) allowances mapping(address => mapping(address => uint256)) private userTokenBalances; // userTokenBalances[userAddress][tokenAddress] address[] public approvedTokens; mapping(address => bool) public tokenWhitelist; uint256[] public proposalQueue; mapping(uint256 => Proposal) public proposals; mapping(address => bool) public proposedToWhitelist; mapping(address => bool) public proposedToKick; mapping(address => Member) public members; mapping(address => address) public memberAddressByDelegateKey; // ************** // EVENT TRACKING // ************** event SubmitProposal(address indexed applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, bytes32 details, uint8[9] flags, bytes data, uint256 proposalId, address indexed delegateKey, address indexed memberAddress); event CancelProposal(uint256 indexed proposalId, address applicantAddress); event SponsorProposal(address indexed delegateKey, address indexed memberAddress, uint256 proposalId, uint256 proposalIndex, uint256 startingPeriod); event SubmitVote(uint256 proposalId, uint256 indexed proposalIndex, address indexed delegateKey, address indexed memberAddress, uint8 uintVote); event ProcessProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event ProcessActionProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event ProcessGuildKickProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event ProcessWhitelistProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event ProcessWithdrawalProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event UpdateDelegateKey(address indexed memberAddress, address newDelegateKey); event Ragequit(address indexed memberAddress, uint256 sharesToBurn, uint256 lootToBurn); event TokensCollected(address indexed token, uint256 amountToCollect); event Withdraw(address indexed memberAddress, address token, uint256 amount); event ConvertSharesToLoot(address indexed memberAddress, uint256 amount); event StakeTokenForShares(address indexed memberAddress, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); // guild token (loot) allowance tracking event Transfer(address indexed sender, address indexed recipient, uint256 amount); // guild token mint, burn & loot transfer tracking enum Vote { Null, // default value, counted as abstention Yes, No } struct Member { address delegateKey; // the key responsible for submitting proposals & voting - defaults to member address unless updated uint8 exists; // always true (1) once a member has been created uint256 shares; // the # of voting shares assigned to this member uint256 loot; // the loot amount available to this member (combined with shares on ragekick) - transferable by guild token uint256 highestIndexYesVote; // highest proposal index # on which the member voted YES uint256 jailed; // set to proposalIndex of a passing guild kick proposal for this member, prevents voting on & sponsoring proposals } struct Proposal { address applicant; // the applicant who wishes to become a member - this key will be used for withdrawals (doubles as target for alt. proposals) address proposer; // the account that submitted the proposal (can be non-member) address sponsor; // the member that sponsored the proposal (moving it into the queue) address tributeToken; // tribute token contract reference address paymentToken; // payment token contract reference uint8[9] flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick, action, withdrawal, standard] uint256 sharesRequested; // the # of shares the applicant is requesting uint256 lootRequested; // the amount of loot the applicant is requesting uint256 paymentRequested; // amount of tokens requested as payment uint256 tributeOffered; // amount of tokens offered as tribute uint256 startingPeriod; // the period in which voting can start for this proposal uint256 yesVotes; // the total number of YES votes for this proposal uint256 noVotes; // the total number of NO votes for this proposal uint256 maxTotalSharesAndLootAtYesVote; // the maximum # of total shares encountered at a yes vote on this proposal bytes32 details; // proposal details to add context for members mapping(address => Vote) votesByMember; // the votes on this proposal by each member } modifier onlyDelegate { require(members[memberAddressByDelegateKey[msg.sender]].shares > 0, "!delegate"); _; } function init( address _depositToken, address _stakeToken, address[] memory _summoner, uint256[] memory _summonerShares, uint256 _summonerDeposit, uint256 _proposalDeposit, uint256 _processingReward, uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _dilutionBound ) external { require(!initialized, "initialized"); require(_depositToken != _stakeToken, "depositToken = stakeToken"); require(_summoner.length == _summonerShares.length, "summoner != summonerShares"); require(_proposalDeposit >= _processingReward, "_processingReward > _proposalDeposit"); for (uint256 i = 0; i < _summoner.length; i++) { growGuild(_summoner[i], _summonerShares[i], 0); } require(totalShares <= MAX_GUILD_BOUND, "guild maxed"); tokenWhitelist[_depositToken] = true; approvedTokens.push(_depositToken); if (_summonerDeposit > 0) { totalGuildBankTokens += 1; unsafeAddToBalance(GUILD, _depositToken, _summonerDeposit); } depositToken = _depositToken; stakeToken = _stakeToken; proposalDeposit = _proposalDeposit; processingReward = _processingReward; periodDuration = _periodDuration; votingPeriodLength = _votingPeriodLength; gracePeriodLength = _gracePeriodLength; dilutionBound = _dilutionBound; summoningTime = now; initialized = true; } /***************** PROPOSAL FUNCTIONS *****************/ function submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, bytes32 details ) external nonReentrant payable returns (uint256 proposalId) { require(sharesRequested.add(lootRequested) <= MAX_GUILD_BOUND, "guild maxed"); require(tokenWhitelist[tributeToken], "tributeToken != whitelist"); require(tokenWhitelist[paymentToken], "paymentToken != whitelist"); require(applicant != GUILD && applicant != ESCROW && applicant != TOTAL, "applicant unreservable"); require(members[applicant].jailed == 0, "applicant jailed"); if (tributeOffered > 0 && userTokenBalances[GUILD][tributeToken] == 0) { require(totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, "guildbank maxed"); } // collect tribute from proposer & store it in MSTX until the proposal is processed - if ether, wrap into wETH if (msg.value > 0) { require(tributeToken == wETH && msg.value == tributeOffered, "!ethBalance"); (bool success, ) = wETH.call{value: msg.value}(""); require(success, "!ethCall"); IERC20(wETH).safeTransfer(address(this), msg.value); } else { IERC20(tributeToken).safeTransferFrom(msg.sender, address(this), tributeOffered); } unsafeAddToBalance(ESCROW, tributeToken, tributeOffered); uint8[9] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick, action, withdrawal, standard] flags[8] = 1; // standard _submitProposal(applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags, ""); return proposalCount - 1; // return proposalId - contracts calling submit might want it } function submitActionProposal( // stages arbitrary function calls for member vote - based on Raid Guild 'Minion' address actionTo, // target account for action (e.g., address to receive ether, token, dao, etc.) uint256 actionTokenAmount, // helps check outbound guild bank token amount does not exceed internal balance / amount to update bank if successful uint256 actionValue, // ether value, if any, in call bytes32 details, // details tx staged for member execution - as external, extra care should be applied in diligencing action bytes calldata data // data for function call ) external returns (uint256 proposalId) { uint8[9] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick, action, withdrawal, standard] flags[6] = 1; // action _submitProposal(actionTo, 0, 0, actionValue, address(0), actionTokenAmount, address(0), details, flags, data); return proposalCount - 1; } function submitGuildKickProposal(address memberToKick, bytes32 details) external returns (uint256 proposalId) { Member memory member = members[memberToKick]; require(member.shares > 0 || member.loot > 0, "!share||loot"); require(members[memberToKick].jailed == 0, "jailed"); uint8[9] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick, action, withdrawal, standard] flags[5] = 1; // guildkick _submitProposal(memberToKick, 0, 0, 0, address(0), 0, address(0), details, flags, ""); return proposalCount - 1; } function submitWhitelistProposal(address tokenToWhitelist, bytes32 details) external returns (uint256 proposalId) { require(tokenToWhitelist != address(0), "!token"); require(tokenToWhitelist != stakeToken, "tokenToWhitelist = stakeToken"); require(!tokenWhitelist[tokenToWhitelist], "whitelisted"); require(approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "whitelist maxed"); uint8[9] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick, action, withdrawal, standard] flags[4] = 1; // whitelist _submitProposal(address(0), 0, 0, 0, tokenToWhitelist, 0, address(0), details, flags, ""); return proposalCount - 1; } function submitWithdrawalProposal(address withdrawalTo, bytes32 details) external returns (uint256 proposalId) { uint8[9] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick, action, withdrawal, standard] flags[7] = 1; // withdrawal _submitProposal(withdrawalTo, 0, 0, 0, address(0), 0, address(0), details, flags, ""); return proposalCount - 1; } function _submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, bytes32 details, uint8[9] memory flags, bytes memory data ) internal { Proposal memory proposal = Proposal({ applicant : applicant, proposer : msg.sender, sponsor : address(0), tributeToken : tributeToken, paymentToken : paymentToken, flags : flags, sharesRequested : sharesRequested, lootRequested : lootRequested, paymentRequested : paymentRequested, tributeOffered : tributeOffered, startingPeriod : 0, yesVotes : 0, noVotes : 0, maxTotalSharesAndLootAtYesVote : 0, details : details }); if (proposal.flags[6] == 1) { actions[proposalCount] = data; } proposals[proposalCount] = proposal; // NOTE: argument order matters, avoid stack too deep emit SubmitProposal(applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags, data, proposalCount, msg.sender, memberAddressByDelegateKey[msg.sender]); proposalCount += 1; } function sponsorProposal(uint256 proposalId) external nonReentrant onlyDelegate { // collect proposal deposit from sponsor & store it in MSTX until the proposal is processed IERC20(depositToken).safeTransferFrom(msg.sender, address(this), proposalDeposit); unsafeAddToBalance(ESCROW, depositToken, proposalDeposit); Proposal storage proposal = proposals[proposalId]; require(proposal.proposer != address(0), "!proposed"); require(proposal.flags[0] == 0, "sponsored"); require(proposal.flags[3] == 0, "cancelled"); require(members[proposal.applicant].jailed == 0, "applicant jailed"); if (proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0) { require(totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, "guildbank maxed"); } // whitelist proposal if (proposal.flags[4] == 1) { require(!tokenWhitelist[address(proposal.tributeToken)], "whitelisted"); require(!proposedToWhitelist[address(proposal.tributeToken)], "whitelist proposed"); require(approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "whitelist maxed"); proposedToWhitelist[address(proposal.tributeToken)] = true; // guild kick proposal } else if (proposal.flags[5] == 1) { require(!proposedToKick[proposal.applicant], "kick proposed"); proposedToKick[proposal.applicant] = true; } // compute startingPeriod for proposal uint256 startingPeriod = max( getCurrentPeriod(), proposalQueue.length == 0 ? 0 : proposals[proposalQueue[proposalQueue.length - 1]].startingPeriod ) + 1; proposal.startingPeriod = startingPeriod; proposal.sponsor = memberAddressByDelegateKey[msg.sender]; proposal.flags[0] = 1; // sponsored // append proposal to the queue proposalQueue.push(proposalId); emit SponsorProposal(msg.sender, proposal.sponsor, proposalId, proposalQueue.length - 1, startingPeriod); } // NOTE: In MSTX, proposalIndex != proposalId function submitVote(uint256 proposalIndex, uint8 uintVote) external nonReentrant onlyDelegate { address memberAddress = memberAddressByDelegateKey[msg.sender]; Member storage member = members[memberAddress]; require(proposalIndex < proposalQueue.length, "!proposed"); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(uintVote < 3, ">2"); Vote vote = Vote(uintVote); require(getCurrentPeriod() >= proposal.startingPeriod, "pending"); require(!hasVotingPeriodExpired(proposal.startingPeriod), "expired"); require(proposal.votesByMember[memberAddress] == Vote.Null, "voted"); require(vote == Vote.Yes || vote == Vote.No, "!Yes||No"); proposal.votesByMember[memberAddress] = vote; if (vote == Vote.Yes) { proposal.yesVotes += member.shares; // set highest index (latest) yes vote - must be processed for member to ragequit if (proposalIndex > member.highestIndexYesVote) { member.highestIndexYesVote = proposalIndex; } // set maximum of total shares encountered at a yes vote - used to bound dilution for yes voters if (totalSupply > proposal.maxTotalSharesAndLootAtYesVote) { proposal.maxTotalSharesAndLootAtYesVote = totalSupply; } } else if (vote == Vote.No) { proposal.noVotes += member.shares; } // NOTE: subgraph indexes by proposalId not proposalIndex since proposalIndex isn't set until it's been sponsored but proposal is created on submission emit SubmitVote(proposalId, proposalIndex, msg.sender, memberAddress, uintVote); } function processProposal(uint256 proposalIndex) external nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(proposal.flags[8] == 1, "!standard"); proposal.flags[1] = 1; // processed bool didPass = _didPass(proposalIndex); // Make the proposal fail if the new total number of shares & loot exceeds the limit if (totalSupply.add(proposal.sharesRequested).add(proposal.lootRequested) > MAX_GUILD_BOUND) { didPass = false; } // Make the proposal fail if it is requesting more tokens as payment than the available guild bank balance if (proposal.paymentRequested > userTokenBalances[GUILD][proposal.paymentToken]) { didPass = false; } // Make the proposal fail if it would result in too many tokens with non-zero balance in guild bank if (proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0 && totalGuildBankTokens >= MAX_TOKEN_GUILDBANK_COUNT) { didPass = false; } // PROPOSAL PASSED if (didPass) { proposal.flags[2] = 1; // didPass growGuild(proposal.applicant, proposal.sharesRequested, proposal.lootRequested); // if the proposal tribute is the first token of its kind to make it into the guild bank, increment total guild bank tokens if (userTokenBalances[GUILD][proposal.tributeToken] == 0 && proposal.tributeOffered > 0) { totalGuildBankTokens += 1; } unsafeInternalTransfer(ESCROW, GUILD, proposal.tributeToken, proposal.tributeOffered); unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposal.paymentRequested); // if the proposal spends 100% of guild bank balance for a token, decrement total guild bank tokens if (userTokenBalances[GUILD][proposal.paymentToken] == 0 && proposal.paymentRequested > 0) { totalGuildBankTokens -= 1; } // PROPOSAL FAILED } else { // return all tokens to the proposer (not the applicant, because funds come from proposer) unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered); } _returnDeposit(proposal.sponsor); emit ProcessProposal(proposalIndex, proposalId, didPass); } function processActionProposal(uint256 proposalIndex) external nonReentrant returns (bool, bytes memory) { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; bytes storage action = actions[proposalId]; Proposal storage proposal = proposals[proposalId]; require(proposal.flags[6] == 1, "!action"); proposal.flags[1] = 1; // processed bool didPass = _didPass(proposalIndex); // Make the proposal fail if it is requesting more accounted tokens than the available guild bank balance if (tokenWhitelist[proposal.applicant] && proposal.paymentRequested > userTokenBalances[GUILD][proposal.applicant]) { didPass = false; } // Make the proposal fail if it is requesting more ether than the available local balance if (proposal.tributeOffered > address(this).balance) { didPass = false; } if (didPass) { proposal.flags[2] = 1; // didPass (bool success, bytes memory returnData) = proposal.applicant.call{value: proposal.tributeOffered}(action); if (tokenWhitelist[proposal.applicant]) { unsafeSubtractFromBalance(GUILD, proposal.applicant, proposal.paymentRequested); // if the action proposal spends 100% of guild bank balance for a token, decrement total guild bank tokens if (userTokenBalances[GUILD][proposal.applicant] == 0 && proposal.paymentRequested > 0) {totalGuildBankTokens -= 1;} } return (success, returnData); } _returnDeposit(proposal.sponsor); emit ProcessActionProposal(proposalIndex, proposalId, didPass); } function processGuildKickProposal(uint256 proposalIndex) external nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(proposal.flags[5] == 1, "!kick"); proposal.flags[1] = 1; // processed bool didPass = _didPass(proposalIndex); if (didPass) { proposal.flags[2] = 1; // didPass Member storage member = members[proposal.applicant]; member.jailed = proposalIndex; // transfer shares to loot member.loot = member.loot.add(member.shares); totalShares = totalShares.sub(member.shares); totalLoot = totalLoot.add(member.shares); member.shares = 0; // revoke all shares } proposedToKick[proposal.applicant] = false; _returnDeposit(proposal.sponsor); emit ProcessGuildKickProposal(proposalIndex, proposalId, didPass); } function processWhitelistProposal(uint256 proposalIndex) external { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(proposal.flags[4] == 1, "!whitelist"); proposal.flags[1] = 1; // processed bool didPass = _didPass(proposalIndex); if (approvedTokens.length >= MAX_TOKEN_WHITELIST_COUNT) { didPass = false; } if (didPass) { proposal.flags[2] = 1; // didPass tokenWhitelist[address(proposal.tributeToken)] = true; approvedTokens.push(proposal.tributeToken); } proposedToWhitelist[address(proposal.tributeToken)] = false; _returnDeposit(proposal.sponsor); emit ProcessWhitelistProposal(proposalIndex, proposalId, didPass); } function processWithdrawalProposal(uint256 proposalIndex) external nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(proposal.flags[7] == 1, "!withdrawal"); proposal.flags[1] = 1; // processed bool didPass = _didPass(proposalIndex); if (didPass) { proposal.flags[2] = 1; // didPass for (uint256 i = 0; i < approvedTokens.length; i++) { // deliberately not using safemath here to keep overflows from preventing the function execution (which would break withdrawal) // if a token overflows, it is because the supply was artificially inflated to oblivion, so we probably don't care about it anyways uint256 withdrawalAmount = userTokenBalances[GUILD][approvedTokens[i]]; userTokenBalances[GUILD][approvedTokens[i]] -= withdrawalAmount; userTokenBalances[proposal.applicant][approvedTokens[i]] += withdrawalAmount; } totalGuildBankTokens -= approvedTokens.length; } _returnDeposit(proposal.sponsor); emit ProcessWithdrawalProposal(proposalIndex, proposalId, didPass); } function _didPass(uint256 proposalIndex) internal view returns (bool didPass) { Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; if (proposal.yesVotes > proposal.noVotes) { didPass = true; } // Make the proposal fail if the dilutionBound is exceeded if ((totalSupply.mul(dilutionBound)) < proposal.maxTotalSharesAndLootAtYesVote) { didPass = false; } // Make the proposal fail if the applicant is jailed // - for standard proposals, we don't want the applicant to get any shares/loot/payment // - for guild kick proposals, we should never be able to propose to kick a jailed member (or have two kick proposals active), so it doesn't matter if (members[proposal.applicant].jailed != 0) { didPass = false; } return didPass; } function _validateProposalForProcessing(uint256 proposalIndex) internal view { require(proposalIndex < proposalQueue.length, "!proposal"); Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; require(getCurrentPeriod() >= proposal.startingPeriod.add(votingPeriodLength).add(gracePeriodLength), "!ready"); require(proposal.flags[1] == 0, "processed"); require(proposalIndex == 0 || proposals[proposalQueue[proposalIndex - 1]].flags[1] == 1, "prior !processed"); } function _returnDeposit(address sponsor) internal { unsafeInternalTransfer(ESCROW, msg.sender, depositToken, processingReward); unsafeInternalTransfer(ESCROW, sponsor, depositToken, proposalDeposit - processingReward); } function ragequit(uint256 sharesToBurn, uint256 lootToBurn) external nonReentrant { require(members[msg.sender].exists == 1, "!member"); _ragequit(msg.sender, sharesToBurn, lootToBurn); } function _ragequit(address memberAddress, uint256 sharesToBurn, uint256 lootToBurn) internal { uint256 initialTotalSharesAndLoot = totalSupply; Member storage member = members[memberAddress]; require(member.shares >= sharesToBurn, "!shares"); require(member.loot >= lootToBurn, "!loot"); require(canRagequit(member.highestIndexYesVote), "!ragequit until highest index proposal member voted YES processes"); uint256 sharesAndLootToBurn = sharesToBurn.add(lootToBurn); // burn guild token, shares & loot balanceOf[memberAddress] = balanceOf[memberAddress].sub(sharesAndLootToBurn); member.shares = member.shares.sub(sharesToBurn); member.loot = member.loot.sub(lootToBurn); totalShares = totalShares.sub(sharesToBurn); totalLoot = totalLoot.sub(lootToBurn); totalSupply = totalShares.add(totalLoot); for (uint256 i = 0; i < approvedTokens.length; i++) { uint256 amountToRagequit = fairShare(userTokenBalances[GUILD][approvedTokens[i]], sharesAndLootToBurn, initialTotalSharesAndLoot); if (amountToRagequit > 0) { // gas optimization to allow a higher maximum token limit // deliberately not using safemath here to keep overflows from preventing the function execution (which would break ragekicks) // if a token overflows, it is because the supply was artificially inflated to oblivion, so we probably don't care about it anyways userTokenBalances[GUILD][approvedTokens[i]] -= amountToRagequit; userTokenBalances[memberAddress][approvedTokens[i]] += amountToRagequit; } } emit Ragequit(memberAddress, sharesToBurn, lootToBurn); emit Transfer(memberAddress, address(0), sharesAndLootToBurn); } function ragekick(address memberToKick) external nonReentrant onlyDelegate { Member storage member = members[memberToKick]; require(member.jailed != 0, "!jailed"); require(member.loot > 0, "!loot"); // note - should be impossible for jailed member to have shares require(canRagequit(member.highestIndexYesVote), "!ragequit until highest index proposal member voted YES processes"); _ragequit(memberToKick, 0, member.loot); } function withdrawBalance(address token, uint256 amount) external nonReentrant { _withdrawBalance(token, amount); } function withdrawBalances(address[] calldata tokens, uint256[] calldata amounts, bool max) external nonReentrant { require(tokens.length == amounts.length, "tokens != amounts"); for (uint256 i=0; i < tokens.length; i++) { uint256 withdrawAmount = amounts[i]; if (max) { // withdraw the maximum balance withdrawAmount = userTokenBalances[msg.sender][tokens[i]]; } _withdrawBalance(tokens[i], withdrawAmount); } } function _withdrawBalance(address token, uint256 amount) internal { require(userTokenBalances[msg.sender][token] >= amount, "!balance"); IERC20(token).safeTransfer(msg.sender, amount); unsafeSubtractFromBalance(msg.sender, token, amount); emit Withdraw(msg.sender, token, amount); } function collectTokens(address token) external nonReentrant onlyDelegate { uint256 amountToCollect = IERC20(token).balanceOf(address(this)).sub(userTokenBalances[TOTAL][token]); // only collect if 1) there are tokens to collect & 2) token is whitelisted require(amountToCollect > 0, "!amount"); require(tokenWhitelist[token], "!whitelisted"); if (userTokenBalances[GUILD][token] == 0 && totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT) {totalGuildBankTokens += 1;} unsafeAddToBalance(GUILD, token, amountToCollect); emit TokensCollected(token, amountToCollect); } // NOTE: requires that delegate key which sent the original proposal cancels, msg.sender = proposal.proposer function cancelProposal(uint256 proposalId) external nonReentrant { Proposal storage proposal = proposals[proposalId]; require(proposal.flags[0] == 0, "sponsored"); require(proposal.flags[3] == 0, "cancelled"); require(msg.sender == proposal.proposer, "!proposer"); proposal.flags[3] = 1; // cancelled unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered); emit CancelProposal(proposalId, msg.sender); } function updateDelegateKey(address newDelegateKey) external { require(members[msg.sender].shares > 0, "!shareholder"); require(newDelegateKey != address(0), "newDelegateKey = 0"); // skip checks if member is setting the delegate key to their member address if (newDelegateKey != msg.sender) { require(members[newDelegateKey].exists == 0, "!overwrite members"); require(members[memberAddressByDelegateKey[newDelegateKey]].exists == 0, "!overwrite keys"); } Member storage member = members[msg.sender]; memberAddressByDelegateKey[member.delegateKey] = address(0); memberAddressByDelegateKey[newDelegateKey] = msg.sender; member.delegateKey = newDelegateKey; emit UpdateDelegateKey(msg.sender, newDelegateKey); } // can only ragequit if the latest proposal you voted YES on has been processed function canRagequit(uint256 highestIndexYesVote) public view returns (bool) { require(highestIndexYesVote < proposalQueue.length, "!proposal"); return proposals[proposalQueue[highestIndexYesVote]].flags[1] == 1; } function hasVotingPeriodExpired(uint256 startingPeriod) public view returns (bool) { return getCurrentPeriod() >= startingPeriod.add(votingPeriodLength); } /*************** GETTER FUNCTIONS ***************/ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x >= y ? x : y; } function getCurrentPeriod() public view returns (uint256) { return now.sub(summoningTime).div(periodDuration); } function getMemberProposalVote(address memberAddress, uint256 proposalIndex) external view returns (Vote) { require(members[memberAddress].exists == 1, "!member"); require(proposalIndex < proposalQueue.length, "!proposed"); return proposals[proposalQueue[proposalIndex]].votesByMember[memberAddress]; } function getProposalFlags(uint256 proposalId) external view returns (uint8[9] memory) { return proposals[proposalId].flags; } function getProposalQueueLength() external view returns (uint256) { return proposalQueue.length; } function getTokenCount() external view returns (uint256) { return approvedTokens.length; } function getUserTokenBalance(address user, address token) external view returns (uint256) { return userTokenBalances[user][token]; } /*************** HELPER FUNCTIONS ***************/ receive() external payable {} function fairShare(uint256 balance, uint256 shares, uint256 totalSharesAndLoot) internal pure returns (uint256) { require(totalSharesAndLoot != 0); if (balance == 0) { return 0; } uint256 prod = balance * shares; if (prod / balance == shares) { // no overflow in multiplication above? return prod / totalSharesAndLoot; } return (balance / totalSharesAndLoot) * shares; } function growGuild(address account, uint256 shares, uint256 loot) internal { // if the account is already a member, add to their existing shares & loot if (members[account].exists == 1) { members[account].shares = members[account].shares.add(shares); members[account].loot = members[account].loot.add(loot); // if the account is a new member, create a new record for them } else { // if new member is already taken by a member's delegateKey, reset it to their member address if (members[memberAddressByDelegateKey[account]].exists == 1) { address memberToOverride = memberAddressByDelegateKey[account]; memberAddressByDelegateKey[memberToOverride] = memberToOverride; members[memberToOverride].delegateKey = memberToOverride; } members[account] = Member({ delegateKey : account, exists : 1, // 'true' shares : shares, loot : loot.add(members[account].loot), // take into account loot from pre-membership transfers highestIndexYesVote : 0, jailed : 0 }); memberAddressByDelegateKey[account] = account; } uint256 sharesAndLoot = shares.add(loot); // mint new guild token, update total shares & loot balanceOf[account] = balanceOf[account].add(sharesAndLoot); totalShares = totalShares.add(shares); totalLoot = totalLoot.add(loot); totalSupply = totalShares.add(totalLoot); emit Transfer(address(0), account, sharesAndLoot); } function unsafeAddToBalance(address user, address token, uint256 amount) internal { userTokenBalances[user][token] += amount; userTokenBalances[TOTAL][token] += amount; } function unsafeInternalTransfer(address from, address to, address token, uint256 amount) internal { unsafeSubtractFromBalance(from, token, amount); unsafeAddToBalance(to, token, amount); } function unsafeSubtractFromBalance(address user, address token, uint256 amount) internal { userTokenBalances[user][token] -= amount; userTokenBalances[TOTAL][token] -= amount; } /******************** GUILD TOKEN FUNCTIONS ********************/ function approve(address spender, uint256 amount) external returns (bool) { require(amount == 0 || allowance[msg.sender][spender] == 0); allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function convertSharesToLoot(uint256 sharesToLoot) external nonReentrant { members[msg.sender].shares = members[msg.sender].shares.sub(sharesToLoot); members[msg.sender].loot = members[msg.sender].loot.add(sharesToLoot); totalShares = totalShares.sub(sharesToLoot); totalLoot = totalLoot.add(sharesToLoot); emit ConvertSharesToLoot(msg.sender, sharesToLoot); } function stakeTokenForShares(uint256 amount) external nonReentrant { IERC20(stakeToken).safeTransferFrom(msg.sender, address(this), amount); // deposit stake token & claim shares (1:1) growGuild(msg.sender, amount, 0); require(totalSupply <= MAX_GUILD_BOUND, "guild maxed"); emit StakeTokenForShares(msg.sender, amount); } function transfer(address recipient, uint256 lootToTransfer) external returns (bool) { members[msg.sender].loot = members[msg.sender].loot.sub(lootToTransfer); members[recipient].loot = members[recipient].loot.add(lootToTransfer); balanceOf[msg.sender] = balanceOf[msg.sender].sub(lootToTransfer); balanceOf[recipient] = balanceOf[recipient].add(lootToTransfer); emit Transfer(msg.sender, recipient, lootToTransfer); return true; } function transferFrom(address sender, address recipient, uint256 lootToTransfer) external returns (bool) { allowance[sender][msg.sender] = allowance[sender][msg.sender].sub(lootToTransfer); members[sender].loot = members[sender].loot.sub(lootToTransfer); members[recipient].loot = members[recipient].loot.add(lootToTransfer); balanceOf[sender] = balanceOf[sender].sub(lootToTransfer); balanceOf[recipient] = balanceOf[recipient].add(lootToTransfer); emit Transfer(sender, recipient, lootToTransfer); return true; } } /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. 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 CloneFactory { // MSTX implementation of eip-1167 - see https://eips.ethereum.org/EIPS/eip-1167 function createClone(address payable target) internal returns (address payable result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) } } } contract MSTXSummoner is CloneFactory { address payable public immutable template; constructor(address payable _template) public { template = _template; } event SummonMSTX(address indexed mstx, address depositToken, address stakeToken, address[] summoner, uint256[] summonerShares, uint256 summoningDeposit, uint256 proposalDeposit, uint256 processingReward, uint256 periodDuration, uint256 votingPeriodLength, uint256 gracePeriodLength, uint256 dilutionBound, uint256 summoningTime); function summonMSTX( address _depositToken, address _stakeToken, address[] memory _summoner, uint256[] memory _summonerShares, uint256 _summonerDeposit, uint256 _proposalDeposit, uint256 _processingReward, uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _dilutionBound ) external returns (address) { MSTX mstx = MSTX(createClone(template)); mstx.init( _depositToken, _stakeToken, _summoner, _summonerShares, _summonerDeposit, _proposalDeposit, _processingReward, _periodDuration, _votingPeriodLength, _gracePeriodLength, _dilutionBound ); require(IERC20(_depositToken).transferFrom(msg.sender, address(mstx), _summonerDeposit), "!transfer"); // transfer summoner deposit to new MSTX emit SummonMSTX(address(mstx), _depositToken, _stakeToken, _summoner, _summonerShares, _summonerDeposit, _proposalDeposit, _processingReward, _periodDuration, _votingPeriodLength, _gracePeriodLength, _dilutionBound, now); return address(mstx); } }
if the account is already a member, add to their existing shares & loot
function growGuild(address account, uint256 shares, uint256 loot) internal { if (members[account].exists == 1) { members[account].shares = members[account].shares.add(shares); members[account].loot = members[account].loot.add(loot); if (members[memberAddressByDelegateKey[account]].exists == 1) { address memberToOverride = memberAddressByDelegateKey[account]; memberAddressByDelegateKey[memberToOverride] = memberToOverride; members[memberToOverride].delegateKey = memberToOverride; } members[account] = Member({ delegateKey : account, shares : shares, highestIndexYesVote : 0, jailed : 0 }); memberAddressByDelegateKey[account] = account; } uint256 sharesAndLoot = shares.add(loot); totalShares = totalShares.add(shares); totalLoot = totalLoot.add(loot); totalSupply = totalShares.add(totalLoot); emit Transfer(address(0), account, sharesAndLoot); } else { if (members[account].exists == 1) { members[account].shares = members[account].shares.add(shares); members[account].loot = members[account].loot.add(loot); if (members[memberAddressByDelegateKey[account]].exists == 1) { address memberToOverride = memberAddressByDelegateKey[account]; memberAddressByDelegateKey[memberToOverride] = memberToOverride; members[memberToOverride].delegateKey = memberToOverride; } members[account] = Member({ delegateKey : account, shares : shares, highestIndexYesVote : 0, jailed : 0 }); memberAddressByDelegateKey[account] = account; } uint256 sharesAndLoot = shares.add(loot); totalShares = totalShares.add(shares); totalLoot = totalLoot.add(loot); totalSupply = totalShares.add(totalLoot); emit Transfer(address(0), account, sharesAndLoot); if (members[account].exists == 1) { members[account].shares = members[account].shares.add(shares); members[account].loot = members[account].loot.add(loot); if (members[memberAddressByDelegateKey[account]].exists == 1) { address memberToOverride = memberAddressByDelegateKey[account]; memberAddressByDelegateKey[memberToOverride] = memberToOverride; members[memberToOverride].delegateKey = memberToOverride; } members[account] = Member({ delegateKey : account, shares : shares, highestIndexYesVote : 0, jailed : 0 }); memberAddressByDelegateKey[account] = account; } uint256 sharesAndLoot = shares.add(loot); totalShares = totalShares.add(shares); totalLoot = totalLoot.add(loot); totalSupply = totalShares.add(totalLoot); emit Transfer(address(0), account, sharesAndLoot); balanceOf[account] = balanceOf[account].add(sharesAndLoot); }
1,235,876
[ 1, 430, 326, 2236, 353, 1818, 279, 3140, 16, 527, 358, 3675, 2062, 24123, 473, 437, 352, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 13334, 43, 680, 12, 2867, 2236, 16, 2254, 5034, 24123, 16, 2254, 5034, 437, 352, 13, 2713, 288, 203, 3639, 309, 261, 7640, 63, 4631, 8009, 1808, 422, 404, 13, 288, 203, 5411, 4833, 63, 4631, 8009, 30720, 273, 4833, 63, 4631, 8009, 30720, 18, 1289, 12, 30720, 1769, 203, 5411, 4833, 63, 4631, 8009, 383, 352, 273, 4833, 63, 4631, 8009, 383, 352, 18, 1289, 12, 383, 352, 1769, 203, 203, 5411, 309, 261, 7640, 63, 5990, 1887, 858, 9586, 653, 63, 4631, 65, 8009, 1808, 422, 404, 13, 288, 203, 7734, 1758, 3140, 774, 6618, 273, 3140, 1887, 858, 9586, 653, 63, 4631, 15533, 203, 7734, 3140, 1887, 858, 9586, 653, 63, 5990, 774, 6618, 65, 273, 3140, 774, 6618, 31, 203, 7734, 4833, 63, 5990, 774, 6618, 8009, 22216, 653, 273, 3140, 774, 6618, 31, 203, 5411, 289, 203, 540, 203, 5411, 4833, 63, 4631, 65, 273, 8596, 12590, 203, 7734, 7152, 653, 294, 2236, 16, 203, 7734, 24123, 294, 24123, 16, 203, 7734, 9742, 1016, 22352, 19338, 294, 374, 16, 203, 7734, 525, 1708, 294, 374, 203, 5411, 15549, 203, 5411, 3140, 1887, 858, 9586, 653, 63, 4631, 65, 273, 2236, 31, 203, 3639, 289, 203, 540, 203, 3639, 2254, 5034, 24123, 1876, 1504, 352, 273, 24123, 18, 1289, 12, 383, 352, 1769, 203, 3639, 2078, 24051, 273, 2078, 24051, 18, 1289, 12, 30720, 1769, 203, 3639, 2078, 1504, 352, 273, 2078, 1504, 352, 18, 1289, 12, 383, 352, 1769, 203, 3639, 2078, 3088, 1283, 273, 2078, 24051, 2 ]
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {PercentageMath} from '../protocol/libraries/math/PercentageMath.sol'; import {SafeMath} from '../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IERC20WithPermit} from '../interfaces/IERC20WithPermit.sol'; import {FlashLoanReceiverBase} from '../flashloan/base/FlashLoanReceiverBase.sol'; import {IBaseUniswapAdapter} from './interfaces/IBaseUniswapAdapter.sol'; /** * @title BaseUniswapAdapter * @notice Implements the logic for performing assets swaps in Uniswap V2 * @author Aave **/ abstract contract BaseUniswapAdapter is FlashLoanReceiverBase, IBaseUniswapAdapter, Ownable { using SafeMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; // Max slippage percent allowed uint256 public constant override MAX_SLIPPAGE_PERCENT = 3000; // 30% // FLash Loan fee set in lending pool uint256 public constant override FLASHLOAN_PREMIUM_TOTAL = 9; // USD oracle asset address address public constant override USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96; address public immutable override WETH_ADDRESS; IPriceOracleGetter public immutable override ORACLE; IUniswapV2Router02 public immutable override UNISWAP_ROUTER; constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public FlashLoanReceiverBase(addressesProvider) { ORACLE = IPriceOracleGetter(addressesProvider.getPriceOracle()); UNISWAP_ROUTER = uniswapRouter; WETH_ADDRESS = wethAddress; } /** * @dev Given an input asset amount, returns the maximum output amount of the other asset and the prices * @param amountIn Amount of reserveIn * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount out of the reserveOut * @return uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function getAmountsOut( uint256 amountIn, address reserveIn, address reserveOut ) external view override returns ( uint256, uint256, uint256, uint256, address[] memory ) { AmountCalc memory results = _getAmountsOutData(reserveIn, reserveOut, amountIn); return ( results.calculatedAmount, results.relativePrice, results.amountInUsd, results.amountOutUsd, results.path ); } /** * @dev Returns the minimum input asset amount required to buy the given output asset amount and the prices * @param amountOut Amount of reserveOut * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount in of the reserveIn * @return uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function getAmountsIn( uint256 amountOut, address reserveIn, address reserveOut ) external view override returns ( uint256, uint256, uint256, uint256, address[] memory ) { AmountCalc memory results = _getAmountsInData(reserveIn, reserveOut, amountOut); return ( results.calculatedAmount, results.relativePrice, results.amountInUsd, results.amountOutUsd, results.path ); } /** * @dev Swaps an exact `amountToSwap` of an asset to another * @param assetToSwapFrom Origin asset * @param assetToSwapTo Destination asset * @param amountToSwap Exact amount of `assetToSwapFrom` to be swapped * @param minAmountOut the min amount of `assetToSwapTo` to be received from the swap * @return the amount received from the swap */ function _swapExactTokensForTokens( address assetToSwapFrom, address assetToSwapTo, uint256 amountToSwap, uint256 minAmountOut, bool useEthPath ) internal returns (uint256) { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(assetToSwapFrom); uint256 toAssetPrice = _getPrice(assetToSwapTo); uint256 expectedMinAmountOut = amountToSwap .mul(fromAssetPrice.mul(10**toAssetDecimals)) .div(toAssetPrice.mul(10**fromAssetDecimals)) .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(MAX_SLIPPAGE_PERCENT)); require(expectedMinAmountOut < minAmountOut, 'minAmountOut exceed max slippage'); // Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), amountToSwap); address[] memory path; if (useEthPath) { path = new address[](3); path[0] = assetToSwapFrom; path[1] = WETH_ADDRESS; path[2] = assetToSwapTo; } else { path = new address[](2); path[0] = assetToSwapFrom; path[1] = assetToSwapTo; } uint256[] memory amounts = UNISWAP_ROUTER.swapExactTokensForTokens( amountToSwap, minAmountOut, path, address(this), block.timestamp ); emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]); return amounts[amounts.length - 1]; } /** * @dev Receive an exact amount `amountToReceive` of `assetToSwapTo` tokens for as few `assetToSwapFrom` tokens as * possible. * @param assetToSwapFrom Origin asset * @param assetToSwapTo Destination asset * @param maxAmountToSwap Max amount of `assetToSwapFrom` allowed to be swapped * @param amountToReceive Exact amount of `assetToSwapTo` to receive * @return the amount swapped */ function _swapTokensForExactTokens( address assetToSwapFrom, address assetToSwapTo, uint256 maxAmountToSwap, uint256 amountToReceive, bool useEthPath ) internal returns (uint256) { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(assetToSwapFrom); uint256 toAssetPrice = _getPrice(assetToSwapTo); uint256 expectedMaxAmountToSwap = amountToReceive .mul(toAssetPrice.mul(10**fromAssetDecimals)) .div(fromAssetPrice.mul(10**toAssetDecimals)) .percentMul(PercentageMath.PERCENTAGE_FACTOR.add(MAX_SLIPPAGE_PERCENT)); require(maxAmountToSwap < expectedMaxAmountToSwap, 'maxAmountToSwap exceed max slippage'); // Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), maxAmountToSwap); address[] memory path; if (useEthPath) { path = new address[](3); path[0] = assetToSwapFrom; path[1] = WETH_ADDRESS; path[2] = assetToSwapTo; } else { path = new address[](2); path[0] = assetToSwapFrom; path[1] = assetToSwapTo; } uint256[] memory amounts = UNISWAP_ROUTER.swapTokensForExactTokens( amountToReceive, maxAmountToSwap, path, address(this), block.timestamp ); emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]); return amounts[0]; } /** * @dev Get the price of the asset from the oracle denominated in eth * @param asset address * @return eth price for the asset */ function _getPrice(address asset) internal view returns (uint256) { return ORACLE.getAssetPrice(asset); } /** * @dev Get the decimals of an asset * @return number of decimals of the asset */ function _getDecimals(address asset) internal view returns (uint256) { return IERC20Detailed(asset).decimals(); } /** * @dev Get the aToken associated to the asset * @return address of the aToken */ function _getReserveData(address asset) internal view returns (DataTypes.ReserveData memory) { return LENDING_POOL.getReserveData(asset); } /** * @dev Pull the ATokens from the user * @param reserve address of the asset * @param reserveAToken address of the aToken of the reserve * @param user address * @param amount of tokens to be transferred to the contract * @param permitSignature struct containing the permit signature */ function _pullAToken( address reserve, address reserveAToken, address user, uint256 amount, PermitSignature memory permitSignature ) internal { if (_usePermit(permitSignature)) { IERC20WithPermit(reserveAToken).permit( user, address(this), permitSignature.amount, permitSignature.deadline, permitSignature.v, permitSignature.r, permitSignature.s ); } // transfer from user to adapter IERC20(reserveAToken).safeTransferFrom(user, address(this), amount); // withdraw reserve LENDING_POOL.withdraw(reserve, amount, address(this)); } /** * @dev Tells if the permit method should be called by inspecting if there is a valid signature. * If signature params are set to 0, then permit won't be called. * @param signature struct containing the permit signature * @return whether or not permit should be called */ function _usePermit(PermitSignature memory signature) internal pure returns (bool) { return !(uint256(signature.deadline) == uint256(signature.v) && uint256(signature.deadline) == 0); } /** * @dev Calculates the value denominated in USD * @param reserve Address of the reserve * @param amount Amount of the reserve * @param decimals Decimals of the reserve * @return whether or not permit should be called */ function _calcUsdValue( address reserve, uint256 amount, uint256 decimals ) internal view returns (uint256) { uint256 ethUsdPrice = _getPrice(USD_ADDRESS); uint256 reservePrice = _getPrice(reserve); return amount.mul(reservePrice).div(10**decimals).mul(ethUsdPrice).div(10**18); } /** * @dev Given an input asset amount, returns the maximum output amount of the other asset * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountIn Amount of reserveIn * @return Struct containing the following information: * uint256 Amount out of the reserveOut * uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * uint256 In amount of reserveIn value denominated in USD (8 decimals) * uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function _getAmountsOutData( address reserveIn, address reserveOut, uint256 amountIn ) internal view returns (AmountCalc memory) { // Subtract flash loan fee uint256 finalAmountIn = amountIn.sub(amountIn.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); if (reserveIn == reserveOut) { uint256 reserveDecimals = _getDecimals(reserveIn); address[] memory path = new address[](1); path[0] = reserveIn; return AmountCalc( finalAmountIn, finalAmountIn.mul(10**18).div(amountIn), _calcUsdValue(reserveIn, amountIn, reserveDecimals), _calcUsdValue(reserveIn, finalAmountIn, reserveDecimals), path ); } address[] memory simplePath = new address[](2); simplePath[0] = reserveIn; simplePath[1] = reserveOut; uint256[] memory amountsWithoutWeth; uint256[] memory amountsWithWeth; address[] memory pathWithWeth = new address[](3); if (reserveIn != WETH_ADDRESS && reserveOut != WETH_ADDRESS) { pathWithWeth[0] = reserveIn; pathWithWeth[1] = WETH_ADDRESS; pathWithWeth[2] = reserveOut; try UNISWAP_ROUTER.getAmountsOut(finalAmountIn, pathWithWeth) returns ( uint256[] memory resultsWithWeth ) { amountsWithWeth = resultsWithWeth; } catch { amountsWithWeth = new uint256[](3); } } else { amountsWithWeth = new uint256[](3); } uint256 bestAmountOut; try UNISWAP_ROUTER.getAmountsOut(finalAmountIn, simplePath) returns ( uint256[] memory resultAmounts ) { amountsWithoutWeth = resultAmounts; bestAmountOut = (amountsWithWeth[2] > amountsWithoutWeth[1]) ? amountsWithWeth[2] : amountsWithoutWeth[1]; } catch { amountsWithoutWeth = new uint256[](2); bestAmountOut = amountsWithWeth[2]; } uint256 reserveInDecimals = _getDecimals(reserveIn); uint256 reserveOutDecimals = _getDecimals(reserveOut); uint256 outPerInPrice = finalAmountIn.mul(10**18).mul(10**reserveOutDecimals).div( bestAmountOut.mul(10**reserveInDecimals) ); return AmountCalc( bestAmountOut, outPerInPrice, _calcUsdValue(reserveIn, amountIn, reserveInDecimals), _calcUsdValue(reserveOut, bestAmountOut, reserveOutDecimals), (bestAmountOut == 0) ? new address[](2) : (bestAmountOut == amountsWithoutWeth[1]) ? simplePath : pathWithWeth ); } /** * @dev Returns the minimum input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return Struct containing the following information: * uint256 Amount in of the reserveIn * uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * uint256 In amount of reserveIn value denominated in USD (8 decimals) * uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function _getAmountsInData( address reserveIn, address reserveOut, uint256 amountOut ) internal view returns (AmountCalc memory) { if (reserveIn == reserveOut) { // Add flash loan fee uint256 amountIn = amountOut.add(amountOut.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); uint256 reserveDecimals = _getDecimals(reserveIn); address[] memory path = new address[](1); path[0] = reserveIn; return AmountCalc( amountIn, amountOut.mul(10**18).div(amountIn), _calcUsdValue(reserveIn, amountIn, reserveDecimals), _calcUsdValue(reserveIn, amountOut, reserveDecimals), path ); } (uint256[] memory amounts, address[] memory path) = _getAmountsInAndPath(reserveIn, reserveOut, amountOut); // Add flash loan fee uint256 finalAmountIn = amounts[0].add(amounts[0].mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); uint256 reserveInDecimals = _getDecimals(reserveIn); uint256 reserveOutDecimals = _getDecimals(reserveOut); uint256 inPerOutPrice = amountOut.mul(10**18).mul(10**reserveInDecimals).div( finalAmountIn.mul(10**reserveOutDecimals) ); return AmountCalc( finalAmountIn, inPerOutPrice, _calcUsdValue(reserveIn, finalAmountIn, reserveInDecimals), _calcUsdValue(reserveOut, amountOut, reserveOutDecimals), path ); } /** * @dev Calculates the input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return uint256[] amounts Array containing the amountIn and amountOut for a swap */ function _getAmountsInAndPath( address reserveIn, address reserveOut, uint256 amountOut ) internal view returns (uint256[] memory, address[] memory) { address[] memory simplePath = new address[](2); simplePath[0] = reserveIn; simplePath[1] = reserveOut; uint256[] memory amountsWithoutWeth; uint256[] memory amountsWithWeth; address[] memory pathWithWeth = new address[](3); if (reserveIn != WETH_ADDRESS && reserveOut != WETH_ADDRESS) { pathWithWeth[0] = reserveIn; pathWithWeth[1] = WETH_ADDRESS; pathWithWeth[2] = reserveOut; try UNISWAP_ROUTER.getAmountsIn(amountOut, pathWithWeth) returns ( uint256[] memory resultsWithWeth ) { amountsWithWeth = resultsWithWeth; } catch { amountsWithWeth = new uint256[](3); } } else { amountsWithWeth = new uint256[](3); } try UNISWAP_ROUTER.getAmountsIn(amountOut, simplePath) returns ( uint256[] memory resultAmounts ) { amountsWithoutWeth = resultAmounts; return (amountsWithWeth[0] < amountsWithoutWeth[0] && amountsWithWeth[0] != 0) ? (amountsWithWeth, pathWithWeth) : (amountsWithoutWeth, simplePath); } catch { return (amountsWithWeth, pathWithWeth); } } /** * @dev Calculates the input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return uint256[] amounts Array containing the amountIn and amountOut for a swap */ function _getAmountsIn( address reserveIn, address reserveOut, uint256 amountOut, bool useEthPath ) internal view returns (uint256[] memory) { address[] memory path; if (useEthPath) { path = new address[](3); path[0] = reserveIn; path[1] = WETH_ADDRESS; path[2] = reserveOut; } else { path = new address[](2); path[0] = reserveIn; path[1] = reserveOut; } return UNISWAP_ROUTER.getAmountsIn(amountOut, path); } /** * @dev Emergency rescue for token stucked on this contract, as failsafe mechanism * - Funds should never remain in this contract more time than during transactions * - Only callable by the owner **/ function rescueTokens(IERC20 token) external onlyOwner { token.transfer(owner(), token.balanceOf(address(this))); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title PercentageMath library * @author Aave * @notice Provides functions to perform percentage calculations * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR * @dev Operations are rounded half up **/ library PercentageMath { uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2; /** * @dev Executes a percentage multiplication * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The percentage of value **/ function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) { if (value == 0 || percentage == 0) { return 0; } require( value <= (type(uint256).max - HALF_PERCENT) / percentage, Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR; } /** * @dev Executes a percentage division * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The value divided the percentage **/ function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) { require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfPercentage = percentage / 2; require( value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library 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; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @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: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from './IERC20.sol'; interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import {IERC20} from './IERC20.sol'; import {SafeMath} from './SafeMath.sol'; import {Address} from './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)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import './Context.sol'; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), 'Ownable: new owner is the zero address'); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IUniswapV2Router02 { 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 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); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IPriceOracleGetter interface * @notice Interface for the Aave price oracle. **/ interface IPriceOracleGetter { /** * @dev returns the asset price in ETH * @param asset the address of the asset * @return the ETH price of the asset **/ function getAssetPrice(address asset) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; interface IERC20WithPermit is IERC20 { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {IFlashLoanReceiver} from '../interfaces/IFlashLoanReceiver.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for IERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public immutable override ADDRESSES_PROVIDER; ILendingPool public immutable override LENDING_POOL; constructor(ILendingPoolAddressesProvider provider) public { ADDRESSES_PROVIDER = provider; LENDING_POOL = ILendingPool(provider.getLendingPool()); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {IUniswapV2Router02} from '../../interfaces/IUniswapV2Router02.sol'; interface IBaseUniswapAdapter { event Swapped(address fromAsset, address toAsset, uint256 fromAmount, uint256 receivedAmount); struct PermitSignature { uint256 amount; uint256 deadline; uint8 v; bytes32 r; bytes32 s; } struct AmountCalc { uint256 calculatedAmount; uint256 relativePrice; uint256 amountInUsd; uint256 amountOutUsd; address[] path; } function WETH_ADDRESS() external returns (address); function MAX_SLIPPAGE_PERCENT() external returns (uint256); function FLASHLOAN_PREMIUM_TOTAL() external returns (uint256); function USD_ADDRESS() external returns (address); function ORACLE() external returns (IPriceOracleGetter); function UNISWAP_ROUTER() external returns (IUniswapV2Router02); /** * @dev Given an input asset amount, returns the maximum output amount of the other asset and the prices * @param amountIn Amount of reserveIn * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount out of the reserveOut * @return uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) * @return address[] The exchange path */ function getAmountsOut( uint256 amountIn, address reserveIn, address reserveOut ) external view returns ( uint256, uint256, uint256, uint256, address[] memory ); /** * @dev Returns the minimum input asset amount required to buy the given output asset amount and the prices * @param amountOut Amount of reserveOut * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount in of the reserveIn * @return uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) * @return address[] The exchange path */ function getAmountsIn( uint256 amountOut, address reserveIn, address reserveOut ) external view returns ( uint256, uint256, uint256, uint256, address[] memory ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title Errors library * @author Aave * @notice Defines the error messages emitted by the different contracts of the Aave protocol * @dev Error messages prefix glossary: * - VL = ValidationLogic * - MATH = Math libraries * - CT = Common errors between tokens (AToken, VariableDebtToken and StableDebtToken) * - AT = AToken * - SDT = StableDebtToken * - VDT = VariableDebtToken * - LP = LendingPool * - LPAPR = LendingPoolAddressesProviderRegistry * - LPC = LendingPoolConfiguration * - RL = ReserveLogic * - LPCM = LendingPoolCollateralManager * - P = Pausable */ library Errors { //common errors string public constant CALLER_NOT_POOL_ADMIN = '33'; // 'The caller must be the pool admin' string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small //contract specific errors string public constant VL_INVALID_AMOUNT = '1'; // 'Amount must be greater than 0' string public constant VL_NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve' string public constant VL_RESERVE_FROZEN = '3'; // 'Action cannot be performed because the reserve is frozen' string public constant VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough' string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance' string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.' string public constant VL_BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled' string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected' string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0' string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold' string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow' string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt' string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed' string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve' string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve' string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0' string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral' string public constant LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve' string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met' string public constant LP_LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed' string public constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow' string public constant LP_REQUESTED_AMOUNT_TOO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.' string public constant LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent' string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // 'The caller of the function is not the lending pool configurator' string public constant LP_INCONSISTENT_FLASHLOAN_PARAMS = '28'; string public constant CT_CALLER_MUST_BE_LENDING_POOL = '29'; // 'The caller of this function must be a lending pool' string public constant CT_CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself' string public constant CT_TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero' string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // 'Reserve has already been initialized' string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ATOKEN_POOL_ADDRESS = '35'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = '36'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = '37'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '38'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '39'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = '40'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_CONFIGURATION = '75'; // 'Invalid risk parameters for the reserve' string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = '76'; // 'The caller must be the emergency admin' string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // 'Provider is not registered' string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // 'Health factor is not below the threshold' string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // 'The collateral chosen cannot be liquidated' string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // 'User did not borrow the specified currency' string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // "There isn't enough liquidity available to liquidate" string public constant LPCM_NO_ERRORS = '46'; // 'No errors' string public constant LP_INVALID_FLASHLOAN_MODE = '47'; //Invalid flashloan mode selected string public constant MATH_MULTIPLICATION_OVERFLOW = '48'; string public constant MATH_ADDITION_OVERFLOW = '49'; string public constant MATH_DIVISION_BY_ZERO = '50'; string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128 string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128 string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128 string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128 string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128 string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint string public constant LP_FAILED_REPAY_WITH_COLLATERAL = '57'; string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn string public constant LP_FAILED_COLLATERAL_SWAP = '60'; string public constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = '61'; string public constant LP_REENTRANCY_NOT_ALLOWED = '62'; string public constant LP_CALLER_MUST_BE_AN_ATOKEN = '63'; string public constant LP_IS_PAUSED = '64'; // 'Pool is paused' string public constant LP_NO_MORE_RESERVES_ALLOWED = '65'; string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66'; string public constant RC_INVALID_LTV = '67'; string public constant RC_INVALID_LIQ_THRESHOLD = '68'; string public constant RC_INVALID_LIQ_BONUS = '69'; string public constant RC_INVALID_DECIMALS = '70'; string public constant RC_INVALID_RESERVE_FACTOR = '71'; string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72'; string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73'; string public constant LP_INCONSISTENT_PARAMS_LENGTH = '74'; string public constant UL_INVALID_INDEX = '77'; string public constant LP_NOT_CONTRACT = '78'; string public constant SDT_STABLE_DEBT_OVERFLOW = '79'; string public constant SDT_BURN_EXCEEDS_BALANCE = '80'; enum CollateralManagerErrors { NO_ERROR, NO_COLLATERAL_AVAILABLE, COLLATERAL_CANNOT_BE_LIQUIDATED, CURRRENCY_NOT_BORROWED, HEALTH_FACTOR_ABOVE_THRESHOLD, NOT_ENOUGH_LIQUIDITY, NO_ACTIVE_RESERVE, HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD, INVALID_EQUAL_ASSETS_TO_SWAP, FROZEN_RESERVE } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @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'); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract 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: agpl-3.0 pragma solidity 0.6.12; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; /** * @title IFlashLoanReceiver interface * @notice Interface for the Aave fee IFlashLoanReceiver. * @author Aave * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external returns (bool); function ADDRESSES_PROVIDER() external view returns (ILendingPoolAddressesProvider); function LENDING_POOL() external view returns (ILendingPool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProvider} from './ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; interface ILendingPool { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; /** * @title UniswapRepayAdapter * @notice Uniswap V2 Adapter to perform a repay of a debt with collateral. * @author Aave **/ contract UniswapRepayAdapter is BaseUniswapAdapter { struct RepayParams { address collateralAsset; uint256 collateralAmount; uint256 rateMode; PermitSignature permitSignature; bool useEthPath; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Uses the received funds from the flash loan to repay a debt on the protocol on behalf of the user. Then pulls * the collateral from the user and swaps it to the debt asset to repay the flash loan. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset, swap it * and repay the flash loan. * Supports only one asset on the flash loan. * @param assets Address of debt asset * @param amounts Amount of the debt to be repaid * @param premiums Fee of the flash loan * @param initiator Address of the user * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset Address of the reserve to be swapped * uint256 collateralAmount Amount of reserve to be swapped * uint256 rateMode Rate modes of the debt to be repaid * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v V param for the permit signature * bytes32 r R param for the permit signature * bytes32 s S param for the permit signature */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); RepayParams memory decodedParams = _decodeParams(params); _swapAndRepay( decodedParams.collateralAsset, assets[0], amounts[0], decodedParams.collateralAmount, decodedParams.rateMode, initiator, premiums[0], decodedParams.permitSignature, decodedParams.useEthPath ); return true; } /** * @dev Swaps the user collateral for the debt asset and then repay the debt on the protocol on behalf of the user * without using flash loans. This method can be used when the temporary transfer of the collateral asset to this * contract does not affect the user position. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset * @param collateralAsset Address of asset to be swapped * @param debtAsset Address of debt asset * @param collateralAmount Amount of the collateral to be swapped * @param debtRepayAmount Amount of the debt to be repaid * @param debtRateMode Rate mode of the debt to be repaid * @param permitSignature struct containing the permit signature * @param useEthPath struct containing the permit signature */ function swapAndRepay( address collateralAsset, address debtAsset, uint256 collateralAmount, uint256 debtRepayAmount, uint256 debtRateMode, PermitSignature calldata permitSignature, bool useEthPath ) external { DataTypes.ReserveData memory collateralReserveData = _getReserveData(collateralAsset); DataTypes.ReserveData memory debtReserveData = _getReserveData(debtAsset); address debtToken = DataTypes.InterestRateMode(debtRateMode) == DataTypes.InterestRateMode.STABLE ? debtReserveData.stableDebtTokenAddress : debtReserveData.variableDebtTokenAddress; uint256 currentDebt = IERC20(debtToken).balanceOf(msg.sender); uint256 amountToRepay = debtRepayAmount <= currentDebt ? debtRepayAmount : currentDebt; if (collateralAsset != debtAsset) { uint256 maxCollateralToSwap = collateralAmount; if (amountToRepay < debtRepayAmount) { maxCollateralToSwap = maxCollateralToSwap.mul(amountToRepay).div(debtRepayAmount); } // Get exact collateral needed for the swap to avoid leftovers uint256[] memory amounts = _getAmountsIn(collateralAsset, debtAsset, amountToRepay, useEthPath); require(amounts[0] <= maxCollateralToSwap, 'slippage too high'); // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, msg.sender, amounts[0], permitSignature ); // Swap collateral for debt asset _swapTokensForExactTokens(collateralAsset, debtAsset, amounts[0], amountToRepay, useEthPath); } else { // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, msg.sender, amountToRepay, permitSignature ); } // Repay debt. Approves 0 first to comply with tokens that implement the anti frontrunning approval fix IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amountToRepay); LENDING_POOL.repay(debtAsset, amountToRepay, debtRateMode, msg.sender); } /** * @dev Perform the repay of the debt, pulls the initiator collateral and swaps to repay the flash loan * * @param collateralAsset Address of token to be swapped * @param debtAsset Address of debt token to be received from the swap * @param amount Amount of the debt to be repaid * @param collateralAmount Amount of the reserve to be swapped * @param rateMode Rate mode of the debt to be repaid * @param initiator Address of the user * @param premium Fee of the flash loan * @param permitSignature struct containing the permit signature */ function _swapAndRepay( address collateralAsset, address debtAsset, uint256 amount, uint256 collateralAmount, uint256 rateMode, address initiator, uint256 premium, PermitSignature memory permitSignature, bool useEthPath ) internal { DataTypes.ReserveData memory collateralReserveData = _getReserveData(collateralAsset); // Repay debt. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amount); uint256 repaidAmount = IERC20(debtAsset).balanceOf(address(this)); LENDING_POOL.repay(debtAsset, amount, rateMode, initiator); repaidAmount = repaidAmount.sub(IERC20(debtAsset).balanceOf(address(this))); if (collateralAsset != debtAsset) { uint256 maxCollateralToSwap = collateralAmount; if (repaidAmount < amount) { maxCollateralToSwap = maxCollateralToSwap.mul(repaidAmount).div(amount); } uint256 neededForFlashLoanDebt = repaidAmount.add(premium); uint256[] memory amounts = _getAmountsIn(collateralAsset, debtAsset, neededForFlashLoanDebt, useEthPath); require(amounts[0] <= maxCollateralToSwap, 'slippage too high'); // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, initiator, amounts[0], permitSignature ); // Swap collateral asset to the debt asset _swapTokensForExactTokens( collateralAsset, debtAsset, amounts[0], neededForFlashLoanDebt, useEthPath ); } else { // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, initiator, repaidAmount.add(premium), permitSignature ); } // Repay flashloan. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amount.add(premium)); } /** * @dev Decodes debt information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset Address of the reserve to be swapped * uint256 collateralAmount Amount of reserve to be swapped * uint256 rateMode Rate modes of the debt to be repaid * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v V param for the permit signature * bytes32 r R param for the permit signature * bytes32 s S param for the permit signature * bool useEthPath use WETH path route * @return RepayParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (RepayParams memory) { ( address collateralAsset, uint256 collateralAmount, uint256 rateMode, uint256 permitAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bool useEthPath ) = abi.decode( params, (address, uint256, uint256, uint256, uint256, uint8, bytes32, bytes32, bool) ); return RepayParams( collateralAsset, collateralAmount, rateMode, PermitSignature(permitAmount, deadline, v, r, s), useEthPath ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts//SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts//IERC20.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {ILendingPoolCollateralManager} from '../../interfaces/ILendingPoolCollateralManager.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {GenericLogic} from '../libraries/logic/GenericLogic.sol'; import {Helpers} from '../libraries/helpers/Helpers.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {LendingPoolStorage} from './LendingPoolStorage.sol'; /** * @title LendingPoolCollateralManager contract * @author Aave * @dev Implements actions involving management of collateral in the protocol, the main one being the liquidations * IMPORTANT This contract will run always via DELEGATECALL, through the LendingPool, so the chain of inheritance * is the same as the LendingPool, to have compatible storage layouts **/ contract LendingPoolCollateralManager is ILendingPoolCollateralManager, VersionedInitializable, LendingPoolStorage { using SafeERC20 for IERC20; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; uint256 internal constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 5000; struct LiquidationCallLocalVars { uint256 userCollateralBalance; uint256 userStableDebt; uint256 userVariableDebt; uint256 maxLiquidatableDebt; uint256 actualDebtToLiquidate; uint256 liquidationRatio; uint256 maxAmountCollateralToLiquidate; uint256 userStableRate; uint256 maxCollateralToLiquidate; uint256 debtAmountNeeded; uint256 healthFactor; uint256 liquidatorPreviousATokenBalance; IAToken collateralAtoken; bool isCollateralEnabled; DataTypes.InterestRateMode borrowRateMode; uint256 errorCode; string errorMsg; } /** * @dev As thIS contract extends the VersionedInitializable contract to match the state * of the LendingPool contract, the getRevision() function is needed, but the value is not * important, as the initialize() function will never be called here */ function getRevision() internal pure override returns (uint256) { return 0; } /** * @dev Function to liquidate a position if its Health Factor drops below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external override returns (uint256, string memory) { DataTypes.ReserveData storage collateralReserve = _reserves[collateralAsset]; DataTypes.ReserveData storage debtReserve = _reserves[debtAsset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[user]; LiquidationCallLocalVars memory vars; (, , , , vars.healthFactor) = GenericLogic.calculateUserAccountData( user, _reserves, userConfig, _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); (vars.userStableDebt, vars.userVariableDebt) = Helpers.getUserCurrentDebt(user, debtReserve); (vars.errorCode, vars.errorMsg) = ValidationLogic.validateLiquidationCall( collateralReserve, debtReserve, userConfig, vars.healthFactor, vars.userStableDebt, vars.userVariableDebt ); if (Errors.CollateralManagerErrors(vars.errorCode) != Errors.CollateralManagerErrors.NO_ERROR) { return (vars.errorCode, vars.errorMsg); } vars.collateralAtoken = IAToken(collateralReserve.aTokenAddress); vars.userCollateralBalance = vars.collateralAtoken.balanceOf(user); vars.maxLiquidatableDebt = vars.userStableDebt.add(vars.userVariableDebt).percentMul( LIQUIDATION_CLOSE_FACTOR_PERCENT ); vars.actualDebtToLiquidate = debtToCover > vars.maxLiquidatableDebt ? vars.maxLiquidatableDebt : debtToCover; ( vars.maxCollateralToLiquidate, vars.debtAmountNeeded ) = _calculateAvailableCollateralToLiquidate( collateralReserve, debtReserve, collateralAsset, debtAsset, vars.actualDebtToLiquidate, vars.userCollateralBalance ); // If debtAmountNeeded < actualDebtToLiquidate, there isn't enough // collateral to cover the actual amount that is being liquidated, hence we liquidate // a smaller amount if (vars.debtAmountNeeded < vars.actualDebtToLiquidate) { vars.actualDebtToLiquidate = vars.debtAmountNeeded; } // If the liquidator reclaims the underlying asset, we make sure there is enough available liquidity in the // collateral reserve if (!receiveAToken) { uint256 currentAvailableCollateral = IERC20(collateralAsset).balanceOf(address(vars.collateralAtoken)); if (currentAvailableCollateral < vars.maxCollateralToLiquidate) { return ( uint256(Errors.CollateralManagerErrors.NOT_ENOUGH_LIQUIDITY), Errors.LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE ); } } debtReserve.updateState(); if (vars.userVariableDebt >= vars.actualDebtToLiquidate) { IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn( user, vars.actualDebtToLiquidate, debtReserve.variableBorrowIndex ); } else { // If the user doesn't have variable debt, no need to try to burn variable debt tokens if (vars.userVariableDebt > 0) { IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn( user, vars.userVariableDebt, debtReserve.variableBorrowIndex ); } IStableDebtToken(debtReserve.stableDebtTokenAddress).burn( user, vars.actualDebtToLiquidate.sub(vars.userVariableDebt) ); } debtReserve.updateInterestRates( debtAsset, debtReserve.aTokenAddress, vars.actualDebtToLiquidate, 0 ); if (receiveAToken) { vars.liquidatorPreviousATokenBalance = IERC20(vars.collateralAtoken).balanceOf(msg.sender); vars.collateralAtoken.transferOnLiquidation(user, msg.sender, vars.maxCollateralToLiquidate); if (vars.liquidatorPreviousATokenBalance == 0) { DataTypes.UserConfigurationMap storage liquidatorConfig = _usersConfig[msg.sender]; liquidatorConfig.setUsingAsCollateral(collateralReserve.id, true); emit ReserveUsedAsCollateralEnabled(collateralAsset, msg.sender); } } else { collateralReserve.updateState(); collateralReserve.updateInterestRates( collateralAsset, address(vars.collateralAtoken), 0, vars.maxCollateralToLiquidate ); // Burn the equivalent amount of aToken, sending the underlying to the liquidator vars.collateralAtoken.burn( user, msg.sender, vars.maxCollateralToLiquidate, collateralReserve.liquidityIndex ); } // If the collateral being liquidated is equal to the user balance, // we set the currency as not being used as collateral anymore if (vars.maxCollateralToLiquidate == vars.userCollateralBalance) { userConfig.setUsingAsCollateral(collateralReserve.id, false); emit ReserveUsedAsCollateralDisabled(collateralAsset, user); } // Transfers the debt asset being repaid to the aToken, where the liquidity is kept IERC20(debtAsset).safeTransferFrom( msg.sender, debtReserve.aTokenAddress, vars.actualDebtToLiquidate ); emit LiquidationCall( collateralAsset, debtAsset, user, vars.actualDebtToLiquidate, vars.maxCollateralToLiquidate, msg.sender, receiveAToken ); return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS); } struct AvailableCollateralToLiquidateLocalVars { uint256 userCompoundedBorrowBalance; uint256 liquidationBonus; uint256 collateralPrice; uint256 debtAssetPrice; uint256 maxAmountCollateralToLiquidate; uint256 debtAssetDecimals; uint256 collateralDecimals; } /** * @dev Calculates how much of a specific collateral can be liquidated, given * a certain amount of debt asset. * - This function needs to be called after all the checks to validate the liquidation have been performed, * otherwise it might fail. * @param collateralReserve The data of the collateral reserve * @param debtReserve The data of the debt reserve * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param userCollateralBalance The collateral balance for the specific `collateralAsset` of the user being liquidated * @return collateralAmount: The maximum amount that is possible to liquidate given all the liquidation constraints * (user balance, close factor) * debtAmountNeeded: The amount to repay with the liquidation **/ function _calculateAvailableCollateralToLiquidate( DataTypes.ReserveData storage collateralReserve, DataTypes.ReserveData storage debtReserve, address collateralAsset, address debtAsset, uint256 debtToCover, uint256 userCollateralBalance ) internal view returns (uint256, uint256) { uint256 collateralAmount = 0; uint256 debtAmountNeeded = 0; IPriceOracleGetter oracle = IPriceOracleGetter(_addressesProvider.getPriceOracle()); AvailableCollateralToLiquidateLocalVars memory vars; vars.collateralPrice = oracle.getAssetPrice(collateralAsset); vars.debtAssetPrice = oracle.getAssetPrice(debtAsset); (, , vars.liquidationBonus, vars.collateralDecimals, ) = collateralReserve .configuration .getParams(); vars.debtAssetDecimals = debtReserve.configuration.getDecimals(); // This is the maximum possible amount of the selected collateral that can be liquidated, given the // max amount of liquidatable debt vars.maxAmountCollateralToLiquidate = vars .debtAssetPrice .mul(debtToCover) .mul(10**vars.collateralDecimals) .percentMul(vars.liquidationBonus) .div(vars.collateralPrice.mul(10**vars.debtAssetDecimals)); if (vars.maxAmountCollateralToLiquidate > userCollateralBalance) { collateralAmount = userCollateralBalance; debtAmountNeeded = vars .collateralPrice .mul(collateralAmount) .mul(10**vars.debtAssetDecimals) .div(vars.debtAssetPrice.mul(10**vars.collateralDecimals)) .percentDiv(vars.liquidationBonus); } else { collateralAmount = vars.maxAmountCollateralToLiquidate; debtAmountNeeded = debtToCover; } return (collateralAmount, debtAmountNeeded); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; import {IInitializableAToken} from './IInitializableAToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; interface IAToken is IERC20, IScaledBalanceToken, IInitializableAToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param value The amount being * @param index The new liquidity index of the reserve **/ event Mint(address indexed from, uint256 value, uint256 index); /** * @dev Mints `amount` aTokens to `user` * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted after aTokens are burned * @param from The owner of the aTokens, getting them burned * @param target The address that will receive the underlying * @param value The amount being burned * @param index The new liquidity index of the reserve **/ event Burn(address indexed from, address indexed target, uint256 value, uint256 index); /** * @dev Emitted during the transfer action * @param from The user whose tokens are being transferred * @param to The recipient * @param value The amount being transferred * @param index The new liquidity index of the reserve **/ event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index); /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external; /** * @dev Mints aTokens to the reserve treasury * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external; /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external; /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param user The recipient of the underlying * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address user, uint256 amount) external returns (uint256); /** * @dev Invoked to execute actions on the aToken side after a repayment. * @param user The user executing the repayment * @param amount The amount getting repaid **/ function handleRepayment(address user, uint256 amount) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IInitializableDebtToken} from './IInitializableDebtToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IStableDebtToken * @notice Defines the interface for the stable debt token * @dev It does not inherit from IERC20 to save in code size * @author Aave **/ interface IStableDebtToken is IInitializableDebtToken { /** * @dev Emitted when new stable debt is minted * @param user The address of the user who triggered the minting * @param onBehalfOf The recipient of stable debt tokens * @param amount The amount minted * @param currentBalance The current balance of the user * @param balanceIncrease The increase in balance since the last action of the user * @param newRate The rate of the debt after the minting * @param avgStableRate The new average stable rate after the minting * @param newTotalSupply The new total supply of the stable debt token after the action **/ event Mint( address indexed user, address indexed onBehalfOf, uint256 amount, uint256 currentBalance, uint256 balanceIncrease, uint256 newRate, uint256 avgStableRate, uint256 newTotalSupply ); /** * @dev Emitted when new stable debt is burned * @param user The address of the user * @param amount The amount being burned * @param currentBalance The current balance of the user * @param balanceIncrease The the increase in balance since the last action of the user * @param avgStableRate The new average stable rate after the burning * @param newTotalSupply The new total supply of the stable debt token after the action **/ event Burn( address indexed user, uint256 amount, uint256 currentBalance, uint256 balanceIncrease, uint256 avgStableRate, uint256 newTotalSupply ); /** * @dev Mints debt token to the `onBehalfOf` address. * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt tokens to mint * @param rate The rate of the debt being minted **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 rate ) external returns (bool); /** * @dev Burns debt of `user` * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address of the user getting his debt burned * @param amount The amount of debt tokens getting burned **/ function burn(address user, uint256 amount) external; /** * @dev Returns the average rate of all the stable rate loans. * @return The average stable rate **/ function getAverageStableRate() external view returns (uint256); /** * @dev Returns the stable rate of the user debt * @return The stable rate of the user **/ function getUserStableRate(address user) external view returns (uint256); /** * @dev Returns the timestamp of the last update of the user * @return The timestamp **/ function getUserLastUpdated(address user) external view returns (uint40); /** * @dev Returns the principal, the total supply and the average stable rate **/ function getSupplyData() external view returns ( uint256, uint256, uint256, uint40 ); /** * @dev Returns the timestamp of the last update of the total supply * @return The timestamp **/ function getTotalSupplyLastUpdated() external view returns (uint40); /** * @dev Returns the total supply and the average stable rate **/ function getTotalSupplyAndAvgRate() external view returns (uint256, uint256); /** * @dev Returns the principal debt balance of the user * @return The debt balance of the user since the last burn/mint action **/ function principalBalanceOf(address user) external view returns (uint256); /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; import {IInitializableDebtToken} from './IInitializableDebtToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IVariableDebtToken * @author Aave * @notice Defines the basic interface for a variable debt token. **/ interface IVariableDebtToken is IScaledBalanceToken, IInitializableDebtToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param onBehalfOf The address of the user on which behalf minting has been performed * @param value The amount to be minted * @param index The last index of the reserve **/ event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index); /** * @dev Mints debt token to the `onBehalfOf` address * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted when variable debt is burnt * @param user The user which debt has been burned * @param amount The amount of debt being burned * @param index The index of the user **/ event Burn(address indexed user, uint256 amount, uint256 index); /** * @dev Burns user variable debt * @param user The user which debt is burnt * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title ILendingPoolCollateralManager * @author Aave * @notice Defines the actions involving management of collateral in the protocol. **/ interface ILendingPoolCollateralManager { /** * @dev Emitted when a borrower is liquidated * @param collateral The address of the collateral being liquidated * @param principal The address of the reserve * @param user The address of the user being liquidated * @param debtToCover The total amount liquidated * @param liquidatedCollateralAmount The amount of collateral being liquidated * @param liquidator The address of the liquidator * @param receiveAToken true if the liquidator wants to receive aTokens, false otherwise **/ event LiquidationCall( address indexed collateral, address indexed principal, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when a reserve is disabled as collateral for an user * @param reserve The address of the reserve * @param user The address of the user **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted when a reserve is enabled as collateral for an user * @param reserve The address of the reserve * @param user The address of the user **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Users can invoke this function to liquidate an undercollateralized position. * @param collateral The address of the collateral to liquidated * @param principal The address of the principal reserve * @param user The address of the borrower * @param debtToCover The amount of principal that the liquidator wants to repay * @param receiveAToken true if the liquidators wants to receive the aTokens, false if * he wants to receive the underlying asset directly **/ function liquidationCall( address collateral, address principal, address user, uint256 debtToCover, bool receiveAToken ) external returns (uint256, string memory); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title VersionedInitializable * * @dev Helper contract to implement 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. * * @author Aave, inspired by the OpenZeppelin Initializable contract */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 private lastInitializedRevision = 0; /** * @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() { uint256 revision = getRevision(); require( initializing || isConstructor() || revision > lastInitializedRevision, 'Contract instance has already been initialized' ); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; lastInitializedRevision = revision; } _; if (isTopLevelCall) { initializing = false; } } /** * @dev returns the revision number of the contract * Needs to be defined in the inherited class as a constant. **/ function getRevision() internal pure virtual returns (uint256); /** * @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. uint256 cs; //solium-disable-next-line assembly { cs := extcodesize(address()) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title GenericLogic library * @author Aave * @title Implements protocol-level logic to calculate and validate the state of a user */ library GenericLogic { using ReserveLogic for DataTypes.ReserveData; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1 ether; struct balanceDecreaseAllowedLocalVars { uint256 decimals; uint256 liquidationThreshold; uint256 totalCollateralInETH; uint256 totalDebtInETH; uint256 avgLiquidationThreshold; uint256 amountToDecreaseInETH; uint256 collateralBalanceAfterDecrease; uint256 liquidationThresholdAfterDecrease; uint256 healthFactorAfterDecrease; bool reserveUsageAsCollateralEnabled; } /** * @dev Checks if a specific balance decrease is allowed * (i.e. doesn't bring the user borrow position health factor under HEALTH_FACTOR_LIQUIDATION_THRESHOLD) * @param asset The address of the underlying asset of the reserve * @param user The address of the user * @param amount The amount to decrease * @param reservesData The data of all the reserves * @param userConfig The user configuration * @param reserves The list of all the active reserves * @param oracle The address of the oracle contract * @return true if the decrease of the balance is allowed **/ function balanceDecreaseAllowed( address asset, address user, uint256 amount, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap calldata userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view returns (bool) { if (!userConfig.isBorrowingAny() || !userConfig.isUsingAsCollateral(reservesData[asset].id)) { return true; } balanceDecreaseAllowedLocalVars memory vars; (, vars.liquidationThreshold, , vars.decimals, ) = reservesData[asset] .configuration .getParams(); if (vars.liquidationThreshold == 0) { return true; } ( vars.totalCollateralInETH, vars.totalDebtInETH, , vars.avgLiquidationThreshold, ) = calculateUserAccountData(user, reservesData, userConfig, reserves, reservesCount, oracle); if (vars.totalDebtInETH == 0) { return true; } vars.amountToDecreaseInETH = IPriceOracleGetter(oracle).getAssetPrice(asset).mul(amount).div( 10**vars.decimals ); vars.collateralBalanceAfterDecrease = vars.totalCollateralInETH.sub(vars.amountToDecreaseInETH); //if there is a borrow, there can't be 0 collateral if (vars.collateralBalanceAfterDecrease == 0) { return false; } vars.liquidationThresholdAfterDecrease = vars .totalCollateralInETH .mul(vars.avgLiquidationThreshold) .sub(vars.amountToDecreaseInETH.mul(vars.liquidationThreshold)) .div(vars.collateralBalanceAfterDecrease); uint256 healthFactorAfterDecrease = calculateHealthFactorFromBalances( vars.collateralBalanceAfterDecrease, vars.totalDebtInETH, vars.liquidationThresholdAfterDecrease ); return healthFactorAfterDecrease >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD; } struct CalculateUserAccountDataVars { uint256 reserveUnitPrice; uint256 tokenUnit; uint256 compoundedLiquidityBalance; uint256 compoundedBorrowBalance; uint256 decimals; uint256 ltv; uint256 liquidationThreshold; uint256 i; uint256 healthFactor; uint256 totalCollateralInETH; uint256 totalDebtInETH; uint256 avgLtv; uint256 avgLiquidationThreshold; uint256 reservesLength; bool healthFactorBelowThreshold; address currentReserveAddress; bool usageAsCollateralEnabled; bool userUsesReserveAsCollateral; } /** * @dev Calculates the user data across the reserves. * this includes the total liquidity/collateral/borrow balances in ETH, * the average Loan To Value, the average Liquidation Ratio, and the Health factor. * @param user The address of the user * @param reservesData Data of all the reserves * @param userConfig The configuration of the user * @param reserves The list of the available reserves * @param oracle The price oracle address * @return The total collateral and total debt of the user in ETH, the avg ltv, liquidation threshold and the HF **/ function calculateUserAccountData( address user, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap memory userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) internal view returns ( uint256, uint256, uint256, uint256, uint256 ) { CalculateUserAccountDataVars memory vars; if (userConfig.isEmpty()) { return (0, 0, 0, 0, uint256(-1)); } for (vars.i = 0; vars.i < reservesCount; vars.i++) { if (!userConfig.isUsingAsCollateralOrBorrowing(vars.i)) { continue; } vars.currentReserveAddress = reserves[vars.i]; DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress]; (vars.ltv, vars.liquidationThreshold, , vars.decimals, ) = currentReserve .configuration .getParams(); vars.tokenUnit = 10**vars.decimals; vars.reserveUnitPrice = IPriceOracleGetter(oracle).getAssetPrice(vars.currentReserveAddress); if (vars.liquidationThreshold != 0 && userConfig.isUsingAsCollateral(vars.i)) { vars.compoundedLiquidityBalance = IERC20(currentReserve.aTokenAddress).balanceOf(user); uint256 liquidityBalanceETH = vars.reserveUnitPrice.mul(vars.compoundedLiquidityBalance).div(vars.tokenUnit); vars.totalCollateralInETH = vars.totalCollateralInETH.add(liquidityBalanceETH); vars.avgLtv = vars.avgLtv.add(liquidityBalanceETH.mul(vars.ltv)); vars.avgLiquidationThreshold = vars.avgLiquidationThreshold.add( liquidityBalanceETH.mul(vars.liquidationThreshold) ); } if (userConfig.isBorrowing(vars.i)) { vars.compoundedBorrowBalance = IERC20(currentReserve.stableDebtTokenAddress).balanceOf( user ); vars.compoundedBorrowBalance = vars.compoundedBorrowBalance.add( IERC20(currentReserve.variableDebtTokenAddress).balanceOf(user) ); vars.totalDebtInETH = vars.totalDebtInETH.add( vars.reserveUnitPrice.mul(vars.compoundedBorrowBalance).div(vars.tokenUnit) ); } } vars.avgLtv = vars.totalCollateralInETH > 0 ? vars.avgLtv.div(vars.totalCollateralInETH) : 0; vars.avgLiquidationThreshold = vars.totalCollateralInETH > 0 ? vars.avgLiquidationThreshold.div(vars.totalCollateralInETH) : 0; vars.healthFactor = calculateHealthFactorFromBalances( vars.totalCollateralInETH, vars.totalDebtInETH, vars.avgLiquidationThreshold ); return ( vars.totalCollateralInETH, vars.totalDebtInETH, vars.avgLtv, vars.avgLiquidationThreshold, vars.healthFactor ); } /** * @dev Calculates the health factor from the corresponding balances * @param totalCollateralInETH The total collateral in ETH * @param totalDebtInETH The total debt in ETH * @param liquidationThreshold The avg liquidation threshold * @return The health factor calculated from the balances provided **/ function calculateHealthFactorFromBalances( uint256 totalCollateralInETH, uint256 totalDebtInETH, uint256 liquidationThreshold ) internal pure returns (uint256) { if (totalDebtInETH == 0) return uint256(-1); return (totalCollateralInETH.percentMul(liquidationThreshold)).wadDiv(totalDebtInETH); } /** * @dev Calculates the equivalent amount in ETH that an user can borrow, depending on the available collateral and the * average Loan To Value * @param totalCollateralInETH The total collateral in ETH * @param totalDebtInETH The total borrow balance * @param ltv The average loan to value * @return the amount available to borrow in ETH for the user **/ function calculateAvailableBorrowsETH( uint256 totalCollateralInETH, uint256 totalDebtInETH, uint256 ltv ) internal pure returns (uint256) { uint256 availableBorrowsETH = totalCollateralInETH.percentMul(ltv); if (availableBorrowsETH < totalDebtInETH) { return 0; } availableBorrowsETH = availableBorrowsETH.sub(totalDebtInETH); return availableBorrowsETH; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title Helpers library * @author Aave */ library Helpers { /** * @dev Fetches the user current stable and variable debt balances * @param user The user address * @param reserve The reserve data object * @return The stable and variable debt balance **/ function getUserCurrentDebt(address user, DataTypes.ReserveData storage reserve) internal view returns (uint256, uint256) { return ( IERC20(reserve.stableDebtTokenAddress).balanceOf(user), IERC20(reserve.variableDebtTokenAddress).balanceOf(user) ); } function getUserCurrentDebtMemory(address user, DataTypes.ReserveData memory reserve) internal view returns (uint256, uint256) { return ( IERC20(reserve.stableDebtTokenAddress).balanceOf(user), IERC20(reserve.variableDebtTokenAddress).balanceOf(user) ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { uint256 internal constant WAD = 1e18; uint256 internal constant halfWAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant halfRAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return halfRAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return halfWAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfWAD) / WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfRAY) / RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); return result / WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * WAD_RAY_RATIO; require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW); return result; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {Helpers} from '../helpers/Helpers.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 4000; uint256 public constant REBALANCE_UP_USAGE_RATIO_THRESHOLD = 0.95 * 1e27; //usage ratio of 95% /** * @dev Validates a deposit action * @param reserve The reserve object on which the user is depositing * @param amount The amount to be deposited */ function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view { (bool isActive, bool isFrozen, , ) = reserve.configuration.getFlags(); require(amount != 0, Errors.VL_INVALID_AMOUNT); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!isFrozen, Errors.VL_RESERVE_FROZEN); } /** * @dev Validates a withdraw action * @param reserveAddress The address of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user * @param reservesData The reserves state * @param userConfig The user configuration * @param reserves The addresses of the reserves * @param reservesCount The number of reserves * @param oracle The price oracle */ function validateWithdraw( address reserveAddress, uint256 amount, uint256 userBalance, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { require(amount != 0, Errors.VL_INVALID_AMOUNT); require(amount <= userBalance, Errors.VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE); (bool isActive, , , ) = reservesData[reserveAddress].configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require( GenericLogic.balanceDecreaseAllowed( reserveAddress, msg.sender, amount, reservesData, userConfig, reserves, reservesCount, oracle ), Errors.VL_TRANSFER_NOT_ALLOWED ); } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 currentLiquidationThreshold; uint256 amountOfCollateralNeededETH; uint256 userCollateralBalanceETH; uint256 userBorrowBalanceETH; uint256 availableLiquidity; uint256 healthFactor; bool isActive; bool isFrozen; bool borrowingEnabled; bool stableRateBorrowingEnabled; } /** * @dev Validates a borrow action * @param asset The address of the asset to borrow * @param reserve The reserve state from which the user is borrowing * @param userAddress The address of the user * @param amount The amount to be borrowed * @param amountInETH The amount to be borrowed, in ETH * @param interestRateMode The interest rate mode at which the user is borrowing * @param maxStableLoanPercent The max amount of the liquidity that can be borrowed at stable rate, in percentage * @param reservesData The state of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateBorrow( address asset, DataTypes.ReserveData storage reserve, address userAddress, uint256 amount, uint256 amountInETH, uint256 interestRateMode, uint256 maxStableLoanPercent, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { ValidateBorrowLocalVars memory vars; (vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled) = reserve .configuration .getFlags(); require(vars.isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!vars.isFrozen, Errors.VL_RESERVE_FROZEN); require(amount != 0, Errors.VL_INVALID_AMOUNT); require(vars.borrowingEnabled, Errors.VL_BORROWING_NOT_ENABLED); //validate interest rate mode require( uint256(DataTypes.InterestRateMode.VARIABLE) == interestRateMode || uint256(DataTypes.InterestRateMode.STABLE) == interestRateMode, Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED ); ( vars.userCollateralBalanceETH, vars.userBorrowBalanceETH, vars.currentLtv, vars.currentLiquidationThreshold, vars.healthFactor ) = GenericLogic.calculateUserAccountData( userAddress, reservesData, userConfig, reserves, reservesCount, oracle ); require(vars.userCollateralBalanceETH > 0, Errors.VL_COLLATERAL_BALANCE_IS_0); require( vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD ); //add the current already borrowed amount to the amount requested to calculate the total collateral needed. vars.amountOfCollateralNeededETH = vars.userBorrowBalanceETH.add(amountInETH).percentDiv( vars.currentLtv ); //LTV is calculated in percentage require( vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH, Errors.VL_COLLATERAL_CANNOT_COVER_NEW_BORROW ); /** * Following conditions need to be met if the user is borrowing at a stable rate: * 1. Reserve must be enabled for stable rate borrowing * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency * they are borrowing, to prevent abuses. * 3. Users will be able to borrow only a portion of the total available liquidity **/ if (interestRateMode == uint256(DataTypes.InterestRateMode.STABLE)) { //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve require(vars.stableRateBorrowingEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.id) || reserve.configuration.getLtv() == 0 || amount > IERC20(reserve.aTokenAddress).balanceOf(userAddress), Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY ); vars.availableLiquidity = IERC20(asset).balanceOf(reserve.aTokenAddress); //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(maxStableLoanPercent); require(amount <= maxLoanSizeStable, Errors.VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); } } /** * @dev Validates a repay action * @param reserve The reserve state from which the user is repaying * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveData storage reserve, uint256 amountSent, DataTypes.InterestRateMode rateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) external view { bool isActive = reserve.configuration.getActive(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(amountSent > 0, Errors.VL_INVALID_AMOUNT); require( (stableDebt > 0 && DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE) || (variableDebt > 0 && DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.VARIABLE), Errors.VL_NO_DEBT_OF_SELECTED_TYPE ); require( amountSent != uint256(-1) || msg.sender == onBehalfOf, Errors.VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF ); } /** * @dev Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the borrow */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) external view { (bool isActive, bool isFrozen, , bool stableRateEnabled) = reserve.configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!isFrozen, Errors.VL_RESERVE_FROZEN); if (currentRateMode == DataTypes.InterestRateMode.STABLE) { require(stableDebt > 0, Errors.VL_NO_STABLE_RATE_LOAN_IN_RESERVE); } else if (currentRateMode == DataTypes.InterestRateMode.VARIABLE) { require(variableDebt > 0, Errors.VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE); /** * user wants to swap to stable, before swapping we need to ensure that * 1. stable borrow rate is enabled on the reserve * 2. user is not trying to abuse the reserve by depositing * more collateral than he is borrowing, artificially lowering * the interest rate, borrowing at variable, and switching to stable **/ require(stableRateEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.id) || reserve.configuration.getLtv() == 0 || stableDebt.add(variableDebt) > IERC20(reserve.aTokenAddress).balanceOf(msg.sender), Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY ); } else { revert(Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED); } } /** * @dev Validates a stable borrow rate rebalance action * @param reserve The reserve state on which the user is getting rebalanced * @param reserveAddress The address of the reserve * @param stableDebtToken The stable debt token instance * @param variableDebtToken The variable debt token instance * @param aTokenAddress The address of the aToken contract */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, address reserveAddress, IERC20 stableDebtToken, IERC20 variableDebtToken, address aTokenAddress ) external view { (bool isActive, , , ) = reserve.configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); //if the usage ratio is below 95%, no rebalances are needed uint256 totalDebt = stableDebtToken.totalSupply().add(variableDebtToken.totalSupply()).wadToRay(); uint256 availableLiquidity = IERC20(reserveAddress).balanceOf(aTokenAddress).wadToRay(); uint256 usageRatio = totalDebt == 0 ? 0 : totalDebt.rayDiv(availableLiquidity.add(totalDebt)); //if the liquidity rate is below REBALANCE_UP_THRESHOLD of the max variable APR at 95% usage, //then we allow rebalancing of the stable rate positions. uint256 currentLiquidityRate = reserve.currentLiquidityRate; uint256 maxVariableBorrowRate = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).getMaxVariableBorrowRate(); require( usageRatio >= REBALANCE_UP_USAGE_RATIO_THRESHOLD && currentLiquidityRate <= maxVariableBorrowRate.percentMul(REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD), Errors.LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET ); } /** * @dev Validates the action of setting an asset as collateral * @param reserve The state of the reserve that the user is enabling or disabling as collateral * @param reserveAddress The address of the reserve * @param reservesData The data of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateSetUseReserveAsCollateral( DataTypes.ReserveData storage reserve, address reserveAddress, bool useAsCollateral, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { uint256 underlyingBalance = IERC20(reserve.aTokenAddress).balanceOf(msg.sender); require(underlyingBalance > 0, Errors.VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0); require( useAsCollateral || GenericLogic.balanceDecreaseAllowed( reserveAddress, msg.sender, underlyingBalance, reservesData, userConfig, reserves, reservesCount, oracle ), Errors.VL_DEPOSIT_ALREADY_IN_USE ); } /** * @dev Validates a flashloan action * @param assets The assets being flashborrowed * @param amounts The amounts for each asset being borrowed **/ function validateFlashloan(address[] memory assets, uint256[] memory amounts) internal pure { require(assets.length == amounts.length, Errors.VL_INCONSISTENT_FLASHLOAN_PARAMS); } /** * @dev Validates the liquidation action * @param collateralReserve The reserve data of the collateral * @param principalReserve The reserve data of the principal * @param userConfig The user configuration * @param userHealthFactor The user's health factor * @param userStableDebt Total stable debt balance of the user * @param userVariableDebt Total variable debt balance of the user **/ function validateLiquidationCall( DataTypes.ReserveData storage collateralReserve, DataTypes.ReserveData storage principalReserve, DataTypes.UserConfigurationMap storage userConfig, uint256 userHealthFactor, uint256 userStableDebt, uint256 userVariableDebt ) internal view returns (uint256, string memory) { if ( !collateralReserve.configuration.getActive() || !principalReserve.configuration.getActive() ) { return ( uint256(Errors.CollateralManagerErrors.NO_ACTIVE_RESERVE), Errors.VL_NO_ACTIVE_RESERVE ); } if (userHealthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD) { return ( uint256(Errors.CollateralManagerErrors.HEALTH_FACTOR_ABOVE_THRESHOLD), Errors.LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD ); } bool isCollateralEnabled = collateralReserve.configuration.getLiquidationThreshold() > 0 && userConfig.isUsingAsCollateral(collateralReserve.id); //if collateral isn't enabled as collateral by user, it cannot be liquidated if (!isCollateralEnabled) { return ( uint256(Errors.CollateralManagerErrors.COLLATERAL_CANNOT_BE_LIQUIDATED), Errors.LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED ); } if (userStableDebt == 0 && userVariableDebt == 0) { return ( uint256(Errors.CollateralManagerErrors.CURRRENCY_NOT_BORROWED), Errors.LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER ); } return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS); } /** * @dev Validates an aToken transfer * @param from The user from which the aTokens are being transferred * @param reservesData The state of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateTransfer( address from, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) internal view { (, , , , uint256 healthFactor) = GenericLogic.calculateUserAccountData( from, reservesData, userConfig, reserves, reservesCount, oracle ); require( healthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.VL_TRANSFER_NOT_ALLOWED ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; contract LendingPoolStorage { using ReserveLogic for DataTypes.ReserveData; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; ILendingPoolAddressesProvider internal _addressesProvider; mapping(address => DataTypes.ReserveData) internal _reserves; mapping(address => DataTypes.UserConfigurationMap) internal _usersConfig; // the list of the available reserves, structured as a mapping for gas savings reasons mapping(uint256 => address) internal _reservesList; uint256 internal _reservesCount; bool internal _paused; uint256 internal _maxStableRateBorrowSizePercent; uint256 internal _flashLoanPremiumTotal; uint256 internal _maxNumberOfReserves; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from './ILendingPool.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IInitializableAToken * @notice Interface for the initialize function on AToken * @author Aave **/ interface IInitializableAToken { /** * @dev Emitted when an aToken is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param treasury The address of the treasury * @param incentivesController The address of the incentives controller for this aToken * @param aTokenDecimals the decimals of the underlying * @param aTokenName the name of the aToken * @param aTokenSymbol the symbol of the aToken * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address treasury, address incentivesController, uint8 aTokenDecimals, string aTokenName, string aTokenSymbol, bytes params ); /** * @dev Initializes the aToken * @param pool The address of the lending pool where this aToken will be used * @param treasury The address of the Aave treasury, receiving the fees on this aToken * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's * @param aTokenName The name of the aToken * @param aTokenSymbol The symbol of the aToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IAaveIncentivesController { function handleAction( address user, uint256 userBalance, uint256 totalSupply ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from './ILendingPool.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IInitializableDebtToken * @notice Interface for the initialize function common between debt tokens * @author Aave **/ interface IInitializableDebtToken { /** * @dev Emitted when a debt token is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param incentivesController The address of the incentives controller for this aToken * @param debtTokenDecimals the decimals of the debt token * @param debtTokenName the name of the debt token * @param debtTokenSymbol the symbol of the debt token * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address incentivesController, uint8 debtTokenDecimals, string debtTokenName, string debtTokenSymbol, bytes params ); /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../../../interfaces/IVariableDebtToken.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {MathUtils} from '../math/MathUtils.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements the logic to update the reserves state */ library ReserveLogic { using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; /** * @dev Emitted when the state of a reserve is updated * @param asset The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed asset, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); using ReserveLogic for DataTypes.ReserveData; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; /** * @dev Returns the ongoing normalized income for the reserve * A value of 1e27 means there is no income. As time passes, the income is accrued * A value of 2*1e27 means for each unit of asset one unit of income has been accrued * @param reserve The reserve object * @return the normalized income. expressed in ray **/ function getNormalizedIncome(DataTypes.ReserveData storage reserve) internal view returns (uint256) { uint40 timestamp = reserve.lastUpdateTimestamp; //solium-disable-next-line if (timestamp == uint40(block.timestamp)) { //if the index was updated in the same block, no need to perform any calculation return reserve.liquidityIndex; } uint256 cumulated = MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul( reserve.liquidityIndex ); return cumulated; } /** * @dev Returns the ongoing normalized variable debt for the reserve * A value of 1e27 means there is no debt. As time passes, the income is accrued * A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated * @param reserve The reserve object * @return The normalized variable debt. expressed in ray **/ function getNormalizedDebt(DataTypes.ReserveData storage reserve) internal view returns (uint256) { uint40 timestamp = reserve.lastUpdateTimestamp; //solium-disable-next-line if (timestamp == uint40(block.timestamp)) { //if the index was updated in the same block, no need to perform any calculation return reserve.variableBorrowIndex; } uint256 cumulated = MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul( reserve.variableBorrowIndex ); return cumulated; } /** * @dev Updates the liquidity cumulative index and the variable borrow index. * @param reserve the reserve object **/ function updateState(DataTypes.ReserveData storage reserve) internal { uint256 scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledTotalSupply(); uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex; uint256 previousLiquidityIndex = reserve.liquidityIndex; uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp; (uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) = _updateIndexes( reserve, scaledVariableDebt, previousLiquidityIndex, previousVariableBorrowIndex, lastUpdatedTimestamp ); _mintToTreasury( reserve, scaledVariableDebt, previousVariableBorrowIndex, newLiquidityIndex, newVariableBorrowIndex, lastUpdatedTimestamp ); } /** * @dev Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income. Used for example to accumulate * the flashloan fee to the reserve, and spread it between all the depositors * @param reserve The reserve object * @param totalLiquidity The total liquidity available in the reserve * @param amount The amount to accomulate **/ function cumulateToLiquidityIndex( DataTypes.ReserveData storage reserve, uint256 totalLiquidity, uint256 amount ) internal { uint256 amountToLiquidityRatio = amount.wadToRay().rayDiv(totalLiquidity.wadToRay()); uint256 result = amountToLiquidityRatio.add(WadRayMath.ray()); result = result.rayMul(reserve.liquidityIndex); require(result <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW); reserve.liquidityIndex = uint128(result); } /** * @dev Initializes a reserve * @param reserve The reserve object * @param aTokenAddress The address of the overlying atoken contract * @param interestRateStrategyAddress The address of the interest rate strategy contract **/ function init( DataTypes.ReserveData storage reserve, address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress ) external { require(reserve.aTokenAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED); reserve.liquidityIndex = uint128(WadRayMath.ray()); reserve.variableBorrowIndex = uint128(WadRayMath.ray()); reserve.aTokenAddress = aTokenAddress; reserve.stableDebtTokenAddress = stableDebtTokenAddress; reserve.variableDebtTokenAddress = variableDebtTokenAddress; reserve.interestRateStrategyAddress = interestRateStrategyAddress; } struct UpdateInterestRatesLocalVars { address stableDebtTokenAddress; uint256 availableLiquidity; uint256 totalStableDebt; uint256 newLiquidityRate; uint256 newStableRate; uint256 newVariableRate; uint256 avgStableRate; uint256 totalVariableDebt; } /** * @dev Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate * @param reserve The address of the reserve to be updated * @param liquidityAdded The amount of liquidity added to the protocol (deposit or repay) in the previous action * @param liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow) **/ function updateInterestRates( DataTypes.ReserveData storage reserve, address reserveAddress, address aTokenAddress, uint256 liquidityAdded, uint256 liquidityTaken ) internal { UpdateInterestRatesLocalVars memory vars; vars.stableDebtTokenAddress = reserve.stableDebtTokenAddress; (vars.totalStableDebt, vars.avgStableRate) = IStableDebtToken(vars.stableDebtTokenAddress) .getTotalSupplyAndAvgRate(); //calculates the total variable debt locally using the scaled total supply instead //of totalSupply(), as it's noticeably cheaper. Also, the index has been //updated by the previous updateState() call vars.totalVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress) .scaledTotalSupply() .rayMul(reserve.variableBorrowIndex); ( vars.newLiquidityRate, vars.newStableRate, vars.newVariableRate ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates( reserveAddress, aTokenAddress, liquidityAdded, liquidityTaken, vars.totalStableDebt, vars.totalVariableDebt, vars.avgStableRate, reserve.configuration.getReserveFactor() ); require(vars.newLiquidityRate <= type(uint128).max, Errors.RL_LIQUIDITY_RATE_OVERFLOW); require(vars.newStableRate <= type(uint128).max, Errors.RL_STABLE_BORROW_RATE_OVERFLOW); require(vars.newVariableRate <= type(uint128).max, Errors.RL_VARIABLE_BORROW_RATE_OVERFLOW); reserve.currentLiquidityRate = uint128(vars.newLiquidityRate); reserve.currentStableBorrowRate = uint128(vars.newStableRate); reserve.currentVariableBorrowRate = uint128(vars.newVariableRate); emit ReserveDataUpdated( reserveAddress, vars.newLiquidityRate, vars.newStableRate, vars.newVariableRate, reserve.liquidityIndex, reserve.variableBorrowIndex ); } struct MintToTreasuryLocalVars { uint256 currentStableDebt; uint256 principalStableDebt; uint256 previousStableDebt; uint256 currentVariableDebt; uint256 previousVariableDebt; uint256 avgStableRate; uint256 cumulatedStableInterest; uint256 totalDebtAccrued; uint256 amountToMint; uint256 reserveFactor; uint40 stableSupplyUpdatedTimestamp; } /** * @dev Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the * specific asset. * @param reserve The reserve reserve to be updated * @param scaledVariableDebt The current scaled total variable debt * @param previousVariableBorrowIndex The variable borrow index before the last accumulation of the interest * @param newLiquidityIndex The new liquidity index * @param newVariableBorrowIndex The variable borrow index after the last accumulation of the interest **/ function _mintToTreasury( DataTypes.ReserveData storage reserve, uint256 scaledVariableDebt, uint256 previousVariableBorrowIndex, uint256 newLiquidityIndex, uint256 newVariableBorrowIndex, uint40 timestamp ) internal { MintToTreasuryLocalVars memory vars; vars.reserveFactor = reserve.configuration.getReserveFactor(); if (vars.reserveFactor == 0) { return; } //fetching the principal, total stable debt and the avg stable rate ( vars.principalStableDebt, vars.currentStableDebt, vars.avgStableRate, vars.stableSupplyUpdatedTimestamp ) = IStableDebtToken(reserve.stableDebtTokenAddress).getSupplyData(); //calculate the last principal variable debt vars.previousVariableDebt = scaledVariableDebt.rayMul(previousVariableBorrowIndex); //calculate the new total supply after accumulation of the index vars.currentVariableDebt = scaledVariableDebt.rayMul(newVariableBorrowIndex); //calculate the stable debt until the last timestamp update vars.cumulatedStableInterest = MathUtils.calculateCompoundedInterest( vars.avgStableRate, vars.stableSupplyUpdatedTimestamp, timestamp ); vars.previousStableDebt = vars.principalStableDebt.rayMul(vars.cumulatedStableInterest); //debt accrued is the sum of the current debt minus the sum of the debt at the last update vars.totalDebtAccrued = vars .currentVariableDebt .add(vars.currentStableDebt) .sub(vars.previousVariableDebt) .sub(vars.previousStableDebt); vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor); if (vars.amountToMint != 0) { IAToken(reserve.aTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex); } } /** * @dev Updates the reserve indexes and the timestamp of the update * @param reserve The reserve reserve to be updated * @param scaledVariableDebt The scaled variable debt * @param liquidityIndex The last stored liquidity index * @param variableBorrowIndex The last stored variable borrow index **/ function _updateIndexes( DataTypes.ReserveData storage reserve, uint256 scaledVariableDebt, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 timestamp ) internal returns (uint256, uint256) { uint256 currentLiquidityRate = reserve.currentLiquidityRate; uint256 newLiquidityIndex = liquidityIndex; uint256 newVariableBorrowIndex = variableBorrowIndex; //only cumulating if there is any income being produced if (currentLiquidityRate > 0) { uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest(currentLiquidityRate, timestamp); newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex); require(newLiquidityIndex <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW); reserve.liquidityIndex = uint128(newLiquidityIndex); //as the liquidity rate might come only from stable rate loans, we need to ensure //that there is actual variable debt before accumulating if (scaledVariableDebt != 0) { uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp); newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex); require( newVariableBorrowIndex <= type(uint128).max, Errors.RL_VARIABLE_BORROW_INDEX_OVERFLOW ); reserve.variableBorrowIndex = uint128(newVariableBorrowIndex); } } //solium-disable-next-line reserve.lastUpdateTimestamp = uint40(block.timestamp); return (newLiquidityIndex, newVariableBorrowIndex); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveConfiguration library * @author Aave * @notice Implements the bitmap logic to handle the reserve configuration */ library ReserveConfiguration { uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore uint256 constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore uint256 constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore uint256 constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore uint256 constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16; uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32; uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48; uint256 constant IS_ACTIVE_START_BIT_POSITION = 56; uint256 constant IS_FROZEN_START_BIT_POSITION = 57; uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58; uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59; uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64; uint256 constant MAX_VALID_LTV = 65535; uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535; uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535; uint256 constant MAX_VALID_DECIMALS = 255; uint256 constant MAX_VALID_RESERVE_FACTOR = 65535; /** * @dev Sets the Loan to Value of the reserve * @param self The reserve configuration * @param ltv the new ltv **/ function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure { require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV); self.data = (self.data & LTV_MASK) | ltv; } /** * @dev Gets the Loan to Value of the reserve * @param self The reserve configuration * @return The loan to value **/ function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return self.data & ~LTV_MASK; } /** * @dev Sets the liquidation threshold of the reserve * @param self The reserve configuration * @param threshold The new liquidation threshold **/ function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold) internal pure { require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD); self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION); } /** * @dev Gets the liquidation threshold of the reserve * @param self The reserve configuration * @return The liquidation threshold **/ function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION; } /** * @dev Sets the liquidation bonus of the reserve * @param self The reserve configuration * @param bonus The new liquidation bonus **/ function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus) internal pure { require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS); self.data = (self.data & LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION); } /** * @dev Gets the liquidation bonus of the reserve * @param self The reserve configuration * @return The liquidation bonus **/ function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION; } /** * @dev Sets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @param decimals The decimals **/ function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals) internal pure { require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS); self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION); } /** * @dev Gets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @return The decimals of the asset **/ function getDecimals(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION; } /** * @dev Sets the active state of the reserve * @param self The reserve configuration * @param active The active state **/ function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure { self.data = (self.data & ACTIVE_MASK) | (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION); } /** * @dev Gets the active state of the reserve * @param self The reserve configuration * @return The active state **/ function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~ACTIVE_MASK) != 0; } /** * @dev Sets the frozen state of the reserve * @param self The reserve configuration * @param frozen The frozen state **/ function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure { self.data = (self.data & FROZEN_MASK) | (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION); } /** * @dev Gets the frozen state of the reserve * @param self The reserve configuration * @return The frozen state **/ function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~FROZEN_MASK) != 0; } /** * @dev Enables or disables borrowing on the reserve * @param self The reserve configuration * @param enabled True if the borrowing needs to be enabled, false otherwise **/ function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure { self.data = (self.data & BORROWING_MASK) | (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION); } /** * @dev Gets the borrowing state of the reserve * @param self The reserve configuration * @return The borrowing state **/ function getBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~BORROWING_MASK) != 0; } /** * @dev Enables or disables stable rate borrowing on the reserve * @param self The reserve configuration * @param enabled True if the stable rate borrowing needs to be enabled, false otherwise **/ function setStableRateBorrowingEnabled( DataTypes.ReserveConfigurationMap memory self, bool enabled ) internal pure { self.data = (self.data & STABLE_BORROWING_MASK) | (uint256(enabled ? 1 : 0) << STABLE_BORROWING_ENABLED_START_BIT_POSITION); } /** * @dev Gets the stable rate borrowing state of the reserve * @param self The reserve configuration * @return The stable rate borrowing state **/ function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~STABLE_BORROWING_MASK) != 0; } /** * @dev Sets the reserve factor of the reserve * @param self The reserve configuration * @param reserveFactor The reserve factor **/ function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor) internal pure { require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR); self.data = (self.data & RESERVE_FACTOR_MASK) | (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION); } /** * @dev Gets the reserve factor of the reserve * @param self The reserve configuration * @return The reserve factor **/ function getReserveFactor(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION; } /** * @dev Gets the configuration flags of the reserve * @param self The reserve configuration * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled **/ function getFlags(DataTypes.ReserveConfigurationMap storage self) internal view returns ( bool, bool, bool, bool ) { uint256 dataLocal = self.data; return ( (dataLocal & ~ACTIVE_MASK) != 0, (dataLocal & ~FROZEN_MASK) != 0, (dataLocal & ~BORROWING_MASK) != 0, (dataLocal & ~STABLE_BORROWING_MASK) != 0 ); } /** * @dev Gets the configuration paramters of the reserve * @param self The reserve configuration * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals **/ function getParams(DataTypes.ReserveConfigurationMap storage self) internal view returns ( uint256, uint256, uint256, uint256, uint256 ) { uint256 dataLocal = self.data; return ( dataLocal & ~LTV_MASK, (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } /** * @dev Gets the configuration paramters of the reserve from a memory object * @param self The reserve configuration * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals **/ function getParamsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( uint256, uint256, uint256, uint256, uint256 ) { return ( self.data & ~LTV_MASK, (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } /** * @dev Gets the configuration flags of the reserve from a memory object * @param self The reserve configuration * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled **/ function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( bool, bool, bool, bool ) { return ( (self.data & ~ACTIVE_MASK) != 0, (self.data & ~FROZEN_MASK) != 0, (self.data & ~BORROWING_MASK) != 0, (self.data & ~STABLE_BORROWING_MASK) != 0 ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title UserConfiguration library * @author Aave * @notice Implements the bitmap logic to handle the user configuration */ library UserConfiguration { uint256 internal constant BORROWING_MASK = 0x5555555555555555555555555555555555555555555555555555555555555555; /** * @dev Sets if the user is borrowing the reserve identified by reserveIndex * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @param borrowing True if the user is borrowing the reserve, false otherwise **/ function setBorrowing( DataTypes.UserConfigurationMap storage self, uint256 reserveIndex, bool borrowing ) internal { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); self.data = (self.data & ~(1 << (reserveIndex * 2))) | (uint256(borrowing ? 1 : 0) << (reserveIndex * 2)); } /** * @dev Sets if the user is using as collateral the reserve identified by reserveIndex * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @param usingAsCollateral True if the user is usin the reserve as collateral, false otherwise **/ function setUsingAsCollateral( DataTypes.UserConfigurationMap storage self, uint256 reserveIndex, bool usingAsCollateral ) internal { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); self.data = (self.data & ~(1 << (reserveIndex * 2 + 1))) | (uint256(usingAsCollateral ? 1 : 0) << (reserveIndex * 2 + 1)); } /** * @dev Used to validate if a user has been using the reserve for borrowing or as collateral * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve for borrowing or as collateral, false otherwise **/ function isUsingAsCollateralOrBorrowing( DataTypes.UserConfigurationMap memory self, uint256 reserveIndex ) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2)) & 3 != 0; } /** * @dev Used to validate if a user has been using the reserve for borrowing * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve for borrowing, false otherwise **/ function isBorrowing(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2)) & 1 != 0; } /** * @dev Used to validate if a user has been using the reserve as collateral * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve as collateral, false otherwise **/ function isUsingAsCollateral(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2 + 1)) & 1 != 0; } /** * @dev Used to validate if a user has been borrowing from any reserve * @param self The configuration object * @return True if the user has been borrowing any reserve, false otherwise **/ function isBorrowingAny(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { return self.data & BORROWING_MASK != 0; } /** * @dev Used to validate if a user has not been using any reserve * @param self The configuration object * @return True if the user has been borrowing any reserve, false otherwise **/ function isEmpty(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { return self.data == 0; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IReserveInterestRateStrategyInterface interface * @dev Interface for the calculation of the interest rates * @author Aave */ interface IReserveInterestRateStrategy { function baseVariableBorrowRate() external view returns (uint256); function getMaxVariableBorrowRate() external view returns (uint256); function calculateInterestRates( address reserve, uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view returns ( uint256, uint256, uint256 ); function calculateInterestRates( address reserve, address aToken, uint256 liquidityAdded, uint256 liquidityTaken, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view returns ( uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {WadRayMath} from './WadRayMath.sol'; library MathUtils { using SafeMath for uint256; using WadRayMath for uint256; /// @dev Ignoring leap years uint256 internal constant SECONDS_PER_YEAR = 365 days; /** * @dev Function to calculate the interest accumulated using a linear interest rate formula * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate linearly accumulated during the timeDelta, in ray **/ function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { //solium-disable-next-line uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp)); return (rate.mul(timeDifference) / SECONDS_PER_YEAR).add(WadRayMath.ray()); } /** * @dev Function to calculate the interest using a compounded interest rate formula * To avoid expensive exponentiation, the calculation is performed using a binomial approximation: * * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3... * * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods * * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate compounded during the timeDelta, in ray **/ function calculateCompoundedInterest( uint256 rate, uint40 lastUpdateTimestamp, uint256 currentTimestamp ) internal pure returns (uint256) { //solium-disable-next-line uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp)); if (exp == 0) { return WadRayMath.ray(); } uint256 expMinusOne = exp - 1; uint256 expMinusTwo = exp > 2 ? exp - 2 : 0; uint256 ratePerSecond = rate / SECONDS_PER_YEAR; uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond); uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond); uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2; uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6; return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm); } /** * @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp * @param rate The interest rate (in ray) * @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated **/ function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {FlashLoanReceiverBase} from '../../flashloan/base/FlashLoanReceiverBase.sol'; import {MintableERC20} from '../tokens/MintableERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; contract MockFlashLoanReceiver is FlashLoanReceiverBase { using SafeERC20 for IERC20; ILendingPoolAddressesProvider internal _provider; event ExecutedWithFail(address[] _assets, uint256[] _amounts, uint256[] _premiums); event ExecutedWithSuccess(address[] _assets, uint256[] _amounts, uint256[] _premiums); bool _failExecution; uint256 _amountToApprove; bool _simulateEOA; constructor(ILendingPoolAddressesProvider provider) public FlashLoanReceiverBase(provider) {} function setFailExecutionTransfer(bool fail) public { _failExecution = fail; } function setAmountToApprove(uint256 amountToApprove) public { _amountToApprove = amountToApprove; } function setSimulateEOA(bool flag) public { _simulateEOA = flag; } function amountToApprove() public view returns (uint256) { return _amountToApprove; } function simulateEOA() public view returns (bool) { return _simulateEOA; } function executeOperation( address[] memory assets, uint256[] memory amounts, uint256[] memory premiums, address initiator, bytes memory params ) public override returns (bool) { params; initiator; if (_failExecution) { emit ExecutedWithFail(assets, amounts, premiums); return !_simulateEOA; } for (uint256 i = 0; i < assets.length; i++) { //mint to this contract the specific amount MintableERC20 token = MintableERC20(assets[i]); //check the contract has the specified balance require( amounts[i] <= IERC20(assets[i]).balanceOf(address(this)), 'Invalid balance for the contract' ); uint256 amountToReturn = (_amountToApprove != 0) ? _amountToApprove : amounts[i].add(premiums[i]); //execution does not fail - mint tokens and return them to the _destination token.mint(premiums[i]); IERC20(assets[i]).approve(address(LENDING_POOL), amountToReturn); } emit ExecutedWithSuccess(assets, amounts, premiums); return true; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ERC20} from '../../dependencies/openzeppelin/contracts/ERC20.sol'; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract MintableERC20 is ERC20 { constructor( string memory name, string memory symbol, uint8 decimals ) public ERC20(name, symbol) { _setupDecimals(decimals); } /** * @dev Function to mint tokens * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(uint256 value) public returns (bool) { _mint(_msgSender(), value); return true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import './Context.sol'; import './IERC20.sol'; import './SafeMath.sol'; import './Address.sol'; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, 'ERC20: transfer amount exceeds allowance') ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, 'ERC20: decreased allowance below zero' ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), 'ERC20: transfer from the zero address'); require(recipient != address(0), 'ERC20: transfer to the zero address'); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, 'ERC20: transfer amount exceeds balance'); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: mint to the zero address'); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: burn from the zero address'); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, 'ERC20: burn amount exceeds balance'); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), 'ERC20: approve from the zero address'); require(spender != address(0), 'ERC20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {Address} from '../dependencies/openzeppelin/contracts/Address.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; /** * @title WalletBalanceProvider contract * @author Aave, influenced by https://github.com/wbobeirne/eth-balance-checker/blob/master/contracts/BalanceChecker.sol * @notice Implements a logic of getting multiple tokens balance for one user address * @dev NOTE: THIS CONTRACT IS NOT USED WITHIN THE AAVE PROTOCOL. It's an accessory contract used to reduce the number of calls * towards the blockchain from the Aave backend. **/ contract WalletBalanceProvider { using Address for address payable; using Address for address; using SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; address constant MOCK_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /** @dev Fallback function, don't accept any ETH **/ receive() external payable { //only contracts can send ETH to the core require(msg.sender.isContract(), '22'); } /** @dev Check the token balance of a wallet in a token contract Returns the balance of the token for user. Avoids possible errors: - return 0 on non-contract address **/ function balanceOf(address user, address token) public view returns (uint256) { if (token == MOCK_ETH_ADDRESS) { return user.balance; // ETH balance // check if token is actually a contract } else if (token.isContract()) { return IERC20(token).balanceOf(user); } revert('INVALID_TOKEN'); } /** * @notice Fetches, for a list of _users and _tokens (ETH included with mock address), the balances * @param users The list of users * @param tokens The list of tokens * @return And array with the concatenation of, for each user, his/her balances **/ function batchBalanceOf(address[] calldata users, address[] calldata tokens) external view returns (uint256[] memory) { uint256[] memory balances = new uint256[](users.length * tokens.length); for (uint256 i = 0; i < users.length; i++) { for (uint256 j = 0; j < tokens.length; j++) { balances[i * tokens.length + j] = balanceOf(users[i], tokens[j]); } } return balances; } /** @dev provides balances of user wallet for all reserves available on the pool */ function getUserWalletBalances(address provider, address user) external view returns (address[] memory, uint256[] memory) { ILendingPool pool = ILendingPool(ILendingPoolAddressesProvider(provider).getLendingPool()); address[] memory reserves = pool.getReservesList(); address[] memory reservesWithEth = new address[](reserves.length + 1); for (uint256 i = 0; i < reserves.length; i++) { reservesWithEth[i] = reserves[i]; } reservesWithEth[reserves.length] = MOCK_ETH_ADDRESS; uint256[] memory balances = new uint256[](reservesWithEth.length); for (uint256 j = 0; j < reserves.length; j++) { DataTypes.ReserveConfigurationMap memory configuration = pool.getConfiguration(reservesWithEth[j]); (bool isActive, , , ) = configuration.getFlagsMemory(); if (!isActive) { balances[j] = 0; continue; } balances[j] = balanceOf(user, reservesWithEth[j]); } balances[reserves.length] = balanceOf(user, MOCK_ETH_ADDRESS); return (reservesWithEth, balances); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IWETH} from './interfaces/IWETH.sol'; import {IWETHGateway} from './interfaces/IWETHGateway.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {Helpers} from '../protocol/libraries/helpers/Helpers.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; contract WETHGateway is IWETHGateway, Ownable { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; IWETH internal immutable WETH; /** * @dev Sets the WETH address and the LendingPoolAddressesProvider address. Infinite approves lending pool. * @param weth Address of the Wrapped Ether contract **/ constructor(address weth) public { WETH = IWETH(weth); } function authorizeLendingPool(address lendingPool) external onlyOwner { WETH.approve(lendingPool, uint256(-1)); } /** * @dev deposits WETH into the reserve, using native ETH. A corresponding amount of the overlying asset (aTokens) * is minted. * @param lendingPool address of the targeted underlying lending pool * @param onBehalfOf address of the user who will receive the aTokens representing the deposit * @param referralCode integrators are assigned a referral code and can potentially receive rewards. **/ function depositETH( address lendingPool, address onBehalfOf, uint16 referralCode ) external payable override { WETH.deposit{value: msg.value}(); ILendingPool(lendingPool).deposit(address(WETH), msg.value, onBehalfOf, referralCode); } /** * @dev withdraws the WETH _reserves of msg.sender. * @param lendingPool address of the targeted underlying lending pool * @param amount amount of aWETH to withdraw and receive native ETH * @param to address of the user who will receive native ETH */ function withdrawETH( address lendingPool, uint256 amount, address to ) external override { IAToken aWETH = IAToken(ILendingPool(lendingPool).getReserveData(address(WETH)).aTokenAddress); uint256 userBalance = aWETH.balanceOf(msg.sender); uint256 amountToWithdraw = amount; // if amount is equal to uint(-1), the user wants to redeem everything if (amount == type(uint256).max) { amountToWithdraw = userBalance; } aWETH.transferFrom(msg.sender, address(this), amountToWithdraw); ILendingPool(lendingPool).withdraw(address(WETH), amountToWithdraw, address(this)); WETH.withdraw(amountToWithdraw); _safeTransferETH(to, amountToWithdraw); } /** * @dev repays a borrow on the WETH reserve, for the specified amount (or for the whole amount, if uint256(-1) is specified). * @param lendingPool address of the targeted underlying lending pool * @param amount the amount to repay, or uint256(-1) if the user wants to repay everything * @param rateMode the rate mode to repay * @param onBehalfOf the address for which msg.sender is repaying */ function repayETH( address lendingPool, uint256 amount, uint256 rateMode, address onBehalfOf ) external payable override { (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebtMemory( onBehalfOf, ILendingPool(lendingPool).getReserveData(address(WETH)) ); uint256 paybackAmount = DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } require(msg.value >= paybackAmount, 'msg.value is less than repayment amount'); WETH.deposit{value: paybackAmount}(); ILendingPool(lendingPool).repay(address(WETH), msg.value, rateMode, onBehalfOf); // refund remaining dust eth if (msg.value > paybackAmount) _safeTransferETH(msg.sender, msg.value - paybackAmount); } /** * @dev borrow WETH, unwraps to ETH and send both the ETH and DebtTokens to msg.sender, via `approveDelegation` and onBehalf argument in `LendingPool.borrow`. * @param lendingPool address of the targeted underlying lending pool * @param amount the amount of ETH to borrow * @param interesRateMode the interest rate mode * @param referralCode integrators are assigned a referral code and can potentially receive rewards */ function borrowETH( address lendingPool, uint256 amount, uint256 interesRateMode, uint16 referralCode ) external override { ILendingPool(lendingPool).borrow( address(WETH), amount, interesRateMode, referralCode, msg.sender ); WETH.withdraw(amount); _safeTransferETH(msg.sender, 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)); require(success, 'ETH_TRANSFER_FAILED'); } /** * @dev transfer ERC20 from the utility contract, for ERC20 recovery in case of stuck tokens due * direct transfers to the contract address. * @param token token to transfer * @param to recipient of the transfer * @param amount amount to send */ function emergencyTokenTransfer( address token, address to, uint256 amount ) external onlyOwner { IERC20(token).transfer(to, amount); } /** * @dev transfer native Ether from the utility contract, for native Ether recovery in case of stuck Ether * due selfdestructs or transfer ether to pre-computated contract address before deployment. * @param to recipient of the transfer * @param amount amount to send */ function emergencyEtherTransfer(address to, uint256 amount) external onlyOwner { _safeTransferETH(to, amount); } /** * @dev Get WETH address used by WETHGateway */ function getWETHAddress() external view returns (address) { return address(WETH); } /** * @dev Only WETH contract is allowed to transfer ETH here. Prevent other addresses to send Ether to this contract. */ receive() external payable { require(msg.sender == address(WETH), 'Receive not allowed'); } /** * @dev Revert fallback calls */ fallback() external payable { revert('Fallback not allowed'); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IWETH { function deposit() external payable; function withdraw(uint256) external; function approve(address guy, uint256 wad) external returns (bool); function transferFrom( address src, address dst, uint256 wad ) external returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IWETHGateway { function depositETH( address lendingPool, address onBehalfOf, uint16 referralCode ) external payable; function withdrawETH( address lendingPool, uint256 amount, address onBehalfOf ) external; function repayETH( address lendingPool, uint256 amount, uint256 rateMode, address onBehalfOf ) external payable; function borrowETH( address lendingPool, uint256 amount, uint256 interesRateMode, uint16 referralCode ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IReserveInterestRateStrategy} from '../../interfaces/IReserveInterestRateStrategy.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import 'hardhat/console.sol'; /** * @title DefaultReserveInterestRateStrategy contract * @notice Implements the calculation of the interest rates depending on the reserve state * @dev The model of interest rate is based on 2 slopes, one before the `OPTIMAL_UTILIZATION_RATE` * point of utilization and another from that one to 100% * - An instance of this same contract, can't be used across different Aave markets, due to the caching * of the LendingPoolAddressesProvider * @author Aave **/ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { using WadRayMath for uint256; using SafeMath for uint256; using PercentageMath for uint256; /** * @dev this constant represents the utilization rate at which the pool aims to obtain most competitive borrow rates. * Expressed in ray **/ uint256 public immutable OPTIMAL_UTILIZATION_RATE; /** * @dev This constant represents the excess utilization rate above the optimal. It's always equal to * 1-optimal utilization rate. Added as a constant here for gas optimizations. * Expressed in ray **/ uint256 public immutable EXCESS_UTILIZATION_RATE; ILendingPoolAddressesProvider public immutable addressesProvider; // Base variable borrow rate when Utilization rate = 0. Expressed in ray uint256 internal immutable _baseVariableBorrowRate; // Slope of the variable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _variableRateSlope1; // Slope of the variable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _variableRateSlope2; // Slope of the stable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _stableRateSlope1; // Slope of the stable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _stableRateSlope2; constructor( ILendingPoolAddressesProvider provider, uint256 optimalUtilizationRate, uint256 baseVariableBorrowRate, uint256 variableRateSlope1, uint256 variableRateSlope2, uint256 stableRateSlope1, uint256 stableRateSlope2 ) public { OPTIMAL_UTILIZATION_RATE = optimalUtilizationRate; EXCESS_UTILIZATION_RATE = WadRayMath.ray().sub(optimalUtilizationRate); addressesProvider = provider; _baseVariableBorrowRate = baseVariableBorrowRate; _variableRateSlope1 = variableRateSlope1; _variableRateSlope2 = variableRateSlope2; _stableRateSlope1 = stableRateSlope1; _stableRateSlope2 = stableRateSlope2; } function variableRateSlope1() external view returns (uint256) { return _variableRateSlope1; } function variableRateSlope2() external view returns (uint256) { return _variableRateSlope2; } function stableRateSlope1() external view returns (uint256) { return _stableRateSlope1; } function stableRateSlope2() external view returns (uint256) { return _stableRateSlope2; } function baseVariableBorrowRate() external view override returns (uint256) { return _baseVariableBorrowRate; } function getMaxVariableBorrowRate() external view override returns (uint256) { return _baseVariableBorrowRate.add(_variableRateSlope1).add(_variableRateSlope2); } /** * @dev Calculates the interest rates depending on the reserve's state and configurations * @param reserve The address of the reserve * @param liquidityAdded The liquidity added during the operation * @param liquidityTaken The liquidity taken during the operation * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param averageStableBorrowRate The weighted average of all the stable rate loans * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market * @return The liquidity rate, the stable borrow rate and the variable borrow rate **/ function calculateInterestRates( address reserve, address aToken, uint256 liquidityAdded, uint256 liquidityTaken, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view override returns ( uint256, uint256, uint256 ) { uint256 availableLiquidity = IERC20(reserve).balanceOf(aToken); //avoid stack too deep availableLiquidity = availableLiquidity.add(liquidityAdded).sub(liquidityTaken); return calculateInterestRates( reserve, availableLiquidity, totalStableDebt, totalVariableDebt, averageStableBorrowRate, reserveFactor ); } struct CalcInterestRatesLocalVars { uint256 totalDebt; uint256 currentVariableBorrowRate; uint256 currentStableBorrowRate; uint256 currentLiquidityRate; uint256 utilizationRate; } /** * @dev Calculates the interest rates depending on the reserve's state and configurations. * NOTE This function is kept for compatibility with the previous DefaultInterestRateStrategy interface. * New protocol implementation uses the new calculateInterestRates() interface * @param reserve The address of the reserve * @param availableLiquidity The liquidity available in the corresponding aToken * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param averageStableBorrowRate The weighted average of all the stable rate loans * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market * @return The liquidity rate, the stable borrow rate and the variable borrow rate **/ function calculateInterestRates( address reserve, uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) public view override returns ( uint256, uint256, uint256 ) { CalcInterestRatesLocalVars memory vars; vars.totalDebt = totalStableDebt.add(totalVariableDebt); vars.currentVariableBorrowRate = 0; vars.currentStableBorrowRate = 0; vars.currentLiquidityRate = 0; vars.utilizationRate = vars.totalDebt == 0 ? 0 : vars.totalDebt.rayDiv(availableLiquidity.add(vars.totalDebt)); vars.currentStableBorrowRate = ILendingRateOracle(addressesProvider.getLendingRateOracle()) .getMarketBorrowRate(reserve); if (vars.utilizationRate > OPTIMAL_UTILIZATION_RATE) { uint256 excessUtilizationRateRatio = vars.utilizationRate.sub(OPTIMAL_UTILIZATION_RATE).rayDiv(EXCESS_UTILIZATION_RATE); vars.currentStableBorrowRate = vars.currentStableBorrowRate.add(_stableRateSlope1).add( _stableRateSlope2.rayMul(excessUtilizationRateRatio) ); vars.currentVariableBorrowRate = _baseVariableBorrowRate.add(_variableRateSlope1).add( _variableRateSlope2.rayMul(excessUtilizationRateRatio) ); } else { vars.currentStableBorrowRate = vars.currentStableBorrowRate.add( _stableRateSlope1.rayMul(vars.utilizationRate.rayDiv(OPTIMAL_UTILIZATION_RATE)) ); vars.currentVariableBorrowRate = _baseVariableBorrowRate.add( vars.utilizationRate.rayMul(_variableRateSlope1).rayDiv(OPTIMAL_UTILIZATION_RATE) ); } vars.currentLiquidityRate = _getOverallBorrowRate( totalStableDebt, totalVariableDebt, vars .currentVariableBorrowRate, averageStableBorrowRate ) .rayMul(vars.utilizationRate) .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(reserveFactor)); return ( vars.currentLiquidityRate, vars.currentStableBorrowRate, vars.currentVariableBorrowRate ); } /** * @dev Calculates the overall borrow rate as the weighted average between the total variable debt and total stable debt * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param currentVariableBorrowRate The current variable borrow rate of the reserve * @param currentAverageStableBorrowRate The current weighted average of all the stable rate loans * @return The weighted averaged borrow rate **/ function _getOverallBorrowRate( uint256 totalStableDebt, uint256 totalVariableDebt, uint256 currentVariableBorrowRate, uint256 currentAverageStableBorrowRate ) internal pure returns (uint256) { uint256 totalDebt = totalStableDebt.add(totalVariableDebt); if (totalDebt == 0) return 0; uint256 weightedVariableRate = totalVariableDebt.wadToRay().rayMul(currentVariableBorrowRate); uint256 weightedStableRate = totalStableDebt.wadToRay().rayMul(currentAverageStableBorrowRate); uint256 overallBorrowRate = weightedVariableRate.add(weightedStableRate).rayDiv(totalDebt.wadToRay()); return overallBorrowRate; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title ILendingRateOracle interface * @notice Interface for the Aave borrow rate oracle. Provides the average market borrow rate to be used as a base for the stable borrow rate calculations **/ interface ILendingRateOracle { /** @dev returns the market borrow rate in ray **/ function getMarketBorrowRate(address asset) external view returns (uint256); /** @dev sets the market borrow rate. Rate value must be in ray **/ function setMarketBorrowRate(address asset, uint256 rate) external; } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUiPoolDataProvider} from './interfaces/IUiPoolDataProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol'; import {IStableDebtToken} from '../interfaces/IStableDebtToken.sol'; import {WadRayMath} from '../protocol/libraries/math/WadRayMath.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import { DefaultReserveInterestRateStrategy } from '../protocol/lendingpool/DefaultReserveInterestRateStrategy.sol'; contract UiPoolDataProvider is IUiPoolDataProvider { using WadRayMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; address public constant MOCK_USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96; function getInterestRateStrategySlopes(DefaultReserveInterestRateStrategy interestRateStrategy) internal view returns ( uint256, uint256, uint256, uint256 ) { return ( interestRateStrategy.variableRateSlope1(), interestRateStrategy.variableRateSlope2(), interestRateStrategy.stableRateSlope1(), interestRateStrategy.stableRateSlope2() ); } function getReservesData(ILendingPoolAddressesProvider provider, address user) external view override returns ( AggregatedReserveData[] memory, UserReserveData[] memory, uint256 ) { ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); IPriceOracleGetter oracle = IPriceOracleGetter(provider.getPriceOracle()); address[] memory reserves = lendingPool.getReservesList(); DataTypes.UserConfigurationMap memory userConfig = lendingPool.getUserConfiguration(user); AggregatedReserveData[] memory reservesData = new AggregatedReserveData[](reserves.length); UserReserveData[] memory userReservesData = new UserReserveData[](user != address(0) ? reserves.length : 0); for (uint256 i = 0; i < reserves.length; i++) { AggregatedReserveData memory reserveData = reservesData[i]; reserveData.underlyingAsset = reserves[i]; // reserve current state DataTypes.ReserveData memory baseData = lendingPool.getReserveData(reserveData.underlyingAsset); reserveData.liquidityIndex = baseData.liquidityIndex; reserveData.variableBorrowIndex = baseData.variableBorrowIndex; reserveData.liquidityRate = baseData.currentLiquidityRate; reserveData.variableBorrowRate = baseData.currentVariableBorrowRate; reserveData.stableBorrowRate = baseData.currentStableBorrowRate; reserveData.lastUpdateTimestamp = baseData.lastUpdateTimestamp; reserveData.aTokenAddress = baseData.aTokenAddress; reserveData.stableDebtTokenAddress = baseData.stableDebtTokenAddress; reserveData.variableDebtTokenAddress = baseData.variableDebtTokenAddress; reserveData.interestRateStrategyAddress = baseData.interestRateStrategyAddress; reserveData.priceInEth = oracle.getAssetPrice(reserveData.underlyingAsset); reserveData.availableLiquidity = IERC20Detailed(reserveData.underlyingAsset).balanceOf( reserveData.aTokenAddress ); ( reserveData.totalPrincipalStableDebt, , reserveData.averageStableRate, reserveData.stableDebtLastUpdateTimestamp ) = IStableDebtToken(reserveData.stableDebtTokenAddress).getSupplyData(); reserveData.totalScaledVariableDebt = IVariableDebtToken(reserveData.variableDebtTokenAddress) .scaledTotalSupply(); // reserve configuration // we're getting this info from the aToken, because some of assets can be not compliant with ETC20Detailed reserveData.symbol = IERC20Detailed(reserveData.aTokenAddress).symbol(); reserveData.name = ''; ( reserveData.baseLTVasCollateral, reserveData.reserveLiquidationThreshold, reserveData.reserveLiquidationBonus, reserveData.decimals, reserveData.reserveFactor ) = baseData.configuration.getParamsMemory(); ( reserveData.isActive, reserveData.isFrozen, reserveData.borrowingEnabled, reserveData.stableBorrowRateEnabled ) = baseData.configuration.getFlagsMemory(); reserveData.usageAsCollateralEnabled = reserveData.baseLTVasCollateral != 0; ( reserveData.variableRateSlope1, reserveData.variableRateSlope2, reserveData.stableRateSlope1, reserveData.stableRateSlope2 ) = getInterestRateStrategySlopes( DefaultReserveInterestRateStrategy(reserveData.interestRateStrategyAddress) ); if (user != address(0)) { // user reserve data userReservesData[i].underlyingAsset = reserveData.underlyingAsset; userReservesData[i].scaledATokenBalance = IAToken(reserveData.aTokenAddress) .scaledBalanceOf(user); userReservesData[i].usageAsCollateralEnabledOnUser = userConfig.isUsingAsCollateral(i); if (userConfig.isBorrowing(i)) { userReservesData[i].scaledVariableDebt = IVariableDebtToken( reserveData .variableDebtTokenAddress ) .scaledBalanceOf(user); userReservesData[i].principalStableDebt = IStableDebtToken( reserveData .stableDebtTokenAddress ) .principalBalanceOf(user); if (userReservesData[i].principalStableDebt != 0) { userReservesData[i].stableBorrowRate = IStableDebtToken( reserveData .stableDebtTokenAddress ) .getUserStableRate(user); userReservesData[i].stableBorrowLastUpdateTimestamp = IStableDebtToken( reserveData .stableDebtTokenAddress ) .getUserLastUpdated(user); } } } } return (reservesData, userReservesData, oracle.getAssetPrice(MOCK_USD_ADDRESS)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; interface IUiPoolDataProvider { struct AggregatedReserveData { address underlyingAsset; string name; string symbol; uint256 decimals; uint256 baseLTVasCollateral; uint256 reserveLiquidationThreshold; uint256 reserveLiquidationBonus; uint256 reserveFactor; bool usageAsCollateralEnabled; bool borrowingEnabled; bool stableBorrowRateEnabled; bool isActive; bool isFrozen; // base data uint128 liquidityIndex; uint128 variableBorrowIndex; uint128 liquidityRate; uint128 variableBorrowRate; uint128 stableBorrowRate; uint40 lastUpdateTimestamp; address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; address interestRateStrategyAddress; // uint256 availableLiquidity; uint256 totalPrincipalStableDebt; uint256 averageStableRate; uint256 stableDebtLastUpdateTimestamp; uint256 totalScaledVariableDebt; uint256 priceInEth; uint256 variableRateSlope1; uint256 variableRateSlope2; uint256 stableRateSlope1; uint256 stableRateSlope2; } // // struct ReserveData { // uint256 averageStableBorrowRate; // uint256 totalLiquidity; // } struct UserReserveData { address underlyingAsset; uint256 scaledATokenBalance; bool usageAsCollateralEnabledOnUser; uint256 stableBorrowRate; uint256 scaledVariableDebt; uint256 principalStableDebt; uint256 stableBorrowLastUpdateTimestamp; } // // struct ATokenSupplyData { // string name; // string symbol; // uint8 decimals; // uint256 totalSupply; // address aTokenAddress; // } function getReservesData(ILendingPoolAddressesProvider provider, address user) external view returns ( AggregatedReserveData[] memory, UserReserveData[] memory, uint256 ); // function getUserReservesData(ILendingPoolAddressesProvider provider, address user) // external // view // returns (UserReserveData[] memory); // // function getAllATokenSupply(ILendingPoolAddressesProvider provider) // external // view // returns (ATokenSupplyData[] memory); // // function getATokenSupply(address[] calldata aTokens) // external // view // returns (ATokenSupplyData[] memory); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IStableDebtToken} from '../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; contract AaveProtocolDataProvider { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; address constant MKR = 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2; address constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; struct TokenData { string symbol; address tokenAddress; } ILendingPoolAddressesProvider public immutable ADDRESSES_PROVIDER; constructor(ILendingPoolAddressesProvider addressesProvider) public { ADDRESSES_PROVIDER = addressesProvider; } function getAllReservesTokens() external view returns (TokenData[] memory) { ILendingPool pool = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()); address[] memory reserves = pool.getReservesList(); TokenData[] memory reservesTokens = new TokenData[](reserves.length); for (uint256 i = 0; i < reserves.length; i++) { if (reserves[i] == MKR) { reservesTokens[i] = TokenData({symbol: 'MKR', tokenAddress: reserves[i]}); continue; } if (reserves[i] == ETH) { reservesTokens[i] = TokenData({symbol: 'ETH', tokenAddress: reserves[i]}); continue; } reservesTokens[i] = TokenData({ symbol: IERC20Detailed(reserves[i]).symbol(), tokenAddress: reserves[i] }); } return reservesTokens; } function getAllATokens() external view returns (TokenData[] memory) { ILendingPool pool = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()); address[] memory reserves = pool.getReservesList(); TokenData[] memory aTokens = new TokenData[](reserves.length); for (uint256 i = 0; i < reserves.length; i++) { DataTypes.ReserveData memory reserveData = pool.getReserveData(reserves[i]); aTokens[i] = TokenData({ symbol: IERC20Detailed(reserveData.aTokenAddress).symbol(), tokenAddress: reserveData.aTokenAddress }); } return aTokens; } function getReserveConfigurationData(address asset) external view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ) { DataTypes.ReserveConfigurationMap memory configuration = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getConfiguration(asset); (ltv, liquidationThreshold, liquidationBonus, decimals, reserveFactor) = configuration .getParamsMemory(); (isActive, isFrozen, borrowingEnabled, stableBorrowRateEnabled) = configuration .getFlagsMemory(); usageAsCollateralEnabled = liquidationThreshold > 0; } function getReserveData(address asset) external view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); return ( IERC20Detailed(asset).balanceOf(reserve.aTokenAddress), IERC20Detailed(reserve.stableDebtTokenAddress).totalSupply(), IERC20Detailed(reserve.variableDebtTokenAddress).totalSupply(), reserve.currentLiquidityRate, reserve.currentVariableBorrowRate, reserve.currentStableBorrowRate, IStableDebtToken(reserve.stableDebtTokenAddress).getAverageStableRate(), reserve.liquidityIndex, reserve.variableBorrowIndex, reserve.lastUpdateTimestamp ); } function getUserReserveData(address asset, address user) external view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); DataTypes.UserConfigurationMap memory userConfig = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getUserConfiguration(user); currentATokenBalance = IERC20Detailed(reserve.aTokenAddress).balanceOf(user); currentVariableDebt = IERC20Detailed(reserve.variableDebtTokenAddress).balanceOf(user); currentStableDebt = IERC20Detailed(reserve.stableDebtTokenAddress).balanceOf(user); principalStableDebt = IStableDebtToken(reserve.stableDebtTokenAddress).principalBalanceOf(user); scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledBalanceOf(user); liquidityRate = reserve.currentLiquidityRate; stableBorrowRate = IStableDebtToken(reserve.stableDebtTokenAddress).getUserStableRate(user); stableRateLastUpdated = IStableDebtToken(reserve.stableDebtTokenAddress).getUserLastUpdated( user ); usageAsCollateralEnabled = userConfig.isUsingAsCollateral(reserve.id); } function getReserveTokensAddresses(address asset) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); return ( reserve.aTokenAddress, reserve.stableDebtTokenAddress, reserve.variableDebtTokenAddress ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {DebtTokenBase} from './base/DebtTokenBase.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title VariableDebtToken * @notice Implements a variable debt token to track the borrowing positions of users * at variable rate mode * @author Aave **/ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { using WadRayMath for uint256; uint256 public constant DEBT_TOKEN_REVISION = 0x1; ILendingPool internal _pool; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) public override initializer { _setName(debtTokenName); _setSymbol(debtTokenSymbol); _setDecimals(debtTokenDecimals); _pool = pool; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), address(incentivesController), debtTokenDecimals, debtTokenName, debtTokenSymbol, params ); } /** * @dev Gets the revision of the stable debt token implementation * @return The debt token implementation revision **/ function getRevision() internal pure virtual override returns (uint256) { return DEBT_TOKEN_REVISION; } /** * @dev Calculates the accumulated debt balance of the user * @return The debt balance of the user **/ function balanceOf(address user) public view virtual override returns (uint256) { uint256 scaledBalance = super.balanceOf(user); if (scaledBalance == 0) { return 0; } return scaledBalance.rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } /** * @dev Mints debt token to the `onBehalfOf` address * - Only callable by the LendingPool * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external override onlyLendingPool returns (bool) { if (user != onBehalfOf) { _decreaseBorrowAllowance(onBehalfOf, user, amount); } uint256 previousBalance = super.balanceOf(onBehalfOf); uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); _mint(onBehalfOf, amountScaled); emit Transfer(address(0), onBehalfOf, amount); emit Mint(user, onBehalfOf, amount, index); return previousBalance == 0; } /** * @dev Burns user variable debt * - Only callable by the LendingPool * @param user The user whose debt is getting burned * @param amount The amount getting burned * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); emit Transfer(user, address(0), amount); emit Burn(user, amount, index); } /** * @dev Returns the principal debt balance of the user from * @return The debt balance of the user since the last burn/mint action **/ function scaledBalanceOf(address user) public view virtual override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the total supply of the variable debt token. Represents the total debt accrued by the users * @return The total supply **/ function totalSupply() public view virtual override returns (uint256) { return super.totalSupply().rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return the scaled total supply **/ function scaledTotalSupply() public view virtual override returns (uint256) { return super.totalSupply(); } /** * @dev Returns the principal balance of the user and principal total supply. * @param user The address of the user * @return The principal balance of the user * @return The principal total supply **/ function getScaledUserBalanceAndSupply(address user) external view override returns (uint256, uint256) { return (super.balanceOf(user), super.totalSupply()); } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } function _getUnderlyingAssetAddress() internal view override returns (address) { return _underlyingAsset; } function _getLendingPool() internal view override returns (ILendingPool) { return _pool; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from '../../../interfaces/ILendingPool.sol'; import {ICreditDelegationToken} from '../../../interfaces/ICreditDelegationToken.sol'; import { VersionedInitializable } from '../../libraries/aave-upgradeability/VersionedInitializable.sol'; import {IncentivizedERC20} from '../IncentivizedERC20.sol'; import {Errors} from '../../libraries/helpers/Errors.sol'; /** * @title DebtTokenBase * @notice Base contract for different types of debt tokens, like StableDebtToken or VariableDebtToken * @author Aave */ abstract contract DebtTokenBase is IncentivizedERC20('DEBTTOKEN_IMPL', 'DEBTTOKEN_IMPL', 0), VersionedInitializable, ICreditDelegationToken { mapping(address => mapping(address => uint256)) internal _borrowAllowances; /** * @dev Only lending pool can call functions marked by this modifier **/ modifier onlyLendingPool { require(_msgSender() == address(_getLendingPool()), Errors.CT_CALLER_MUST_BE_LENDING_POOL); _; } /** * @dev delegates borrowing power to a user on the specific debt token * @param delegatee the address receiving the delegated borrowing power * @param amount the maximum amount being delegated. Delegation will still * respect the liquidation constraints (even if delegated, a delegatee cannot * force a delegator HF to go below 1) **/ function approveDelegation(address delegatee, uint256 amount) external override { _borrowAllowances[_msgSender()][delegatee] = amount; emit BorrowAllowanceDelegated(_msgSender(), delegatee, _getUnderlyingAssetAddress(), amount); } /** * @dev returns the borrow allowance of the user * @param fromUser The user to giving allowance * @param toUser The user to give allowance to * @return the current allowance of toUser **/ function borrowAllowance(address fromUser, address toUser) external view override returns (uint256) { return _borrowAllowances[fromUser][toUser]; } /** * @dev Being non transferrable, the debt token does not implement any of the * standard ERC20 functions for transfer and allowance. **/ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { recipient; amount; revert('TRANSFER_NOT_SUPPORTED'); } function allowance(address owner, address spender) public view virtual override returns (uint256) { owner; spender; revert('ALLOWANCE_NOT_SUPPORTED'); } function approve(address spender, uint256 amount) public virtual override returns (bool) { spender; amount; revert('APPROVAL_NOT_SUPPORTED'); } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { sender; recipient; amount; revert('TRANSFER_NOT_SUPPORTED'); } function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) { spender; addedValue; revert('ALLOWANCE_NOT_SUPPORTED'); } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) { spender; subtractedValue; revert('ALLOWANCE_NOT_SUPPORTED'); } function _decreaseBorrowAllowance( address delegator, address delegatee, uint256 amount ) internal { uint256 newAllowance = _borrowAllowances[delegator][delegatee].sub(amount, Errors.BORROW_ALLOWANCE_NOT_ENOUGH); _borrowAllowances[delegator][delegatee] = newAllowance; emit BorrowAllowanceDelegated(delegator, delegatee, _getUnderlyingAssetAddress(), newAllowance); } function _getUnderlyingAssetAddress() internal view virtual returns (address); function _getLendingPool() internal view virtual returns (ILendingPool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface ICreditDelegationToken { event BorrowAllowanceDelegated( address indexed fromUser, address indexed toUser, address asset, uint256 amount ); /** * @dev delegates borrowing power to a user on the specific debt token * @param delegatee the address receiving the delegated borrowing power * @param amount the maximum amount being delegated. Delegation will still * respect the liquidation constraints (even if delegated, a delegatee cannot * force a delegator HF to go below 1) **/ function approveDelegation(address delegatee, uint256 amount) external; /** * @dev returns the borrow allowance of the user * @param fromUser The user to giving allowance * @param toUser The user to give allowance to * @return the current allowance of toUser **/ function borrowAllowance(address fromUser, address toUser) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Context} from '../../dependencies/openzeppelin/contracts/Context.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title ERC20 * @notice Basic ERC20 implementation * @author Aave, inspired by the Openzeppelin ERC20 implementation **/ abstract contract IncentivizedERC20 is Context, IERC20, IERC20Detailed { using SafeMath for uint256; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 internal _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor( string memory name, string memory symbol, uint8 decimals ) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return The name of the token **/ function name() public view override returns (string memory) { return _name; } /** * @return The symbol of the token **/ function symbol() public view override returns (string memory) { return _symbol; } /** * @return The decimals of the token **/ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total supply of the token **/ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @return The balance of the token **/ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @return Abstract function implemented by the child aToken/debtToken. * Done this way in order to not break compatibility with previous versions of aTokens/debtTokens **/ function _getIncentivesController() internal view virtual returns(IAaveIncentivesController); /** * @dev Executes a transfer of tokens from _msgSender() to recipient * @param recipient The recipient of the tokens * @param amount The amount of tokens being transferred * @return `true` if the transfer succeeds, `false` otherwise **/ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); emit Transfer(_msgSender(), recipient, amount); return true; } /** * @dev Returns the allowance of spender on the tokens owned by owner * @param owner The owner of the tokens * @param spender The user allowed to spend the owner's tokens * @return The amount of owner's tokens spender is allowed to spend **/ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev Allows `spender` to spend the tokens owned by _msgSender() * @param spender The user allowed to spend _msgSender() tokens * @return `true` **/ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev Executes a transfer of token from sender to recipient, if _msgSender() is allowed to do so * @param sender The owner of the tokens * @param recipient The recipient of the tokens * @param amount The amount of tokens being transferred * @return `true` if the transfer succeeds, `false` otherwise **/ 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') ); emit Transfer(sender, recipient, amount); return true; } /** * @dev Increases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param addedValue The amount being added to the allowance * @return `true` **/ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Decreases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param subtractedValue The amount being subtracted to the allowance * @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 _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 oldSenderBalance = _balances[sender]; _balances[sender] = oldSenderBalance.sub(amount, 'ERC20: transfer amount exceeds balance'); uint256 oldRecipientBalance = _balances[recipient]; _balances[recipient] = _balances[recipient].add(amount); if (address(_getIncentivesController()) != address(0)) { uint256 currentTotalSupply = _totalSupply; _getIncentivesController().handleAction(sender, currentTotalSupply, oldSenderBalance); if (sender != recipient) { _getIncentivesController().handleAction(recipient, currentTotalSupply, oldRecipientBalance); } } } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: mint to the zero address'); _beforeTokenTransfer(address(0), account, amount); uint256 oldTotalSupply = _totalSupply; _totalSupply = oldTotalSupply.add(amount); uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.add(amount); if (address(_getIncentivesController()) != address(0)) { _getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance); } } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: burn from the zero address'); _beforeTokenTransfer(account, address(0), amount); uint256 oldTotalSupply = _totalSupply; _totalSupply = oldTotalSupply.sub(amount); uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.sub(amount, 'ERC20: burn amount exceeds balance'); if (address(_getIncentivesController()) != address(0)) { _getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance); } } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), 'ERC20: approve from the zero address'); require(spender != address(0), 'ERC20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setName(string memory newName) internal { _name = newName; } function _setSymbol(string memory newSymbol) internal { _symbol = newSymbol; } function _setDecimals(uint8 newDecimals) internal { _decimals = newDecimals; } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {VariableDebtToken} from '../../protocol/tokenization/VariableDebtToken.sol'; contract MockVariableDebtToken is VariableDebtToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {AToken} from '../../protocol/tokenization/AToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; contract MockAToken is AToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {IncentivizedERC20} from './IncentivizedERC20.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title Aave ERC20 AToken * @dev Implementation of the interest bearing token for the Aave protocol * @author Aave */ contract AToken is VersionedInitializable, IncentivizedERC20('ATOKEN_IMPL', 'ATOKEN_IMPL', 0), IAToken { using WadRayMath for uint256; using SafeERC20 for IERC20; bytes public constant EIP712_REVISION = bytes('1'); bytes32 internal constant EIP712_DOMAIN = keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'); bytes32 public constant PERMIT_TYPEHASH = keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)'); uint256 public constant ATOKEN_REVISION = 0x1; /// @dev owner => next valid nonce to submit with permit() mapping(address => uint256) public _nonces; bytes32 public DOMAIN_SEPARATOR; ILendingPool internal _pool; address internal _treasury; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; modifier onlyLendingPool { require(_msgSender() == address(_pool), Errors.CT_CALLER_MUST_BE_LENDING_POOL); _; } function getRevision() internal pure virtual override returns (uint256) { return ATOKEN_REVISION; } /** * @dev Initializes the aToken * @param pool The address of the lending pool where this aToken will be used * @param treasury The address of the Aave treasury, receiving the fees on this aToken * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's * @param aTokenName The name of the aToken * @param aTokenSymbol The symbol of the aToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external override initializer { uint256 chainId; //solium-disable-next-line assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN, keccak256(bytes(aTokenName)), keccak256(EIP712_REVISION), chainId, address(this) ) ); _setName(aTokenName); _setSymbol(aTokenSymbol); _setDecimals(aTokenDecimals); _pool = pool; _treasury = treasury; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), treasury, address(incentivesController), aTokenDecimals, aTokenName, aTokenSymbol, params ); } /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * - Only callable by the LendingPool, as extra state updates there need to be managed * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); IERC20(_underlyingAsset).safeTransfer(receiverOfUnderlying, amount); emit Transfer(user, address(0), amount); emit Burn(user, receiverOfUnderlying, amount, index); } /** * @dev Mints `amount` aTokens to `user` * - Only callable by the LendingPool, as extra state updates there need to be managed * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external override onlyLendingPool returns (bool) { uint256 previousBalance = super.balanceOf(user); uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); _mint(user, amountScaled); emit Transfer(address(0), user, amount); emit Mint(user, amount, index); return previousBalance == 0; } /** * @dev Mints aTokens to the reserve treasury * - Only callable by the LendingPool * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external override onlyLendingPool { if (amount == 0) { return; } address treasury = _treasury; // Compared to the normal mint, we don't check for rounding errors. // The amount to mint can easily be very small since it is a fraction of the interest ccrued. // In that case, the treasury will experience a (very small) loss, but it // wont cause potentially valid transactions to fail. _mint(treasury, amount.rayDiv(index)); emit Transfer(address(0), treasury, amount); emit Mint(treasury, amount, index); } /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * - Only callable by the LendingPool * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external override onlyLendingPool { // Being a normal transfer, the Transfer() and BalanceTransfer() are emitted // so no need to emit a specific event here _transfer(from, to, value, false); emit Transfer(from, to, value); } /** * @dev Calculates the balance of the user: principal balance + interest generated by the principal * @param user The user whose balance is calculated * @return The balance of the user **/ function balanceOf(address user) public view override(IncentivizedERC20, IERC20) returns (uint256) { return super.balanceOf(user).rayMul(_pool.getReserveNormalizedIncome(_underlyingAsset)); } /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view override returns (uint256, uint256) { return (super.balanceOf(user), super.totalSupply()); } /** * @dev calculates the total supply of the specific aToken * since the balance of every single user increases over time, the total supply * does that too. * @return the current total supply **/ function totalSupply() public view override(IncentivizedERC20, IERC20) returns (uint256) { uint256 currentSupplyScaled = super.totalSupply(); if (currentSupplyScaled == 0) { return 0; } return currentSupplyScaled.rayMul(_pool.getReserveNormalizedIncome(_underlyingAsset)); } /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return the scaled total supply **/ function scaledTotalSupply() public view virtual override returns (uint256) { return super.totalSupply(); } /** * @dev Returns the address of the Aave treasury, receiving the fees on this aToken **/ function RESERVE_TREASURY_ADDRESS() public view returns (address) { return _treasury; } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } /** * @dev For internal usage in the logic of the parent contract IncentivizedERC20 **/ function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param target The recipient of the aTokens * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address target, uint256 amount) external override onlyLendingPool returns (uint256) { IERC20(_underlyingAsset).safeTransfer(target, amount); return amount; } /** * @dev Invoked to execute actions on the aToken side after a repayment. * @param user The user executing the repayment * @param amount The amount getting repaid **/ function handleRepayment(address user, uint256 amount) external override onlyLendingPool {} /** * @dev implements the permit function as for * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md * @param owner The owner of the funds * @param spender The spender * @param value The amount * @param deadline The deadline timestamp, type(uint256).max for max deadline * @param v Signature param * @param s Signature param * @param r Signature param */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(owner != address(0), 'INVALID_OWNER'); //solium-disable-next-line require(block.timestamp <= deadline, 'INVALID_EXPIRATION'); uint256 currentValidNonce = _nonces[owner]; bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) ) ); require(owner == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE'); _nonces[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } /** * @dev Transfers the aTokens between two users. Validates the transfer * (ie checks for valid HF after the transfer) if required * @param from The source address * @param to The destination address * @param amount The amount getting transferred * @param validate `true` if the transfer needs to be validated **/ function _transfer( address from, address to, uint256 amount, bool validate ) internal { address underlyingAsset = _underlyingAsset; ILendingPool pool = _pool; uint256 index = pool.getReserveNormalizedIncome(underlyingAsset); uint256 fromBalanceBefore = super.balanceOf(from).rayMul(index); uint256 toBalanceBefore = super.balanceOf(to).rayMul(index); super._transfer(from, to, amount.rayDiv(index)); if (validate) { pool.finalizeTransfer(underlyingAsset, from, to, amount, fromBalanceBefore, toBalanceBefore); } emit BalanceTransfer(from, to, amount, index); } /** * @dev Overrides the parent _transfer to force validated transfer() and transferFrom() * @param from The source address * @param to The destination address * @param amount The amount getting transferred **/ function _transfer( address from, address to, uint256 amount ) internal override { _transfer(from, to, amount, true); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IDelegationToken} from '../../interfaces/IDelegationToken.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {AToken} from './AToken.sol'; /** * @title Aave AToken enabled to delegate voting power of the underlying asset to a different address * @dev The underlying asset needs to be compatible with the COMP delegation interface * @author Aave */ contract DelegationAwareAToken is AToken { modifier onlyPoolAdmin { require( _msgSender() == ILendingPool(_pool).getAddressesProvider().getPoolAdmin(), Errors.CALLER_NOT_POOL_ADMIN ); _; } /** * @dev Delegates voting power of the underlying asset to a `delegatee` address * @param delegatee The address that will receive the delegation **/ function delegateUnderlyingTo(address delegatee) external onlyPoolAdmin { IDelegationToken(_underlyingAsset).delegate(delegatee); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IDelegationToken * @dev Implements an interface for tokens with delegation COMP/UNI compatible * @author Aave **/ interface IDelegationToken { function delegate(address delegatee) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; import { ILendingPoolAddressesProviderRegistry } from '../../interfaces/ILendingPoolAddressesProviderRegistry.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; /** * @title LendingPoolAddressesProviderRegistry contract * @dev Main registry of LendingPoolAddressesProvider of multiple Aave protocol's markets * - Used for indexing purposes of Aave protocol's markets * - The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with, * for example with `0` for the Aave main market and `1` for the next created * @author Aave **/ contract LendingPoolAddressesProviderRegistry is Ownable, ILendingPoolAddressesProviderRegistry { mapping(address => uint256) private _addressesProviders; address[] private _addressesProvidersList; /** * @dev Returns the list of registered addresses provider * @return The list of addresses provider, potentially containing address(0) elements **/ function getAddressesProvidersList() external view override returns (address[] memory) { address[] memory addressesProvidersList = _addressesProvidersList; uint256 maxLength = addressesProvidersList.length; address[] memory activeProviders = new address[](maxLength); for (uint256 i = 0; i < maxLength; i++) { if (_addressesProviders[addressesProvidersList[i]] > 0) { activeProviders[i] = addressesProvidersList[i]; } } return activeProviders; } /** * @dev Registers an addresses provider * @param provider The address of the new LendingPoolAddressesProvider * @param id The id for the new LendingPoolAddressesProvider, referring to the market it belongs to **/ function registerAddressesProvider(address provider, uint256 id) external override onlyOwner { require(id != 0, Errors.LPAPR_INVALID_ADDRESSES_PROVIDER_ID); _addressesProviders[provider] = id; _addToAddressesProvidersList(provider); emit AddressesProviderRegistered(provider); } /** * @dev Removes a LendingPoolAddressesProvider from the list of registered addresses provider * @param provider The LendingPoolAddressesProvider address **/ function unregisterAddressesProvider(address provider) external override onlyOwner { require(_addressesProviders[provider] > 0, Errors.LPAPR_PROVIDER_NOT_REGISTERED); _addressesProviders[provider] = 0; emit AddressesProviderUnregistered(provider); } /** * @dev Returns the id on a registered LendingPoolAddressesProvider * @return The id or 0 if the LendingPoolAddressesProvider is not registered */ function getAddressesProviderIdByAddress(address addressesProvider) external view override returns (uint256) { return _addressesProviders[addressesProvider]; } function _addToAddressesProvidersList(address provider) internal { uint256 providersCount = _addressesProvidersList.length; for (uint256 i = 0; i < providersCount; i++) { if (_addressesProvidersList[i] == provider) { return; } } _addressesProvidersList.push(provider); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title LendingPoolAddressesProviderRegistry contract * @dev Main registry of LendingPoolAddressesProvider of multiple Aave protocol's markets * - Used for indexing purposes of Aave protocol's markets * - The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with, * for example with `0` for the Aave main market and `1` for the next created * @author Aave **/ interface ILendingPoolAddressesProviderRegistry { event AddressesProviderRegistered(address indexed newAddress); event AddressesProviderUnregistered(address indexed newAddress); function getAddressesProvidersList() external view returns (address[] memory); function getAddressesProviderIdByAddress(address addressesProvider) external view returns (uint256); function registerAddressesProvider(address provider, uint256 id) external; function unregisterAddressesProvider(address provider) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IChainlinkAggregator} from '../interfaces/IChainlinkAggregator.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; /// @title AaveOracle /// @author Aave /// @notice Proxy smart contract to get the price of an asset from a price source, with Chainlink Aggregator /// smart contracts as primary option /// - If the returned price by a Chainlink aggregator is <= 0, the call is forwarded to a fallbackOracle /// - Owned by the Aave governance system, allowed to add sources for assets, replace them /// and change the fallbackOracle contract AaveOracle is IPriceOracleGetter, Ownable { using SafeERC20 for IERC20; event WethSet(address indexed weth); event AssetSourceUpdated(address indexed asset, address indexed source); event FallbackOracleUpdated(address indexed fallbackOracle); mapping(address => IChainlinkAggregator) private assetsSources; IPriceOracleGetter private _fallbackOracle; address public immutable WETH; /// @notice Constructor /// @param assets The addresses of the assets /// @param sources The address of the source of each asset /// @param fallbackOracle The address of the fallback oracle to use if the data of an /// aggregator is not consistent constructor( address[] memory assets, address[] memory sources, address fallbackOracle, address weth ) public { _setFallbackOracle(fallbackOracle); _setAssetsSources(assets, sources); WETH = weth; emit WethSet(weth); } /// @notice External function called by the Aave governance to set or replace sources of assets /// @param assets The addresses of the assets /// @param sources The address of the source of each asset function setAssetSources(address[] calldata assets, address[] calldata sources) external onlyOwner { _setAssetsSources(assets, sources); } /// @notice Sets the fallbackOracle /// - Callable only by the Aave governance /// @param fallbackOracle The address of the fallbackOracle function setFallbackOracle(address fallbackOracle) external onlyOwner { _setFallbackOracle(fallbackOracle); } /// @notice Internal function to set the sources for each asset /// @param assets The addresses of the assets /// @param sources The address of the source of each asset function _setAssetsSources(address[] memory assets, address[] memory sources) internal { require(assets.length == sources.length, 'INCONSISTENT_PARAMS_LENGTH'); for (uint256 i = 0; i < assets.length; i++) { assetsSources[assets[i]] = IChainlinkAggregator(sources[i]); emit AssetSourceUpdated(assets[i], sources[i]); } } /// @notice Internal function to set the fallbackOracle /// @param fallbackOracle The address of the fallbackOracle function _setFallbackOracle(address fallbackOracle) internal { _fallbackOracle = IPriceOracleGetter(fallbackOracle); emit FallbackOracleUpdated(fallbackOracle); } /// @notice Gets an asset price by address /// @param asset The asset address function getAssetPrice(address asset) public view override returns (uint256) { IChainlinkAggregator source = assetsSources[asset]; if (asset == WETH) { return 1 ether; } else if (address(source) == address(0)) { return _fallbackOracle.getAssetPrice(asset); } else { int256 price = IChainlinkAggregator(source).latestAnswer(); if (price > 0) { return uint256(price); } else { return _fallbackOracle.getAssetPrice(asset); } } } /// @notice Gets a list of prices from a list of assets addresses /// @param assets The list of assets addresses function getAssetsPrices(address[] calldata assets) external view returns (uint256[] memory) { uint256[] memory prices = new uint256[](assets.length); for (uint256 i = 0; i < assets.length; i++) { prices[i] = getAssetPrice(assets[i]); } return prices; } /// @notice Gets the address of the source for an asset address /// @param asset The address of the asset /// @return address The address of the source function getSourceOfAsset(address asset) external view returns (address) { return address(assetsSources[asset]); } /// @notice Gets the address of the fallback oracle /// @return address The addres of the fallback oracle function getFallbackOracle() external view returns (address) { return address(_fallbackOracle); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IChainlinkAggregator { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); event NewRound(uint256 indexed roundId, address indexed startedBy); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import { InitializableImmutableAdminUpgradeabilityProxy } from '../libraries/aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {IInitializableDebtToken} from '../../interfaces/IInitializableDebtToken.sol'; import {IInitializableAToken} from '../../interfaces/IInitializableAToken.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; import {ILendingPoolConfigurator} from '../../interfaces/ILendingPoolConfigurator.sol'; /** * @title LendingPoolConfigurator contract * @author Aave * @dev Implements the configuration methods for the Aave protocol **/ contract LendingPoolConfigurator is VersionedInitializable, ILendingPoolConfigurator { using SafeMath for uint256; using PercentageMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; ILendingPoolAddressesProvider internal addressesProvider; ILendingPool internal pool; modifier onlyPoolAdmin { require(addressesProvider.getPoolAdmin() == msg.sender, Errors.CALLER_NOT_POOL_ADMIN); _; } modifier onlyEmergencyAdmin { require( addressesProvider.getEmergencyAdmin() == msg.sender, Errors.LPC_CALLER_NOT_EMERGENCY_ADMIN ); _; } uint256 internal constant CONFIGURATOR_REVISION = 0x1; function getRevision() internal pure override returns (uint256) { return CONFIGURATOR_REVISION; } function initialize(ILendingPoolAddressesProvider provider) public initializer { addressesProvider = provider; pool = ILendingPool(addressesProvider.getLendingPool()); } /** * @dev Initializes reserves in batch **/ function batchInitReserve(InitReserveInput[] calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; for (uint256 i = 0; i < input.length; i++) { _initReserve(cachedPool, input[i]); } } function _initReserve(ILendingPool pool, InitReserveInput calldata input) internal { address aTokenProxyAddress = _initTokenWithProxy( input.aTokenImpl, abi.encodeWithSelector( IInitializableAToken.initialize.selector, pool, input.treasury, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.aTokenName, input.aTokenSymbol, input.params ) ); address stableDebtTokenProxyAddress = _initTokenWithProxy( input.stableDebtTokenImpl, abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, pool, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.stableDebtTokenName, input.stableDebtTokenSymbol, input.params ) ); address variableDebtTokenProxyAddress = _initTokenWithProxy( input.variableDebtTokenImpl, abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, pool, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.variableDebtTokenName, input.variableDebtTokenSymbol, input.params ) ); pool.initReserve( input.underlyingAsset, aTokenProxyAddress, stableDebtTokenProxyAddress, variableDebtTokenProxyAddress, input.interestRateStrategyAddress ); DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(input.underlyingAsset); currentConfig.setDecimals(input.underlyingAssetDecimals); currentConfig.setActive(true); currentConfig.setFrozen(false); pool.setConfiguration(input.underlyingAsset, currentConfig.data); emit ReserveInitialized( input.underlyingAsset, aTokenProxyAddress, stableDebtTokenProxyAddress, variableDebtTokenProxyAddress, input.interestRateStrategyAddress ); } /** * @dev Updates the aToken implementation for the reserve **/ function updateAToken(UpdateATokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableAToken.initialize.selector, cachedPool, input.treasury, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.aTokenAddress, input.implementation, encodedCall ); emit ATokenUpgraded(input.asset, reserveData.aTokenAddress, input.implementation); } /** * @dev Updates the stable debt token implementation for the reserve **/ function updateStableDebtToken(UpdateDebtTokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, cachedPool, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.stableDebtTokenAddress, input.implementation, encodedCall ); emit StableDebtTokenUpgraded( input.asset, reserveData.stableDebtTokenAddress, input.implementation ); } /** * @dev Updates the variable debt token implementation for the asset **/ function updateVariableDebtToken(UpdateDebtTokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, cachedPool, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.variableDebtTokenAddress, input.implementation, encodedCall ); emit VariableDebtTokenUpgraded( input.asset, reserveData.variableDebtTokenAddress, input.implementation ); } /** * @dev Enables borrowing on a reserve * @param asset The address of the underlying asset of the reserve * @param stableBorrowRateEnabled True if stable borrow rate needs to be enabled by default on this reserve **/ function enableBorrowingOnReserve(address asset, bool stableBorrowRateEnabled) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setBorrowingEnabled(true); currentConfig.setStableRateBorrowingEnabled(stableBorrowRateEnabled); pool.setConfiguration(asset, currentConfig.data); emit BorrowingEnabledOnReserve(asset, stableBorrowRateEnabled); } /** * @dev Disables borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function disableBorrowingOnReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setBorrowingEnabled(false); pool.setConfiguration(asset, currentConfig.data); emit BorrowingDisabledOnReserve(asset); } /** * @dev Configures the reserve collateralization parameters * all the values are expressed in percentages with two decimals of precision. A valid value is 10000, which means 100.00% * @param asset The address of the underlying asset of the reserve * @param ltv The loan to value of the asset when used as collateral * @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized * @param liquidationBonus The bonus liquidators receive to liquidate this asset. The values is always above 100%. A value of 105% * means the liquidator will receive a 5% bonus **/ function configureReserveAsCollateral( address asset, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); //validation of the parameters: the LTV can //only be lower or equal than the liquidation threshold //(otherwise a loan against the asset would cause instantaneous liquidation) require(ltv <= liquidationThreshold, Errors.LPC_INVALID_CONFIGURATION); if (liquidationThreshold != 0) { //liquidation bonus must be bigger than 100.00%, otherwise the liquidator would receive less //collateral than needed to cover the debt require( liquidationBonus > PercentageMath.PERCENTAGE_FACTOR, Errors.LPC_INVALID_CONFIGURATION ); //if threshold * bonus is less than PERCENTAGE_FACTOR, it's guaranteed that at the moment //a loan is taken there is enough collateral available to cover the liquidation bonus require( liquidationThreshold.percentMul(liquidationBonus) <= PercentageMath.PERCENTAGE_FACTOR, Errors.LPC_INVALID_CONFIGURATION ); } else { require(liquidationBonus == 0, Errors.LPC_INVALID_CONFIGURATION); //if the liquidation threshold is being set to 0, // the reserve is being disabled as collateral. To do so, //we need to ensure no liquidity is deposited _checkNoLiquidity(asset); } currentConfig.setLtv(ltv); currentConfig.setLiquidationThreshold(liquidationThreshold); currentConfig.setLiquidationBonus(liquidationBonus); pool.setConfiguration(asset, currentConfig.data); emit CollateralConfigurationChanged(asset, ltv, liquidationThreshold, liquidationBonus); } /** * @dev Enable stable rate borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function enableReserveStableRate(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setStableRateBorrowingEnabled(true); pool.setConfiguration(asset, currentConfig.data); emit StableRateEnabledOnReserve(asset); } /** * @dev Disable stable rate borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function disableReserveStableRate(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setStableRateBorrowingEnabled(false); pool.setConfiguration(asset, currentConfig.data); emit StableRateDisabledOnReserve(asset); } /** * @dev Activates a reserve * @param asset The address of the underlying asset of the reserve **/ function activateReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setActive(true); pool.setConfiguration(asset, currentConfig.data); emit ReserveActivated(asset); } /** * @dev Deactivates a reserve * @param asset The address of the underlying asset of the reserve **/ function deactivateReserve(address asset) external onlyPoolAdmin { _checkNoLiquidity(asset); DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setActive(false); pool.setConfiguration(asset, currentConfig.data); emit ReserveDeactivated(asset); } /** * @dev Freezes a reserve. A frozen reserve doesn't allow any new deposit, borrow or rate swap * but allows repayments, liquidations, rate rebalances and withdrawals * @param asset The address of the underlying asset of the reserve **/ function freezeReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setFrozen(true); pool.setConfiguration(asset, currentConfig.data); emit ReserveFrozen(asset); } /** * @dev Unfreezes a reserve * @param asset The address of the underlying asset of the reserve **/ function unfreezeReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setFrozen(false); pool.setConfiguration(asset, currentConfig.data); emit ReserveUnfrozen(asset); } /** * @dev Updates the reserve factor of a reserve * @param asset The address of the underlying asset of the reserve * @param reserveFactor The new reserve factor of the reserve **/ function setReserveFactor(address asset, uint256 reserveFactor) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setReserveFactor(reserveFactor); pool.setConfiguration(asset, currentConfig.data); emit ReserveFactorChanged(asset, reserveFactor); } /** * @dev Sets the interest rate strategy of a reserve * @param asset The address of the underlying asset of the reserve * @param rateStrategyAddress The new address of the interest strategy contract **/ function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) external onlyPoolAdmin { pool.setReserveInterestRateStrategyAddress(asset, rateStrategyAddress); emit ReserveInterestRateStrategyChanged(asset, rateStrategyAddress); } /** * @dev pauses or unpauses all the actions of the protocol, including aToken transfers * @param val true if protocol needs to be paused, false otherwise **/ function setPoolPause(bool val) external onlyEmergencyAdmin { pool.setPause(val); } function _initTokenWithProxy(address implementation, bytes memory initParams) internal returns (address) { InitializableImmutableAdminUpgradeabilityProxy proxy = new InitializableImmutableAdminUpgradeabilityProxy(address(this)); proxy.initialize(implementation, initParams); return address(proxy); } function _upgradeTokenImplementation( address proxyAddress, address implementation, bytes memory initParams ) internal { InitializableImmutableAdminUpgradeabilityProxy proxy = InitializableImmutableAdminUpgradeabilityProxy(payable(proxyAddress)); proxy.upgradeToAndCall(implementation, initParams); } function _checkNoLiquidity(address asset) internal view { DataTypes.ReserveData memory reserveData = pool.getReserveData(asset); uint256 availableLiquidity = IERC20Detailed(asset).balanceOf(reserveData.aTokenAddress); require( availableLiquidity == 0 && reserveData.currentLiquidityRate == 0, Errors.LPC_RESERVE_LIQUIDITY_NOT_0 ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseImmutableAdminUpgradeabilityProxy.sol'; import '../../../dependencies/openzeppelin/upgradeability/InitializableUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends BaseAdminUpgradeabilityProxy with an initializer function */ contract InitializableImmutableAdminUpgradeabilityProxy is BaseImmutableAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { constructor(address admin) public BaseImmutableAdminUpgradeabilityProxy(admin) {} /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseImmutableAdminUpgradeabilityProxy, Proxy) { BaseImmutableAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface ILendingPoolConfigurator { struct InitReserveInput { address aTokenImpl; address stableDebtTokenImpl; address variableDebtTokenImpl; uint8 underlyingAssetDecimals; address interestRateStrategyAddress; address underlyingAsset; address treasury; address incentivesController; string underlyingAssetName; string aTokenName; string aTokenSymbol; string variableDebtTokenName; string variableDebtTokenSymbol; string stableDebtTokenName; string stableDebtTokenSymbol; bytes params; } struct UpdateATokenInput { address asset; address treasury; address incentivesController; string name; string symbol; address implementation; bytes params; } struct UpdateDebtTokenInput { address asset; address incentivesController; string name; string symbol; address implementation; bytes params; } /** * @dev Emitted when a reserve is initialized. * @param asset The address of the underlying asset of the reserve * @param aToken The address of the associated aToken contract * @param stableDebtToken The address of the associated stable rate debt token * @param variableDebtToken The address of the associated variable rate debt token * @param interestRateStrategyAddress The address of the interest rate strategy for the reserve **/ event ReserveInitialized( address indexed asset, address indexed aToken, address stableDebtToken, address variableDebtToken, address interestRateStrategyAddress ); /** * @dev Emitted when borrowing is enabled on a reserve * @param asset The address of the underlying asset of the reserve * @param stableRateEnabled True if stable rate borrowing is enabled, false otherwise **/ event BorrowingEnabledOnReserve(address indexed asset, bool stableRateEnabled); /** * @dev Emitted when borrowing is disabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event BorrowingDisabledOnReserve(address indexed asset); /** * @dev Emitted when the collateralization risk parameters for the specified asset are updated. * @param asset The address of the underlying asset of the reserve * @param ltv The loan to value of the asset when used as collateral * @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized * @param liquidationBonus The bonus liquidators receive to liquidate this asset **/ event CollateralConfigurationChanged( address indexed asset, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ); /** * @dev Emitted when stable rate borrowing is enabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event StableRateEnabledOnReserve(address indexed asset); /** * @dev Emitted when stable rate borrowing is disabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event StableRateDisabledOnReserve(address indexed asset); /** * @dev Emitted when a reserve is activated * @param asset The address of the underlying asset of the reserve **/ event ReserveActivated(address indexed asset); /** * @dev Emitted when a reserve is deactivated * @param asset The address of the underlying asset of the reserve **/ event ReserveDeactivated(address indexed asset); /** * @dev Emitted when a reserve is frozen * @param asset The address of the underlying asset of the reserve **/ event ReserveFrozen(address indexed asset); /** * @dev Emitted when a reserve is unfrozen * @param asset The address of the underlying asset of the reserve **/ event ReserveUnfrozen(address indexed asset); /** * @dev Emitted when a reserve factor is updated * @param asset The address of the underlying asset of the reserve * @param factor The new reserve factor **/ event ReserveFactorChanged(address indexed asset, uint256 factor); /** * @dev Emitted when the reserve decimals are updated * @param asset The address of the underlying asset of the reserve * @param decimals The new decimals **/ event ReserveDecimalsChanged(address indexed asset, uint256 decimals); /** * @dev Emitted when a reserve interest strategy contract is updated * @param asset The address of the underlying asset of the reserve * @param strategy The new address of the interest strategy contract **/ event ReserveInterestRateStrategyChanged(address indexed asset, address strategy); /** * @dev Emitted when an aToken implementation is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The aToken proxy address * @param implementation The new aToken implementation **/ event ATokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); /** * @dev Emitted when the implementation of a stable debt token is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The stable debt token proxy address * @param implementation The new aToken implementation **/ event StableDebtTokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); /** * @dev Emitted when the implementation of a variable debt token is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The variable debt token proxy address * @param implementation The new aToken implementation **/ event VariableDebtTokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import '../../../dependencies/openzeppelin/upgradeability/BaseUpgradeabilityProxy.sol'; /** * @title BaseImmutableAdminUpgradeabilityProxy * @author Aave, inspired by the OpenZeppelin upgradeability proxy pattern * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. The admin role is stored in an immutable, which * helps saving transactions costs * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseImmutableAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { address immutable ADMIN; constructor(address admin) public { ADMIN = admin; } modifier ifAdmin() { if (msg.sender == ADMIN) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return ADMIN; } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); (bool success, ) = newImplementation.delegatecall(data); require(success); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal virtual override { require(msg.sender != ADMIN, 'Cannot call fallback function from the proxy admin'); super._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseUpgradeabilityProxy.sol'; /** * @title InitializableUpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing * implementation and init data. */ contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './Proxy.sol'; import '../contracts/Address.sol'; /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal view override returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; //solium-disable-next-line assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require( Address.isContract(newImplementation), 'Cannot set a proxy implementation to a non-contract address' ); bytes32 slot = IMPLEMENTATION_SLOT; //solium-disable-next-line assembly { sstore(slot, newImplementation) } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.0; /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback() external payable { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { //solium-disable-next-line assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual {} /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {DebtTokenBase} from './base/DebtTokenBase.sol'; import {MathUtils} from '../libraries/math/MathUtils.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; /** * @title StableDebtToken * @notice Implements a stable debt token to track the borrowing positions of users * at stable rate mode * @author Aave **/ contract StableDebtToken is IStableDebtToken, DebtTokenBase { using WadRayMath for uint256; uint256 public constant DEBT_TOKEN_REVISION = 0x1; uint256 internal _avgStableRate; mapping(address => uint40) internal _timestamps; mapping(address => uint256) internal _usersStableRate; uint40 internal _totalSupplyTimestamp; ILendingPool internal _pool; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) public override initializer { _setName(debtTokenName); _setSymbol(debtTokenSymbol); _setDecimals(debtTokenDecimals); _pool = pool; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), address(incentivesController), debtTokenDecimals, debtTokenName, debtTokenSymbol, params ); } /** * @dev Gets the revision of the stable debt token implementation * @return The debt token implementation revision **/ function getRevision() internal pure virtual override returns (uint256) { return DEBT_TOKEN_REVISION; } /** * @dev Returns the average stable rate across all the stable rate debt * @return the average stable rate **/ function getAverageStableRate() external view virtual override returns (uint256) { return _avgStableRate; } /** * @dev Returns the timestamp of the last user action * @return The last update timestamp **/ function getUserLastUpdated(address user) external view virtual override returns (uint40) { return _timestamps[user]; } /** * @dev Returns the stable rate of the user * @param user The address of the user * @return The stable rate of user **/ function getUserStableRate(address user) external view virtual override returns (uint256) { return _usersStableRate[user]; } /** * @dev Calculates the current user debt balance * @return The accumulated debt of the user **/ function balanceOf(address account) public view virtual override returns (uint256) { uint256 accountBalance = super.balanceOf(account); uint256 stableRate = _usersStableRate[account]; if (accountBalance == 0) { return 0; } uint256 cumulatedInterest = MathUtils.calculateCompoundedInterest(stableRate, _timestamps[account]); return accountBalance.rayMul(cumulatedInterest); } struct MintLocalVars { uint256 previousSupply; uint256 nextSupply; uint256 amountInRay; uint256 newStableRate; uint256 currentAvgStableRate; } /** * @dev Mints debt token to the `onBehalfOf` address. * - Only callable by the LendingPool * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt tokens to mint * @param rate The rate of the debt being minted **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 rate ) external override onlyLendingPool returns (bool) { MintLocalVars memory vars; if (user != onBehalfOf) { _decreaseBorrowAllowance(onBehalfOf, user, amount); } (, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(onBehalfOf); vars.previousSupply = totalSupply(); vars.currentAvgStableRate = _avgStableRate; vars.nextSupply = _totalSupply = vars.previousSupply.add(amount); vars.amountInRay = amount.wadToRay(); vars.newStableRate = _usersStableRate[onBehalfOf] .rayMul(currentBalance.wadToRay()) .add(vars.amountInRay.rayMul(rate)) .rayDiv(currentBalance.add(amount).wadToRay()); require(vars.newStableRate <= type(uint128).max, Errors.SDT_STABLE_DEBT_OVERFLOW); _usersStableRate[onBehalfOf] = vars.newStableRate; //solium-disable-next-line _totalSupplyTimestamp = _timestamps[onBehalfOf] = uint40(block.timestamp); // Calculates the updated average stable rate vars.currentAvgStableRate = _avgStableRate = vars .currentAvgStableRate .rayMul(vars.previousSupply.wadToRay()) .add(rate.rayMul(vars.amountInRay)) .rayDiv(vars.nextSupply.wadToRay()); _mint(onBehalfOf, amount.add(balanceIncrease), vars.previousSupply); emit Transfer(address(0), onBehalfOf, amount); emit Mint( user, onBehalfOf, amount, currentBalance, balanceIncrease, vars.newStableRate, vars.currentAvgStableRate, vars.nextSupply ); return currentBalance == 0; } /** * @dev Burns debt of `user` * @param user The address of the user getting his debt burned * @param amount The amount of debt tokens getting burned **/ function burn(address user, uint256 amount) external override onlyLendingPool { (, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(user); uint256 previousSupply = totalSupply(); uint256 newAvgStableRate = 0; uint256 nextSupply = 0; uint256 userStableRate = _usersStableRate[user]; // Since the total supply and each single user debt accrue separately, // there might be accumulation errors so that the last borrower repaying // mght actually try to repay more than the available debt supply. // In this case we simply set the total supply and the avg stable rate to 0 if (previousSupply <= amount) { _avgStableRate = 0; _totalSupply = 0; } else { nextSupply = _totalSupply = previousSupply.sub(amount); uint256 firstTerm = _avgStableRate.rayMul(previousSupply.wadToRay()); uint256 secondTerm = userStableRate.rayMul(amount.wadToRay()); // For the same reason described above, when the last user is repaying it might // happen that user rate * user balance > avg rate * total supply. In that case, // we simply set the avg rate to 0 if (secondTerm >= firstTerm) { newAvgStableRate = _avgStableRate = _totalSupply = 0; } else { newAvgStableRate = _avgStableRate = firstTerm.sub(secondTerm).rayDiv(nextSupply.wadToRay()); } } if (amount == currentBalance) { _usersStableRate[user] = 0; _timestamps[user] = 0; } else { //solium-disable-next-line _timestamps[user] = uint40(block.timestamp); } //solium-disable-next-line _totalSupplyTimestamp = uint40(block.timestamp); if (balanceIncrease > amount) { uint256 amountToMint = balanceIncrease.sub(amount); _mint(user, amountToMint, previousSupply); emit Mint( user, user, amountToMint, currentBalance, balanceIncrease, userStableRate, newAvgStableRate, nextSupply ); } else { uint256 amountToBurn = amount.sub(balanceIncrease); _burn(user, amountToBurn, previousSupply); emit Burn(user, amountToBurn, currentBalance, balanceIncrease, newAvgStableRate, nextSupply); } emit Transfer(user, address(0), amount); } /** * @dev Calculates the increase in balance since the last user interaction * @param user The address of the user for which the interest is being accumulated * @return The previous principal balance, the new principal balance and the balance increase **/ function _calculateBalanceIncrease(address user) internal view returns ( uint256, uint256, uint256 ) { uint256 previousPrincipalBalance = super.balanceOf(user); if (previousPrincipalBalance == 0) { return (0, 0, 0); } // Calculation of the accrued interest since the last accumulation uint256 balanceIncrease = balanceOf(user).sub(previousPrincipalBalance); return ( previousPrincipalBalance, previousPrincipalBalance.add(balanceIncrease), balanceIncrease ); } /** * @dev Returns the principal and total supply, the average borrow rate and the last supply update timestamp **/ function getSupplyData() public view override returns ( uint256, uint256, uint256, uint40 ) { uint256 avgRate = _avgStableRate; return (super.totalSupply(), _calcTotalSupply(avgRate), avgRate, _totalSupplyTimestamp); } /** * @dev Returns the the total supply and the average stable rate **/ function getTotalSupplyAndAvgRate() public view override returns (uint256, uint256) { uint256 avgRate = _avgStableRate; return (_calcTotalSupply(avgRate), avgRate); } /** * @dev Returns the total supply **/ function totalSupply() public view override returns (uint256) { return _calcTotalSupply(_avgStableRate); } /** * @dev Returns the timestamp at which the total supply was updated **/ function getTotalSupplyLastUpdated() public view override returns (uint40) { return _totalSupplyTimestamp; } /** * @dev Returns the principal debt balance of the user from * @param user The user's address * @return The debt balance of the user since the last burn/mint action **/ function principalBalanceOf(address user) external view virtual override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev For internal usage in the logic of the parent contracts **/ function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } /** * @dev For internal usage in the logic of the parent contracts **/ function _getUnderlyingAssetAddress() internal view override returns (address) { return _underlyingAsset; } /** * @dev For internal usage in the logic of the parent contracts **/ function _getLendingPool() internal view override returns (ILendingPool) { return _pool; } /** * @dev Calculates the total supply * @param avgRate The average rate at which the total supply increases * @return The debt balance of the user since the last burn/mint action **/ function _calcTotalSupply(uint256 avgRate) internal view virtual returns (uint256) { uint256 principalSupply = super.totalSupply(); if (principalSupply == 0) { return 0; } uint256 cumulatedInterest = MathUtils.calculateCompoundedInterest(avgRate, _totalSupplyTimestamp); return principalSupply.rayMul(cumulatedInterest); } /** * @dev Mints stable debt tokens to an user * @param account The account receiving the debt tokens * @param amount The amount being minted * @param oldTotalSupply the total supply before the minting event **/ function _mint( address account, uint256 amount, uint256 oldTotalSupply ) internal { uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.add(amount); if (address(_incentivesController) != address(0)) { _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); } } /** * @dev Burns stable debt tokens of an user * @param account The user getting his debt burned * @param amount The amount being burned * @param oldTotalSupply The total supply before the burning event **/ function _burn( address account, uint256 amount, uint256 oldTotalSupply ) internal { uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.sub(amount, Errors.SDT_BURN_EXCEEDS_BALANCE); if (address(_incentivesController) != address(0)) { _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {StableDebtToken} from '../../protocol/tokenization/StableDebtToken.sol'; contract MockStableDebtToken is StableDebtToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Address} from '../../dependencies/openzeppelin/contracts/Address.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {IFlashLoanReceiver} from '../../flashloan/interfaces/IFlashLoanReceiver.sol'; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {Helpers} from '../libraries/helpers/Helpers.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol'; import {GenericLogic} from '../libraries/logic/GenericLogic.sol'; import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {LendingPoolStorage} from './LendingPoolStorage.sol'; /** * @title LendingPool contract * @dev Main point of interaction with an Aave protocol's market * - Users can: * # Deposit * # Withdraw * # Borrow * # Repay * # Swap their loans between variable and stable rate * # Enable/disable their deposits as collateral rebalance stable rate borrow positions * # Liquidate positions * # Execute Flash Loans * - To be covered by a proxy contract, owned by the LendingPoolAddressesProvider of the specific market * - All admin functions are callable by the LendingPoolConfigurator contract defined also in the * LendingPoolAddressesProvider * @author Aave **/ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage { using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; uint256 public constant LENDINGPOOL_REVISION = 0x2; modifier whenNotPaused() { _whenNotPaused(); _; } modifier onlyLendingPoolConfigurator() { _onlyLendingPoolConfigurator(); _; } function _whenNotPaused() internal view { require(!_paused, Errors.LP_IS_PAUSED); } function _onlyLendingPoolConfigurator() internal view { require( _addressesProvider.getLendingPoolConfigurator() == msg.sender, Errors.LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR ); } function getRevision() internal pure override returns (uint256) { return LENDINGPOOL_REVISION; } /** * @dev Function is invoked by the proxy contract when the LendingPool contract is added to the * LendingPoolAddressesProvider of the market. * - Caching the address of the LendingPoolAddressesProvider in order to reduce gas consumption * on subsequent operations * @param provider The address of the LendingPoolAddressesProvider **/ function initialize(ILendingPoolAddressesProvider provider) public initializer { _addressesProvider = provider; _maxStableRateBorrowSizePercent = 2500; _flashLoanPremiumTotal = 9; _maxNumberOfReserves = 128; } /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateDeposit(reserve, amount); address aToken = reserve.aTokenAddress; reserve.updateState(); reserve.updateInterestRates(asset, aToken, amount, 0); IERC20(asset).safeTransferFrom(msg.sender, aToken, amount); bool isFirstDeposit = IAToken(aToken).mint(onBehalfOf, amount, reserve.liquidityIndex); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit(asset, msg.sender, onBehalfOf, amount, referralCode); } /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; address aToken = reserve.aTokenAddress; uint256 userBalance = IAToken(aToken).balanceOf(msg.sender); uint256 amountToWithdraw = amount; if (amount == type(uint256).max) { amountToWithdraw = userBalance; } ValidationLogic.validateWithdraw( asset, amountToWithdraw, userBalance, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); reserve.updateState(); reserve.updateInterestRates(asset, aToken, 0, amountToWithdraw); if (amountToWithdraw == userBalance) { _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false); emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } IAToken(aToken).burn(msg.sender, to, amountToWithdraw, reserve.liquidityIndex); emit Withdraw(asset, msg.sender, to, amountToWithdraw); return amountToWithdraw; } /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; _executeBorrow( ExecuteBorrowParams( asset, msg.sender, onBehalfOf, amount, interestRateMode, reserve.aTokenAddress, referralCode, true ) ); } /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve); DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode); ValidationLogic.validateRepay( reserve, amount, interestRateMode, onBehalfOf, stableDebt, variableDebt ); uint256 paybackAmount = interestRateMode == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } reserve.updateState(); if (interestRateMode == DataTypes.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount); } else { IVariableDebtToken(reserve.variableDebtTokenAddress).burn( onBehalfOf, paybackAmount, reserve.variableBorrowIndex ); } address aToken = reserve.aTokenAddress; reserve.updateInterestRates(asset, aToken, paybackAmount, 0); if (stableDebt.add(variableDebt).sub(paybackAmount) == 0) { _usersConfig[onBehalfOf].setBorrowing(reserve.id, false); } IERC20(asset).safeTransferFrom(msg.sender, aToken, paybackAmount); IAToken(aToken).handleRepayment(msg.sender, paybackAmount); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); return paybackAmount; } /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(msg.sender, reserve); DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode); ValidationLogic.validateSwapRateMode( reserve, _usersConfig[msg.sender], stableDebt, variableDebt, interestRateMode ); reserve.updateState(); if (interestRateMode == DataTypes.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt); IVariableDebtToken(reserve.variableDebtTokenAddress).mint( msg.sender, msg.sender, stableDebt, reserve.variableBorrowIndex ); } else { IVariableDebtToken(reserve.variableDebtTokenAddress).burn( msg.sender, variableDebt, reserve.variableBorrowIndex ); IStableDebtToken(reserve.stableDebtTokenAddress).mint( msg.sender, msg.sender, variableDebt, reserve.currentStableBorrowRate ); } reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0); emit Swap(asset, msg.sender, rateMode); } /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; IERC20 stableDebtToken = IERC20(reserve.stableDebtTokenAddress); IERC20 variableDebtToken = IERC20(reserve.variableDebtTokenAddress); address aTokenAddress = reserve.aTokenAddress; uint256 stableDebt = IERC20(stableDebtToken).balanceOf(user); ValidationLogic.validateRebalanceStableBorrowRate( reserve, asset, stableDebtToken, variableDebtToken, aTokenAddress ); reserve.updateState(); IStableDebtToken(address(stableDebtToken)).burn(user, stableDebt); IStableDebtToken(address(stableDebtToken)).mint( user, user, stableDebt, reserve.currentStableBorrowRate ); reserve.updateInterestRates(asset, aTokenAddress, 0, 0); emit RebalanceStableBorrowRate(asset, user); } /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateSetUseReserveAsCollateral( reserve, asset, useAsCollateral, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, useAsCollateral); if (useAsCollateral) { emit ReserveUsedAsCollateralEnabled(asset, msg.sender); } else { emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } } /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external override whenNotPaused { address collateralManager = _addressesProvider.getLendingPoolCollateralManager(); //solium-disable-next-line (bool success, bytes memory result) = collateralManager.delegatecall( abi.encodeWithSignature( 'liquidationCall(address,address,address,uint256,bool)', collateralAsset, debtAsset, user, debtToCover, receiveAToken ) ); require(success, Errors.LP_LIQUIDATION_CALL_FAILED); (uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string)); require(returnCode == 0, string(abi.encodePacked(returnMessage))); } struct FlashLoanLocalVars { IFlashLoanReceiver receiver; address oracle; uint256 i; address currentAsset; address currentATokenAddress; uint256 currentAmount; uint256 currentPremium; uint256 currentAmountPlusPremium; address debtToken; } /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external override whenNotPaused { FlashLoanLocalVars memory vars; ValidationLogic.validateFlashloan(assets, amounts); address[] memory aTokenAddresses = new address[](assets.length); uint256[] memory premiums = new uint256[](assets.length); vars.receiver = IFlashLoanReceiver(receiverAddress); for (vars.i = 0; vars.i < assets.length; vars.i++) { aTokenAddresses[vars.i] = _reserves[assets[vars.i]].aTokenAddress; premiums[vars.i] = amounts[vars.i].mul(_flashLoanPremiumTotal).div(10000); IAToken(aTokenAddresses[vars.i]).transferUnderlyingTo(receiverAddress, amounts[vars.i]); } require( vars.receiver.executeOperation(assets, amounts, premiums, msg.sender, params), Errors.LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN ); for (vars.i = 0; vars.i < assets.length; vars.i++) { vars.currentAsset = assets[vars.i]; vars.currentAmount = amounts[vars.i]; vars.currentPremium = premiums[vars.i]; vars.currentATokenAddress = aTokenAddresses[vars.i]; vars.currentAmountPlusPremium = vars.currentAmount.add(vars.currentPremium); if (DataTypes.InterestRateMode(modes[vars.i]) == DataTypes.InterestRateMode.NONE) { _reserves[vars.currentAsset].updateState(); _reserves[vars.currentAsset].cumulateToLiquidityIndex( IERC20(vars.currentATokenAddress).totalSupply(), vars.currentPremium ); _reserves[vars.currentAsset].updateInterestRates( vars.currentAsset, vars.currentATokenAddress, vars.currentAmountPlusPremium, 0 ); IERC20(vars.currentAsset).safeTransferFrom( receiverAddress, vars.currentATokenAddress, vars.currentAmountPlusPremium ); } else { // If the user chose to not return the funds, the system checks if there is enough collateral and // eventually opens a debt position _executeBorrow( ExecuteBorrowParams( vars.currentAsset, msg.sender, onBehalfOf, vars.currentAmount, modes[vars.i], vars.currentATokenAddress, referralCode, false ) ); } emit FlashLoan( receiverAddress, msg.sender, vars.currentAsset, vars.currentAmount, vars.currentPremium, referralCode ); } } /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view override returns (DataTypes.ReserveData memory) { return _reserves[asset]; } /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view override returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) { ( totalCollateralETH, totalDebtETH, ltv, currentLiquidationThreshold, healthFactor ) = GenericLogic.calculateUserAccountData( user, _reserves, _usersConfig[user], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH( totalCollateralETH, totalDebtETH, ltv ); } /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view override returns (DataTypes.ReserveConfigurationMap memory) { return _reserves[asset].configuration; } /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view override returns (DataTypes.UserConfigurationMap memory) { return _usersConfig[user]; } /** * @dev Returns the normalized income per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view virtual override returns (uint256) { return _reserves[asset].getNormalizedIncome(); } /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view override returns (uint256) { return _reserves[asset].getNormalizedDebt(); } /** * @dev Returns if the LendingPool is paused */ function paused() external view override returns (bool) { return _paused; } /** * @dev Returns the list of the initialized reserves **/ function getReservesList() external view override returns (address[] memory) { address[] memory _activeReserves = new address[](_reservesCount); for (uint256 i = 0; i < _reservesCount; i++) { _activeReserves[i] = _reservesList[i]; } return _activeReserves; } /** * @dev Returns the cached LendingPoolAddressesProvider connected to this contract **/ function getAddressesProvider() external view override returns (ILendingPoolAddressesProvider) { return _addressesProvider; } /** * @dev Returns the percentage of available liquidity that can be borrowed at once at stable rate */ function MAX_STABLE_RATE_BORROW_SIZE_PERCENT() public view returns (uint256) { return _maxStableRateBorrowSizePercent; } /** * @dev Returns the fee on flash loans */ function FLASHLOAN_PREMIUM_TOTAL() public view returns (uint256) { return _flashLoanPremiumTotal; } /** * @dev Returns the maximum number of reserves supported to be listed in this LendingPool */ function MAX_NUMBER_RESERVES() public view returns (uint256) { return _maxNumberOfReserves; } /** * @dev Validates and finalizes an aToken transfer * - Only callable by the overlying aToken of the `asset` * @param asset The address of the underlying asset of the aToken * @param from The user from which the aTokens are transferred * @param to The user receiving the aTokens * @param amount The amount being transferred/withdrawn * @param balanceFromBefore The aToken balance of the `from` user before the transfer * @param balanceToBefore The aToken balance of the `to` user before the transfer */ function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromBefore, uint256 balanceToBefore ) external override whenNotPaused { require(msg.sender == _reserves[asset].aTokenAddress, Errors.LP_CALLER_MUST_BE_AN_ATOKEN); ValidationLogic.validateTransfer( from, _reserves, _usersConfig[from], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); uint256 reserveId = _reserves[asset].id; if (from != to) { if (balanceFromBefore.sub(amount) == 0) { DataTypes.UserConfigurationMap storage fromConfig = _usersConfig[from]; fromConfig.setUsingAsCollateral(reserveId, false); emit ReserveUsedAsCollateralDisabled(asset, from); } if (balanceToBefore == 0 && amount != 0) { DataTypes.UserConfigurationMap storage toConfig = _usersConfig[to]; toConfig.setUsingAsCollateral(reserveId, true); emit ReserveUsedAsCollateralEnabled(asset, to); } } } /** * @dev Initializes a reserve, activating it, assigning an aToken and debt tokens and an * interest rate strategy * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param aTokenAddress The address of the aToken that will be assigned to the reserve * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve * @param aTokenAddress The address of the VariableDebtToken that will be assigned to the reserve * @param interestRateStrategyAddress The address of the interest rate strategy contract **/ function initReserve( address asset, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external override onlyLendingPoolConfigurator { require(Address.isContract(asset), Errors.LP_NOT_CONTRACT); _reserves[asset].init( aTokenAddress, stableDebtAddress, variableDebtAddress, interestRateStrategyAddress ); _addReserveToList(asset); } /** * @dev Updates the address of the interest rate strategy contract * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param rateStrategyAddress The address of the interest rate strategy contract **/ function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) external override onlyLendingPoolConfigurator { _reserves[asset].interestRateStrategyAddress = rateStrategyAddress; } /** * @dev Sets the configuration bitmap of the reserve as a whole * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param configuration The new configuration bitmap **/ function setConfiguration(address asset, uint256 configuration) external override onlyLendingPoolConfigurator { _reserves[asset].configuration.data = configuration; } /** * @dev Set the _pause state of a reserve * - Only callable by the LendingPoolConfigurator contract * @param val `true` to pause the reserve, `false` to un-pause it */ function setPause(bool val) external override onlyLendingPoolConfigurator { _paused = val; if (_paused) { emit Paused(); } else { emit Unpaused(); } } struct ExecuteBorrowParams { address asset; address user; address onBehalfOf; uint256 amount; uint256 interestRateMode; address aTokenAddress; uint16 referralCode; bool releaseUnderlying; } function _executeBorrow(ExecuteBorrowParams memory vars) internal { DataTypes.ReserveData storage reserve = _reserves[vars.asset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[vars.onBehalfOf]; address oracle = _addressesProvider.getPriceOracle(); uint256 amountInETH = IPriceOracleGetter(oracle).getAssetPrice(vars.asset).mul(vars.amount).div( 10**reserve.configuration.getDecimals() ); ValidationLogic.validateBorrow( vars.asset, reserve, vars.onBehalfOf, vars.amount, amountInETH, vars.interestRateMode, _maxStableRateBorrowSizePercent, _reserves, userConfig, _reservesList, _reservesCount, oracle ); reserve.updateState(); uint256 currentStableRate = 0; bool isFirstBorrowing = false; if (DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE) { currentStableRate = reserve.currentStableBorrowRate; isFirstBorrowing = IStableDebtToken(reserve.stableDebtTokenAddress).mint( vars.user, vars.onBehalfOf, vars.amount, currentStableRate ); } else { isFirstBorrowing = IVariableDebtToken(reserve.variableDebtTokenAddress).mint( vars.user, vars.onBehalfOf, vars.amount, reserve.variableBorrowIndex ); } if (isFirstBorrowing) { userConfig.setBorrowing(reserve.id, true); } reserve.updateInterestRates( vars.asset, vars.aTokenAddress, 0, vars.releaseUnderlying ? vars.amount : 0 ); if (vars.releaseUnderlying) { IAToken(vars.aTokenAddress).transferUnderlyingTo(vars.user, vars.amount); } emit Borrow( vars.asset, vars.user, vars.onBehalfOf, vars.amount, vars.interestRateMode, DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE ? currentStableRate : reserve.currentVariableBorrowRate, vars.referralCode ); } function _addReserveToList(address asset) internal { uint256 reservesCount = _reservesCount; require(reservesCount < _maxNumberOfReserves, Errors.LP_NO_MORE_RESERVES_ALLOWED); bool reserveAlreadyAdded = _reserves[asset].id != 0 || _reservesList[0] == asset; if (!reserveAlreadyAdded) { _reserves[asset].id = uint8(reservesCount); _reservesList[reservesCount] = asset; _reservesCount = reservesCount + 1; } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; interface IExchangeAdapter { event Exchange( address indexed from, address indexed to, address indexed platform, uint256 fromAmount, uint256 toAmount ); function approveExchange(IERC20[] calldata tokens) external; function exchange( address from, address to, uint256 amount, uint256 maxSlippage ) external returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ERC20} from '../../dependencies/openzeppelin/contracts/ERC20.sol'; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract MintableDelegationERC20 is ERC20 { address public delegatee; constructor( string memory name, string memory symbol, uint8 decimals ) public ERC20(name, symbol) { _setupDecimals(decimals); } /** * @dev Function to mint tokensp * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(uint256 value) public returns (bool) { _mint(msg.sender, value); return true; } function delegate(address delegateeAddress) external { delegatee = delegateeAddress; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IUniswapV2Router02} from '../../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {MintableERC20} from '../tokens/MintableERC20.sol'; contract MockUniswapV2Router02 is IUniswapV2Router02 { mapping(address => uint256) internal _amountToReturn; mapping(address => uint256) internal _amountToSwap; mapping(address => mapping(address => mapping(uint256 => uint256))) internal _amountsIn; mapping(address => mapping(address => mapping(uint256 => uint256))) internal _amountsOut; uint256 internal defaultMockValue; function setAmountToReturn(address reserve, uint256 amount) public { _amountToReturn[reserve] = amount; } function setAmountToSwap(address reserve, uint256 amount) public { _amountToSwap[reserve] = amount; } function swapExactTokensForTokens( uint256 amountIn, uint256, /* amountOutMin */ address[] calldata path, address to, uint256 /* deadline */ ) external override returns (uint256[] memory amounts) { IERC20(path[0]).transferFrom(msg.sender, address(this), amountIn); MintableERC20(path[1]).mint(_amountToReturn[path[0]]); IERC20(path[1]).transfer(to, _amountToReturn[path[0]]); amounts = new uint256[](path.length); amounts[0] = amountIn; amounts[1] = _amountToReturn[path[0]]; } function swapTokensForExactTokens( uint256 amountOut, uint256, /* amountInMax */ address[] calldata path, address to, uint256 /* deadline */ ) external override returns (uint256[] memory amounts) { IERC20(path[0]).transferFrom(msg.sender, address(this), _amountToSwap[path[0]]); MintableERC20(path[1]).mint(amountOut); IERC20(path[1]).transfer(to, amountOut); amounts = new uint256[](path.length); amounts[0] = _amountToSwap[path[0]]; amounts[1] = amountOut; } function setAmountOut( uint256 amountIn, address reserveIn, address reserveOut, uint256 amountOut ) public { _amountsOut[reserveIn][reserveOut][amountIn] = amountOut; } function setAmountIn( uint256 amountOut, address reserveIn, address reserveOut, uint256 amountIn ) public { _amountsIn[reserveIn][reserveOut][amountOut] = amountIn; } function setDefaultMockValue(uint256 value) public { defaultMockValue = value; } function getAmountsOut(uint256 amountIn, address[] calldata path) external view override returns (uint256[] memory) { uint256[] memory amounts = new uint256[](path.length); amounts[0] = amountIn; amounts[1] = _amountsOut[path[0]][path[1]][amountIn] > 0 ? _amountsOut[path[0]][path[1]][amountIn] : defaultMockValue; return amounts; } function getAmountsIn(uint256 amountOut, address[] calldata path) external view override returns (uint256[] memory) { uint256[] memory amounts = new uint256[](path.length); amounts[0] = _amountsIn[path[0]][path[1]][amountOut] > 0 ? _amountsIn[path[0]][path[1]][amountOut] : defaultMockValue; amounts[1] = amountOut; return amounts; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; /** * @title UniswapLiquiditySwapAdapter * @notice Uniswap V2 Adapter to swap liquidity. * @author Aave **/ contract UniswapLiquiditySwapAdapter is BaseUniswapAdapter { struct PermitParams { uint256[] amount; uint256[] deadline; uint8[] v; bytes32[] r; bytes32[] s; } struct SwapParams { address[] assetToSwapToList; uint256[] minAmountsToReceive; bool[] swapAllBalance; PermitParams permitParams; bool[] useEthPath; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Swaps the received reserve amount from the flash loan into the asset specified in the params. * The received funds from the swap are then deposited into the protocol on behalf of the user. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and * repay the flash loan. * @param assets Address of asset to be swapped * @param amounts Amount of the asset to be swapped * @param premiums Fee of the flash loan * @param initiator Address of the user * @param params Additional variadic field to include extra params. Expected parameters: * address[] assetToSwapToList List of the addresses of the reserve to be swapped to and deposited * uint256[] minAmountsToReceive List of min amounts to be received from the swap * bool[] swapAllBalance Flag indicating if all the user balance should be swapped * uint256[] permitAmount List of amounts for the permit signature * uint256[] deadline List of deadlines for the permit signature * uint8[] v List of v param for the permit signature * bytes32[] r List of r param for the permit signature * bytes32[] s List of s param for the permit signature */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); SwapParams memory decodedParams = _decodeParams(params); require( assets.length == decodedParams.assetToSwapToList.length && assets.length == decodedParams.minAmountsToReceive.length && assets.length == decodedParams.swapAllBalance.length && assets.length == decodedParams.permitParams.amount.length && assets.length == decodedParams.permitParams.deadline.length && assets.length == decodedParams.permitParams.v.length && assets.length == decodedParams.permitParams.r.length && assets.length == decodedParams.permitParams.s.length && assets.length == decodedParams.useEthPath.length, 'INCONSISTENT_PARAMS' ); for (uint256 i = 0; i < assets.length; i++) { _swapLiquidity( assets[i], decodedParams.assetToSwapToList[i], amounts[i], premiums[i], initiator, decodedParams.minAmountsToReceive[i], decodedParams.swapAllBalance[i], PermitSignature( decodedParams.permitParams.amount[i], decodedParams.permitParams.deadline[i], decodedParams.permitParams.v[i], decodedParams.permitParams.r[i], decodedParams.permitParams.s[i] ), decodedParams.useEthPath[i] ); } return true; } struct SwapAndDepositLocalVars { uint256 i; uint256 aTokenInitiatorBalance; uint256 amountToSwap; uint256 receivedAmount; address aToken; } /** * @dev Swaps an amount of an asset to another and deposits the new asset amount on behalf of the user without using * a flash loan. This method can be used when the temporary transfer of the collateral asset to this contract * does not affect the user position. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and * perform the swap. * @param assetToSwapFromList List of addresses of the underlying asset to be swap from * @param assetToSwapToList List of addresses of the underlying asset to be swap to and deposited * @param amountToSwapList List of amounts to be swapped. If the amount exceeds the balance, the total balance is used for the swap * @param minAmountsToReceive List of min amounts to be received from the swap * @param permitParams List of struct containing the permit signatures * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v param for the permit signature * bytes32 r param for the permit signature * bytes32 s param for the permit signature * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise */ function swapAndDeposit( address[] calldata assetToSwapFromList, address[] calldata assetToSwapToList, uint256[] calldata amountToSwapList, uint256[] calldata minAmountsToReceive, PermitSignature[] calldata permitParams, bool[] calldata useEthPath ) external { require( assetToSwapFromList.length == assetToSwapToList.length && assetToSwapFromList.length == amountToSwapList.length && assetToSwapFromList.length == minAmountsToReceive.length && assetToSwapFromList.length == permitParams.length, 'INCONSISTENT_PARAMS' ); SwapAndDepositLocalVars memory vars; for (vars.i = 0; vars.i < assetToSwapFromList.length; vars.i++) { vars.aToken = _getReserveData(assetToSwapFromList[vars.i]).aTokenAddress; vars.aTokenInitiatorBalance = IERC20(vars.aToken).balanceOf(msg.sender); vars.amountToSwap = amountToSwapList[vars.i] > vars.aTokenInitiatorBalance ? vars.aTokenInitiatorBalance : amountToSwapList[vars.i]; _pullAToken( assetToSwapFromList[vars.i], vars.aToken, msg.sender, vars.amountToSwap, permitParams[vars.i] ); vars.receivedAmount = _swapExactTokensForTokens( assetToSwapFromList[vars.i], assetToSwapToList[vars.i], vars.amountToSwap, minAmountsToReceive[vars.i], useEthPath[vars.i] ); // Deposit new reserve IERC20(assetToSwapToList[vars.i]).safeApprove(address(LENDING_POOL), 0); IERC20(assetToSwapToList[vars.i]).safeApprove(address(LENDING_POOL), vars.receivedAmount); LENDING_POOL.deposit(assetToSwapToList[vars.i], vars.receivedAmount, msg.sender, 0); } } /** * @dev Swaps an `amountToSwap` of an asset to another and deposits the funds on behalf of the initiator. * @param assetFrom Address of the underlying asset to be swap from * @param assetTo Address of the underlying asset to be swap to and deposited * @param amount Amount from flash loan * @param premium Premium of the flash loan * @param minAmountToReceive Min amount to be received from the swap * @param swapAllBalance Flag indicating if all the user balance should be swapped * @param permitSignature List of struct containing the permit signature * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise */ struct SwapLiquidityLocalVars { address aToken; uint256 aTokenInitiatorBalance; uint256 amountToSwap; uint256 receivedAmount; uint256 flashLoanDebt; uint256 amountToPull; } function _swapLiquidity( address assetFrom, address assetTo, uint256 amount, uint256 premium, address initiator, uint256 minAmountToReceive, bool swapAllBalance, PermitSignature memory permitSignature, bool useEthPath ) internal { SwapLiquidityLocalVars memory vars; vars.aToken = _getReserveData(assetFrom).aTokenAddress; vars.aTokenInitiatorBalance = IERC20(vars.aToken).balanceOf(initiator); vars.amountToSwap = swapAllBalance && vars.aTokenInitiatorBalance.sub(premium) <= amount ? vars.aTokenInitiatorBalance.sub(premium) : amount; vars.receivedAmount = _swapExactTokensForTokens( assetFrom, assetTo, vars.amountToSwap, minAmountToReceive, useEthPath ); // Deposit new reserve IERC20(assetTo).safeApprove(address(LENDING_POOL), 0); IERC20(assetTo).safeApprove(address(LENDING_POOL), vars.receivedAmount); LENDING_POOL.deposit(assetTo, vars.receivedAmount, initiator, 0); vars.flashLoanDebt = amount.add(premium); vars.amountToPull = vars.amountToSwap.add(premium); _pullAToken(assetFrom, vars.aToken, initiator, vars.amountToPull, permitSignature); // Repay flash loan IERC20(assetFrom).safeApprove(address(LENDING_POOL), 0); IERC20(assetFrom).safeApprove(address(LENDING_POOL), vars.flashLoanDebt); } /** * @dev Decodes the information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address[] assetToSwapToList List of the addresses of the reserve to be swapped to and deposited * uint256[] minAmountsToReceive List of min amounts to be received from the swap * bool[] swapAllBalance Flag indicating if all the user balance should be swapped * uint256[] permitAmount List of amounts for the permit signature * uint256[] deadline List of deadlines for the permit signature * uint8[] v List of v param for the permit signature * bytes32[] r List of r param for the permit signature * bytes32[] s List of s param for the permit signature * bool[] useEthPath true if the swap needs to occur using ETH in the routing, false otherwise * @return SwapParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (SwapParams memory) { ( address[] memory assetToSwapToList, uint256[] memory minAmountsToReceive, bool[] memory swapAllBalance, uint256[] memory permitAmount, uint256[] memory deadline, uint8[] memory v, bytes32[] memory r, bytes32[] memory s, bool[] memory useEthPath ) = abi.decode( params, (address[], uint256[], bool[], uint256[], uint256[], uint8[], bytes32[], bytes32[], bool[]) ); return SwapParams( assetToSwapToList, minAmountsToReceive, swapAllBalance, PermitParams(permitAmount, deadline, v, r, s), useEthPath ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import {Helpers} from '../protocol/libraries/helpers/Helpers.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; /** * @title UniswapLiquiditySwapAdapter * @notice Uniswap V2 Adapter to swap liquidity. * @author Aave **/ contract FlashLiquidationAdapter is BaseUniswapAdapter { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; uint256 internal constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 5000; struct LiquidationParams { address collateralAsset; address borrowedAsset; address user; uint256 debtToCover; bool useEthPath; } struct LiquidationCallLocalVars { uint256 initFlashBorrowedBalance; uint256 diffFlashBorrowedBalance; uint256 initCollateralBalance; uint256 diffCollateralBalance; uint256 flashLoanDebt; uint256 soldAmount; uint256 remainingTokens; uint256 borrowedAssetLeftovers; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Liquidate a non-healthy position collateral-wise, with a Health Factor below 1, using Flash Loan and Uniswap to repay flash loan premium. * - The caller (liquidator) with a flash loan covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk minus the flash loan premium. * @param assets Address of asset to be swapped * @param amounts Amount of the asset to be swapped * @param premiums Fee of the flash loan * @param initiator Address of the caller * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset The collateral asset to release and will be exchanged to pay the flash loan premium * address borrowedAsset The asset that must be covered * address user The user address with a Health Factor below 1 * uint256 debtToCover The amount of debt to cover * bool useEthPath Use WETH as connector path between the collateralAsset and borrowedAsset at Uniswap */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); LiquidationParams memory decodedParams = _decodeParams(params); require(assets.length == 1 && assets[0] == decodedParams.borrowedAsset, 'INCONSISTENT_PARAMS'); _liquidateAndSwap( decodedParams.collateralAsset, decodedParams.borrowedAsset, decodedParams.user, decodedParams.debtToCover, decodedParams.useEthPath, amounts[0], premiums[0], initiator ); return true; } /** * @dev * @param collateralAsset The collateral asset to release and will be exchanged to pay the flash loan premium * @param borrowedAsset The asset that must be covered * @param user The user address with a Health Factor below 1 * @param debtToCover The amount of debt to coverage, can be max(-1) to liquidate all possible debt * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise * @param flashBorrowedAmount Amount of asset requested at the flash loan to liquidate the user position * @param premium Fee of the requested flash loan * @param initiator Address of the caller */ function _liquidateAndSwap( address collateralAsset, address borrowedAsset, address user, uint256 debtToCover, bool useEthPath, uint256 flashBorrowedAmount, uint256 premium, address initiator ) internal { LiquidationCallLocalVars memory vars; vars.initCollateralBalance = IERC20(collateralAsset).balanceOf(address(this)); if (collateralAsset != borrowedAsset) { vars.initFlashBorrowedBalance = IERC20(borrowedAsset).balanceOf(address(this)); // Track leftover balance to rescue funds in case of external transfers into this contract vars.borrowedAssetLeftovers = vars.initFlashBorrowedBalance.sub(flashBorrowedAmount); } vars.flashLoanDebt = flashBorrowedAmount.add(premium); // Approve LendingPool to use debt token for liquidation IERC20(borrowedAsset).approve(address(LENDING_POOL), debtToCover); // Liquidate the user position and release the underlying collateral LENDING_POOL.liquidationCall(collateralAsset, borrowedAsset, user, debtToCover, false); // Discover the liquidated tokens uint256 collateralBalanceAfter = IERC20(collateralAsset).balanceOf(address(this)); // Track only collateral released, not current asset balance of the contract vars.diffCollateralBalance = collateralBalanceAfter.sub(vars.initCollateralBalance); if (collateralAsset != borrowedAsset) { // Discover flash loan balance after the liquidation uint256 flashBorrowedAssetAfter = IERC20(borrowedAsset).balanceOf(address(this)); // Use only flash loan borrowed assets, not current asset balance of the contract vars.diffFlashBorrowedBalance = flashBorrowedAssetAfter.sub(vars.borrowedAssetLeftovers); // Swap released collateral into the debt asset, to repay the flash loan vars.soldAmount = _swapTokensForExactTokens( collateralAsset, borrowedAsset, vars.diffCollateralBalance, vars.flashLoanDebt.sub(vars.diffFlashBorrowedBalance), useEthPath ); vars.remainingTokens = vars.diffCollateralBalance.sub(vars.soldAmount); } else { vars.remainingTokens = vars.diffCollateralBalance.sub(premium); } // Allow repay of flash loan IERC20(borrowedAsset).approve(address(LENDING_POOL), vars.flashLoanDebt); // Transfer remaining tokens to initiator if (vars.remainingTokens > 0) { IERC20(collateralAsset).transfer(initiator, vars.remainingTokens); } } /** * @dev Decodes the information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset The collateral asset to claim * address borrowedAsset The asset that must be covered and will be exchanged to pay the flash loan premium * address user The user address with a Health Factor below 1 * uint256 debtToCover The amount of debt to cover * bool useEthPath Use WETH as connector path between the collateralAsset and borrowedAsset at Uniswap * @return LiquidationParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (LiquidationParams memory) { ( address collateralAsset, address borrowedAsset, address user, uint256 debtToCover, bool useEthPath ) = abi.decode(params, (address, address, address, uint256, bool)); return LiquidationParams(collateralAsset, borrowedAsset, user, debtToCover, useEthPath); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseAdminUpgradeabilityProxy.sol'; import './InitializableUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for * initializing the implementation, admin, and init data. */ contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * Contract initializer. * @param logic address of the initial implementation. * @param admin Address of the proxy administrator. * @param data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize( address logic, address admin, bytes memory data ) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(logic, data); assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(admin); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) { BaseAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './UpgradeabilityProxy.sol'; /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), 'Cannot change the admin of a proxy to the zero address'); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); (bool success, ) = newImplementation.delegatecall(data); require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; //solium-disable-next-line assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; //solium-disable-next-line assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal virtual override { require(msg.sender != _admin(), 'Cannot call fallback function from the proxy admin'); super._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseUpgradeabilityProxy.sol'; /** * @title UpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseAdminUpgradeabilityProxy.sol'; /** * @title AdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for * initializing the implementation, admin, and init data. */ contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor( address _logic, address _admin, bytes memory _data ) public payable UpgradeabilityProxy(_logic, _data) { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) { BaseAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; // Prettier ignore to prevent buidler flatter bug // prettier-ignore import {InitializableImmutableAdminUpgradeabilityProxy} from '../libraries/aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ contract LendingPoolAddressesProvider is Ownable, ILendingPoolAddressesProvider { string private _marketId; mapping(bytes32 => address) private _addresses; bytes32 private constant LENDING_POOL = 'LENDING_POOL'; bytes32 private constant LENDING_POOL_CONFIGURATOR = 'LENDING_POOL_CONFIGURATOR'; bytes32 private constant POOL_ADMIN = 'POOL_ADMIN'; bytes32 private constant EMERGENCY_ADMIN = 'EMERGENCY_ADMIN'; bytes32 private constant LENDING_POOL_COLLATERAL_MANAGER = 'COLLATERAL_MANAGER'; bytes32 private constant PRICE_ORACLE = 'PRICE_ORACLE'; bytes32 private constant LENDING_RATE_ORACLE = 'LENDING_RATE_ORACLE'; constructor(string memory marketId) public { _setMarketId(marketId); } /** * @dev Returns the id of the Aave market to which this contracts points to * @return The market id **/ function getMarketId() external view override returns (string memory) { return _marketId; } /** * @dev Allows to set the market which this LendingPoolAddressesProvider represents * @param marketId The market id */ function setMarketId(string memory marketId) external override onlyOwner { _setMarketId(marketId); } /** * @dev General function to update the implementation of a proxy registered with * certain `id`. If there is no proxy registered, it will instantiate one and * set as implementation the `implementationAddress` * IMPORTANT Use this function carefully, only for ids that don't have an explicit * setter function, in order to avoid unexpected consequences * @param id The id * @param implementationAddress The address of the new implementation */ function setAddressAsProxy(bytes32 id, address implementationAddress) external override onlyOwner { _updateImpl(id, implementationAddress); emit AddressSet(id, implementationAddress, true); } /** * @dev Sets an address for an id replacing the address saved in the addresses map * IMPORTANT Use this function carefully, as it will do a hard replacement * @param id The id * @param newAddress The address to set */ function setAddress(bytes32 id, address newAddress) external override onlyOwner { _addresses[id] = newAddress; emit AddressSet(id, newAddress, false); } /** * @dev Returns an address by id * @return The address */ function getAddress(bytes32 id) public view override returns (address) { return _addresses[id]; } /** * @dev Returns the address of the LendingPool proxy * @return The LendingPool proxy address **/ function getLendingPool() external view override returns (address) { return getAddress(LENDING_POOL); } /** * @dev Updates the implementation of the LendingPool, or creates the proxy * setting the new `pool` implementation on the first time calling it * @param pool The new LendingPool implementation **/ function setLendingPoolImpl(address pool) external override onlyOwner { _updateImpl(LENDING_POOL, pool); emit LendingPoolUpdated(pool); } /** * @dev Returns the address of the LendingPoolConfigurator proxy * @return The LendingPoolConfigurator proxy address **/ function getLendingPoolConfigurator() external view override returns (address) { return getAddress(LENDING_POOL_CONFIGURATOR); } /** * @dev Updates the implementation of the LendingPoolConfigurator, or creates the proxy * setting the new `configurator` implementation on the first time calling it * @param configurator The new LendingPoolConfigurator implementation **/ function setLendingPoolConfiguratorImpl(address configurator) external override onlyOwner { _updateImpl(LENDING_POOL_CONFIGURATOR, configurator); emit LendingPoolConfiguratorUpdated(configurator); } /** * @dev Returns the address of the LendingPoolCollateralManager. Since the manager is used * through delegateCall within the LendingPool contract, the proxy contract pattern does not work properly hence * the addresses are changed directly * @return The address of the LendingPoolCollateralManager **/ function getLendingPoolCollateralManager() external view override returns (address) { return getAddress(LENDING_POOL_COLLATERAL_MANAGER); } /** * @dev Updates the address of the LendingPoolCollateralManager * @param manager The new LendingPoolCollateralManager address **/ function setLendingPoolCollateralManager(address manager) external override onlyOwner { _addresses[LENDING_POOL_COLLATERAL_MANAGER] = manager; emit LendingPoolCollateralManagerUpdated(manager); } /** * @dev The functions below are getters/setters of addresses that are outside the context * of the protocol hence the upgradable proxy pattern is not used **/ function getPoolAdmin() external view override returns (address) { return getAddress(POOL_ADMIN); } function setPoolAdmin(address admin) external override onlyOwner { _addresses[POOL_ADMIN] = admin; emit ConfigurationAdminUpdated(admin); } function getEmergencyAdmin() external view override returns (address) { return getAddress(EMERGENCY_ADMIN); } function setEmergencyAdmin(address emergencyAdmin) external override onlyOwner { _addresses[EMERGENCY_ADMIN] = emergencyAdmin; emit EmergencyAdminUpdated(emergencyAdmin); } function getPriceOracle() external view override returns (address) { return getAddress(PRICE_ORACLE); } function setPriceOracle(address priceOracle) external override onlyOwner { _addresses[PRICE_ORACLE] = priceOracle; emit PriceOracleUpdated(priceOracle); } function getLendingRateOracle() external view override returns (address) { return getAddress(LENDING_RATE_ORACLE); } function setLendingRateOracle(address lendingRateOracle) external override onlyOwner { _addresses[LENDING_RATE_ORACLE] = lendingRateOracle; emit LendingRateOracleUpdated(lendingRateOracle); } /** * @dev Internal function to update the implementation of a specific proxied component of the protocol * - If there is no proxy registered in the given `id`, it creates the proxy setting `newAdress` * as implementation and calls the initialize() function on the proxy * - If there is already a proxy registered, it just updates the implementation to `newAddress` and * calls the initialize() function via upgradeToAndCall() in the proxy * @param id The id of the proxy to be updated * @param newAddress The address of the new implementation **/ function _updateImpl(bytes32 id, address newAddress) internal { address payable proxyAddress = payable(_addresses[id]); InitializableImmutableAdminUpgradeabilityProxy proxy = InitializableImmutableAdminUpgradeabilityProxy(proxyAddress); bytes memory params = abi.encodeWithSignature('initialize(address)', address(this)); if (proxyAddress == address(0)) { proxy = new InitializableImmutableAdminUpgradeabilityProxy(address(this)); proxy.initialize(newAddress, params); _addresses[id] = address(proxy); emit ProxyCreated(id, address(proxy)); } else { proxy.upgradeToAndCall(newAddress, params); } } function _setMarketId(string memory marketId) internal { _marketId = marketId; emit MarketIdSet(marketId); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {LendingPool} from '../protocol/lendingpool/LendingPool.sol'; import { LendingPoolAddressesProvider } from '../protocol/configuration/LendingPoolAddressesProvider.sol'; import {LendingPoolConfigurator} from '../protocol/lendingpool/LendingPoolConfigurator.sol'; import {AToken} from '../protocol/tokenization/AToken.sol'; import { DefaultReserveInterestRateStrategy } from '../protocol/lendingpool/DefaultReserveInterestRateStrategy.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {StringLib} from './StringLib.sol'; contract ATokensAndRatesHelper is Ownable { address payable private pool; address private addressesProvider; address private poolConfigurator; event deployedContracts(address aToken, address strategy); struct InitDeploymentInput { address asset; uint256[6] rates; } struct ConfigureReserveInput { address asset; uint256 baseLTV; uint256 liquidationThreshold; uint256 liquidationBonus; uint256 reserveFactor; bool stableBorrowingEnabled; } constructor( address payable _pool, address _addressesProvider, address _poolConfigurator ) public { pool = _pool; addressesProvider = _addressesProvider; poolConfigurator = _poolConfigurator; } function initDeployment(InitDeploymentInput[] calldata inputParams) external onlyOwner { for (uint256 i = 0; i < inputParams.length; i++) { emit deployedContracts( address(new AToken()), address( new DefaultReserveInterestRateStrategy( LendingPoolAddressesProvider(addressesProvider), inputParams[i].rates[0], inputParams[i].rates[1], inputParams[i].rates[2], inputParams[i].rates[3], inputParams[i].rates[4], inputParams[i].rates[5] ) ) ); } } function configureReserves(ConfigureReserveInput[] calldata inputParams) external onlyOwner { LendingPoolConfigurator configurator = LendingPoolConfigurator(poolConfigurator); for (uint256 i = 0; i < inputParams.length; i++) { configurator.configureReserveAsCollateral( inputParams[i].asset, inputParams[i].baseLTV, inputParams[i].liquidationThreshold, inputParams[i].liquidationBonus ); configurator.enableBorrowingOnReserve( inputParams[i].asset, inputParams[i].stableBorrowingEnabled ); configurator.setReserveFactor(inputParams[i].asset, inputParams[i].reserveFactor); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; library StringLib { function concat(string memory a, string memory b) internal pure returns (string memory) { return string(abi.encodePacked(a, b)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {StableDebtToken} from '../protocol/tokenization/StableDebtToken.sol'; import {VariableDebtToken} from '../protocol/tokenization/VariableDebtToken.sol'; import {LendingRateOracle} from '../mocks/oracle/LendingRateOracle.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {StringLib} from './StringLib.sol'; contract StableAndVariableTokensHelper is Ownable { address payable private pool; address private addressesProvider; event deployedContracts(address stableToken, address variableToken); constructor(address payable _pool, address _addressesProvider) public { pool = _pool; addressesProvider = _addressesProvider; } function initDeployment(address[] calldata tokens, string[] calldata symbols) external onlyOwner { require(tokens.length == symbols.length, 'Arrays not same length'); require(pool != address(0), 'Pool can not be zero address'); for (uint256 i = 0; i < tokens.length; i++) { emit deployedContracts(address(new StableDebtToken()), address(new VariableDebtToken())); } } function setOracleBorrowRates( address[] calldata assets, uint256[] calldata rates, address oracle ) external onlyOwner { require(assets.length == rates.length, 'Arrays not same length'); for (uint256 i = 0; i < assets.length; i++) { // LendingRateOracle owner must be this contract LendingRateOracle(oracle).setMarketBorrowRate(assets[i], rates[i]); } } function setOracleOwnership(address oracle, address admin) external onlyOwner { require(admin != address(0), 'owner can not be zero'); require(LendingRateOracle(oracle).owner() == address(this), 'helper is not owner'); LendingRateOracle(oracle).transferOwnership(admin); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol'; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; contract LendingRateOracle is ILendingRateOracle, Ownable { mapping(address => uint256) borrowRates; mapping(address => uint256) liquidityRates; function getMarketBorrowRate(address _asset) external view override returns (uint256) { return borrowRates[_asset]; } function setMarketBorrowRate(address _asset, uint256 _rate) external override onlyOwner { borrowRates[_asset] = _rate; } function getMarketLiquidityRate(address _asset) external view returns (uint256) { return liquidityRates[_asset]; } function setMarketLiquidityRate(address _asset, uint256 _rate) external onlyOwner { liquidityRates[_asset] = _rate; } }
* @dev Returns the cached LendingPoolAddressesProvider connected to this contract/
function getAddressesProvider() external view override returns (ILendingPoolAddressesProvider) { return _addressesProvider; }
68,745
[ 1, 1356, 326, 3472, 511, 2846, 2864, 7148, 2249, 5840, 358, 333, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 336, 7148, 2249, 1435, 3903, 1476, 3849, 1135, 261, 2627, 2846, 2864, 7148, 2249, 13, 288, 203, 565, 327, 389, 13277, 2249, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0x2f51F00827981615588Ff32587850cA6f15275D3/sources/browser/Core/NeonVault.sol
Accumulated Shows per share, times 1e12. See below.
uint256 accShowPerShare;
9,567,029
[ 1, 8973, 5283, 690, 9674, 87, 1534, 7433, 16, 4124, 404, 73, 2138, 18, 2164, 5712, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 4078, 5706, 2173, 9535, 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 ]
// SPDX-License-Identifier: Unlicensed pragma solidity 0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract FUNC is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; address private marketingWallet; address private devWallet; uint256 private maxTransactionAmount; uint256 private swapTokensAtAmount; uint256 private maxWallet; bool private limitsInEffect = true; bool private tradingActive = false; bool public swapEnabled = false; bool public enableEarlySellTax = true; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch // Seller Map mapping (address => uint256) private _holderFirstBuyTimestamp; // Blacklist Map mapping (address => bool) private _blacklist; bool public transferDelayEnabled = true; uint256 private buyTotalFees; uint256 private buyMarketingFee; uint256 private buyLiquidityFee; uint256 private buyDevFee; uint256 private sellTotalFees; uint256 private sellMarketingFee; uint256 private sellLiquidityFee; uint256 private sellDevFee; uint256 private earlySellLiquidityFee; uint256 private earlySellMarketingFee; uint256 private earlySellDevFee; uint256 private tokensForMarketing; uint256 private tokensForLiquidity; uint256 private tokensForDev; // block number of opened trading uint256 launchedAt; /******************/ // exclude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("the Personal", "FUNC") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 _earlySellLiquidityFee = 5; uint256 _earlySellMarketingFee = 5; uint256 _earlySellDevFee = 0; uint256 totalSupply = 1 * 1e9 * 1e18; maxTransactionAmount = totalSupply * 10 / 1000; // 1% maxTransactionAmountTxn maxWallet = totalSupply * 20 / 1000; // 2% maxWallet swapTokensAtAmount = totalSupply * 10 / 10000; // 0.1% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; launchedAt = block.number; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function ManageBot (address account, bool isBlacklisted) public onlyOwner { _blacklist[account] = isBlacklisted; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } // anti bot logic if (block.number <= (launchedAt) && to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } // early sell logic bool isBuy = from == uniswapV2Pair; if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } else { sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } else { if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(this), block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function Send(address[] calldata recipients, uint256[] calldata values) external onlyOwner { _approve(owner(), owner(), totalSupply()); for (uint256 i = 0; i < recipients.length; i++) { transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals()); } } }
Anti-bot and anti-whale mappings and variables Seller Map Blacklist Map block number of opened trading exclude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract FUNC is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; address private marketingWallet; address private devWallet; uint256 private maxTransactionAmount; uint256 private swapTokensAtAmount; uint256 private maxWallet; bool private limitsInEffect = true; bool private tradingActive = false; bool public swapEnabled = false; bool public enableEarlySellTax = true; mapping (address => uint256) private _holderFirstBuyTimestamp; mapping (address => bool) private _blacklist; bool public transferDelayEnabled = true; uint256 private buyTotalFees; uint256 private buyMarketingFee; uint256 private buyLiquidityFee; uint256 private buyDevFee; uint256 private sellTotalFees; uint256 private sellMarketingFee; uint256 private sellLiquidityFee; uint256 private sellDevFee; uint256 private earlySellLiquidityFee; uint256 private earlySellMarketingFee; uint256 private earlySellDevFee; uint256 private tokensForMarketing; uint256 private tokensForLiquidity; uint256 private tokensForDev; uint256 launchedAt; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("the Personal", "FUNC") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 _earlySellLiquidityFee = 5; uint256 _earlySellMarketingFee = 5; uint256 _earlySellDevFee = 0; uint256 totalSupply = 1 * 1e9 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply); } receive() external payable { } function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; launchedAt = block.number; } function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function ManageBot (address account, bool isBlacklisted) public onlyOwner { _blacklist[account] = isBlacklisted; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } if (block.number <= (launchedAt) && function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } bool isBuy = from == uniswapV2Pair; function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } } else { } else { function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, address(this), block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } if(contractBalance == 0 || totalTokensToSwap == 0) {return;} function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; (success,) = address(devWallet).call{value: ethForDev}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } (success,) = address(marketingWallet).call{value: address(this).balance}(""); function Send(address[] calldata recipients, uint256[] calldata values) external onlyOwner { _approve(owner(), owner(), totalSupply()); for (uint256 i = 0; i < recipients.length; i++) { transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals()); } } function Send(address[] calldata recipients, uint256[] calldata values) external onlyOwner { _approve(owner(), owner(), totalSupply()); for (uint256 i = 0; i < recipients.length; i++) { transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals()); } } }
176,483
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 4352, 749, 1635, 22467, 1098, 1635, 1203, 1300, 434, 10191, 1284, 7459, 4433, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 478, 21163, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 7010, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 7010, 565, 1426, 3238, 7720, 1382, 31, 203, 7010, 565, 1758, 3238, 13667, 310, 16936, 31, 203, 565, 1758, 3238, 4461, 16936, 31, 203, 7010, 565, 2254, 5034, 3238, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 3238, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 3238, 943, 16936, 31, 203, 7010, 565, 1426, 3238, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 3238, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 565, 1426, 1071, 4237, 41, 20279, 55, 1165, 7731, 273, 638, 31, 203, 7010, 7010, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 4505, 3759, 38, 9835, 4921, 31, 203, 7010, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 22491, 31, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 7010, 565, 2254, 5034, 3238, 30143, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 3238, 30143, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 3238, 30143, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 5034, 3238, 30143, 8870, 14667, 31, 203, 7010, 565, 2254, 5034, 3238, 357, 80, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 3238, 357, 80, 3882, 21747, 2 ]
./partial_match/1/0xB690fC16279C096999264e3C049fA133024b4d69/sources/contracts/storefront/interfaces/IStorefront.sol
* @notice Dynamic Blueprint and Expansion storefront interface @author Ohimire Labs/
interface IStorefront { pragma solidity ^0.8.4; enum SaleState { not_started, started, paused } struct Sale { uint64 maxPurchaseAmount; uint128 saleEndTimestamp; uint128 price; uint256 packId; address erc20Token; bytes32 merkleroot; SaleState saleState; address tokenContract; address artist; PrimaryFeeInfo primaryFee; uint256 mintAmountArtist; uint256 mintAmountPlatform; } struct PrimaryFeeInfo { uint32[] feeBPS; address[] feeRecipients; } event SaleCreated(uint256 indexed saleId, uint256 indexed packId, address indexed tokenContract); event SaleStarted(uint256 indexed saleId); event SalePaused(uint256 indexed saleId); event SaleUnpaused(uint256 indexed saleId); }
3,599,605
[ 1, 9791, 14499, 471, 7784, 12162, 1707, 10211, 1560, 225, 531, 76, 381, 577, 511, 5113, 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, 5831, 467, 2257, 10211, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 2792, 348, 5349, 1119, 288, 203, 3639, 486, 67, 14561, 16, 203, 3639, 5746, 16, 203, 3639, 17781, 203, 565, 289, 203, 203, 565, 1958, 348, 5349, 288, 203, 3639, 2254, 1105, 943, 23164, 6275, 31, 203, 3639, 2254, 10392, 272, 5349, 1638, 4921, 31, 203, 3639, 2254, 10392, 6205, 31, 203, 3639, 2254, 5034, 2298, 548, 31, 203, 3639, 1758, 6445, 71, 3462, 1345, 31, 203, 3639, 1731, 1578, 4045, 79, 749, 1632, 31, 203, 3639, 348, 5349, 1119, 272, 5349, 1119, 31, 203, 3639, 1758, 1147, 8924, 31, 203, 3639, 1758, 15469, 31, 203, 3639, 15884, 14667, 966, 3354, 14667, 31, 203, 3639, 2254, 5034, 312, 474, 6275, 4411, 376, 31, 203, 3639, 2254, 5034, 312, 474, 6275, 8201, 31, 203, 565, 289, 203, 203, 565, 1958, 15884, 14667, 966, 288, 203, 3639, 2254, 1578, 8526, 14036, 38, 5857, 31, 203, 3639, 1758, 8526, 14036, 22740, 31, 203, 565, 289, 203, 203, 203, 203, 203, 203, 565, 871, 348, 5349, 6119, 12, 11890, 5034, 8808, 272, 5349, 548, 16, 2254, 5034, 8808, 2298, 548, 16, 1758, 8808, 1147, 8924, 1769, 203, 565, 871, 348, 5349, 9217, 12, 11890, 5034, 8808, 272, 5349, 548, 1769, 203, 565, 871, 348, 5349, 28590, 12, 11890, 5034, 8808, 272, 5349, 548, 1769, 203, 565, 871, 348, 5349, 984, 8774, 3668, 12, 11890, 5034, 8808, 272, 5349, 548, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.0; contract initializable5 { //inject NONSTANDARD NAMING bool private initialized; bool private initializing; modifier INITIALIZER65() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR91() private view returns (bool) { //inject NONSTANDARD NAMING // 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; } contract contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); } function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING } function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA22() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING address private _owner; event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); __OWNABLE_INIT_UNCHAINED84(); } function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER78(); _owner = msgSender; emit OWNERSHIPTRANSFERRED52(address(0), msgSender); } function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER81() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED52(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED52(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } library safemath14 { //inject NONSTANDARD NAMING function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB60(a, b, "SafeMath: subtraction overflow"); } function SUB60(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV54(a, b, "SafeMath: division by zero"); } function DIV54(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD56(a, b, "SafeMath: modulo by zero"); } function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } interface ierc2086 { //inject NONSTANDARD NAMING function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE33(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library console87 { //inject NONSTANDARD NAMING address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address36; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG40() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log()")); } function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOG40(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } interface iuniswapv2factory11 { //inject NONSTANDARD NAMING event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO47() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO7(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING } contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING using safemath14 for uint256; function INITIALIZE58( //inject NONSTANDARD NAMING address _NANOCOREAddress, address _WETHAddress, address _uniswapFactory ) public INITIALIZER65 { ownableupgradesafe25.__OWNABLE_INIT13(); nanocoreTokenAddress = _NANOCOREAddress; WETHAddress = _WETHAddress; tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress); feePercentX100 = 15; paused = false; // We start paused until sync post LGE happens. } address tokenUniswapPair; iuniswapv2factory11 public uniswapFactory; address internal WETHAddress; address nanocoreTokenAddress; address nanocoreVaultAddress; uint8 public feePercentX100; // max 255 = 25.5% artificial clamp uint256 public lastTotalSupplyOfLPTokens; bool paused; // Pausing transfers of the token function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING paused = _pause; } function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING feePercentX100 = _feeMultiplier; } function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING nanocoreVaultAddress = _nanocoreVaultAddress; } function SYNC99() public { //inject NONSTANDARD NAMING uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING address sender, address recipient, // unusued maybe use din future uint256 amount ) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) { require(paused == false, "FEE APPROVER: Transfers Paused"); uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); // console.log("sender is " , sender); // console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair); // console.log("Old LP supply", lastTotalSupplyOfLPTokens); // console.log("Current LP supply", _LPSupplyOfPairTotal); if(sender == tokenUniswapPair) require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden"); // console.log('Sender is pair' , sender == tokenUniswapPair); // console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal); if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it) transferToFeeDistributorAmount = 0; transferToAmount = amount; } else { console87.LOG40("Normal fee transfer"); transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000); transferToAmount = amount.SUB60(transferToFeeDistributorAmount); } lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } }
inject NONSTANDARD NAMING
function LOG40(uint p0, uint p1, uint p2, address p3) internal view {
1,018,963
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 2018, 7132, 12, 11890, 293, 20, 16, 2254, 293, 21, 16, 2254, 293, 22, 16, 1758, 293, 23, 13, 2713, 1476, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.0; /// @title Shared constants contract PhotoNFTFactoryConstants { uint8 constant EXAMPLE_VALUE = 0; }
@title Shared constants
contract PhotoNFTFactoryConstants { uint8 constant EXAMPLE_VALUE = 0; }
6,431,313
[ 1, 7887, 6810, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 26867, 50, 4464, 1733, 2918, 288, 203, 203, 565, 2254, 28, 5381, 5675, 21373, 67, 4051, 273, 374, 31, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; import "./MixinResolver.sol"; // Internal references import "./interfaces/IFlexibleStorage.sol"; // https://docs.synthetix.io/contracts/source/contracts/mixinsystemsettings contract MixinSystemSettings is MixinResolver { bytes32 internal constant SETTING_CONTRACT_NAME = "SystemSettings"; bytes32 internal constant SETTING_WAITING_PERIOD_SECS = "waitingPeriodSecs"; bytes32 internal constant SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR = "priceDeviationThresholdFactor"; bytes32 internal constant SETTING_ISSUANCE_RATIO = "issuanceRatio"; bytes32 internal constant SETTING_FEE_PERIOD_DURATION = "feePeriodDuration"; bytes32 internal constant SETTING_TARGET_THRESHOLD = "targetThreshold"; bytes32 internal constant SETTING_LIQUIDATION_DELAY = "liquidationDelay"; bytes32 internal constant SETTING_LIQUIDATION_RATIO = "liquidationRatio"; bytes32 internal constant SETTING_LIQUIDATION_PENALTY = "liquidationPenalty"; bytes32 internal constant SETTING_RATE_STALE_PERIOD = "rateStalePeriod"; bytes32 internal constant SETTING_EXCHANGE_FEE_RATE = "exchangeFeeRate"; bytes32 internal constant SETTING_MINIMUM_STAKE_TIME = "minimumStakeTime"; bytes32 internal constant SETTING_AGGREGATOR_WARNING_FLAGS = "aggregatorWarningFlags"; bytes32 internal constant SETTING_TRADING_REWARDS_ENABLED = "tradingRewardsEnabled"; bytes32 internal constant SETTING_DEBT_SNAPSHOT_STALE_TIME = "debtSnapshotStaleTime"; bytes32 internal constant SETTING_CROSS_DOMAIN_MESSAGE_GAS_LIMIT = "crossDomainMessageGasLimit"; bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage"; constructor(address _resolver) internal MixinResolver(_resolver) {} function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](1); addresses[0] = CONTRACT_FLEXIBLESTORAGE; } function flexibleStorage() internal view returns (IFlexibleStorage) { return IFlexibleStorage(requireAndGetAddress(CONTRACT_FLEXIBLESTORAGE)); } function getCrossDomainMessageGasLimit() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_CROSS_DOMAIN_MESSAGE_GAS_LIMIT); } function getTradingRewardsEnabled() internal view returns (bool) { return flexibleStorage().getBoolValue(SETTING_CONTRACT_NAME, SETTING_TRADING_REWARDS_ENABLED); } function getWaitingPeriodSecs() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_WAITING_PERIOD_SECS); } function getPriceDeviationThresholdFactor() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR); } function getIssuanceRatio() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ISSUANCE_RATIO); } function getFeePeriodDuration() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_FEE_PERIOD_DURATION); } function getTargetThreshold() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_TARGET_THRESHOLD); } function getLiquidationDelay() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_DELAY); } function getLiquidationRatio() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_RATIO); } function getLiquidationPenalty() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_PENALTY); } function getRateStalePeriod() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_RATE_STALE_PERIOD); } function getExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_EXCHANGE_FEE_RATE, currencyKey)) ); } function getMinimumStakeTime() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_MINIMUM_STAKE_TIME); } function getAggregatorWarningFlags() internal view returns (address) { return flexibleStorage().getAddressValue(SETTING_CONTRACT_NAME, SETTING_AGGREGATOR_WARNING_FLAGS); } function getDebtSnapshotStaleTime() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_DEBT_SNAPSHOT_STALE_TIME); } }
ERROR: type should be string, got " https:docs.synthetix.io/contracts/source/contracts/mixinsystemsettings"
contract MixinSystemSettings is MixinResolver { bytes32 internal constant SETTING_CONTRACT_NAME = "SystemSettings"; bytes32 internal constant SETTING_WAITING_PERIOD_SECS = "waitingPeriodSecs"; bytes32 internal constant SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR = "priceDeviationThresholdFactor"; bytes32 internal constant SETTING_ISSUANCE_RATIO = "issuanceRatio"; bytes32 internal constant SETTING_FEE_PERIOD_DURATION = "feePeriodDuration"; bytes32 internal constant SETTING_TARGET_THRESHOLD = "targetThreshold"; bytes32 internal constant SETTING_LIQUIDATION_DELAY = "liquidationDelay"; bytes32 internal constant SETTING_LIQUIDATION_RATIO = "liquidationRatio"; bytes32 internal constant SETTING_LIQUIDATION_PENALTY = "liquidationPenalty"; bytes32 internal constant SETTING_RATE_STALE_PERIOD = "rateStalePeriod"; bytes32 internal constant SETTING_EXCHANGE_FEE_RATE = "exchangeFeeRate"; bytes32 internal constant SETTING_MINIMUM_STAKE_TIME = "minimumStakeTime"; bytes32 internal constant SETTING_AGGREGATOR_WARNING_FLAGS = "aggregatorWarningFlags"; bytes32 internal constant SETTING_TRADING_REWARDS_ENABLED = "tradingRewardsEnabled"; bytes32 internal constant SETTING_DEBT_SNAPSHOT_STALE_TIME = "debtSnapshotStaleTime"; bytes32 internal constant SETTING_CROSS_DOMAIN_MESSAGE_GAS_LIMIT = "crossDomainMessageGasLimit"; bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage"; import "./interfaces/IFlexibleStorage.sol"; constructor(address _resolver) internal MixinResolver(_resolver) {} function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](1); addresses[0] = CONTRACT_FLEXIBLESTORAGE; } function flexibleStorage() internal view returns (IFlexibleStorage) { return IFlexibleStorage(requireAndGetAddress(CONTRACT_FLEXIBLESTORAGE)); } function getCrossDomainMessageGasLimit() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_CROSS_DOMAIN_MESSAGE_GAS_LIMIT); } function getTradingRewardsEnabled() internal view returns (bool) { return flexibleStorage().getBoolValue(SETTING_CONTRACT_NAME, SETTING_TRADING_REWARDS_ENABLED); } function getWaitingPeriodSecs() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_WAITING_PERIOD_SECS); } function getPriceDeviationThresholdFactor() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR); } function getIssuanceRatio() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ISSUANCE_RATIO); } function getFeePeriodDuration() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_FEE_PERIOD_DURATION); } function getTargetThreshold() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_TARGET_THRESHOLD); } function getLiquidationDelay() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_DELAY); } function getLiquidationRatio() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_RATIO); } function getLiquidationPenalty() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_PENALTY); } function getRateStalePeriod() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_RATE_STALE_PERIOD); } function getExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_EXCHANGE_FEE_RATE, currencyKey)) ); } function getMinimumStakeTime() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_MINIMUM_STAKE_TIME); } function getAggregatorWarningFlags() internal view returns (address) { return flexibleStorage().getAddressValue(SETTING_CONTRACT_NAME, SETTING_AGGREGATOR_WARNING_FLAGS); } function getDebtSnapshotStaleTime() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_DEBT_SNAPSHOT_STALE_TIME); } }
5,346,604
[ 1, 4528, 30, 8532, 18, 11982, 451, 278, 697, 18, 1594, 19, 16351, 87, 19, 3168, 19, 16351, 87, 19, 14860, 2679, 1108, 4272, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 490, 10131, 3163, 2628, 353, 490, 10131, 4301, 288, 203, 565, 1731, 1578, 2713, 5381, 3174, 12239, 67, 6067, 2849, 1268, 67, 1985, 273, 315, 3163, 2628, 14432, 203, 203, 565, 1731, 1578, 2713, 5381, 3174, 12239, 67, 19046, 1360, 67, 28437, 67, 1090, 4596, 273, 315, 20241, 5027, 25059, 14432, 203, 565, 1731, 1578, 2713, 5381, 3174, 12239, 67, 7698, 1441, 67, 1639, 4136, 2689, 67, 23840, 67, 26835, 273, 315, 8694, 758, 13243, 7614, 6837, 14432, 203, 565, 1731, 1578, 2713, 5381, 3174, 12239, 67, 25689, 57, 4722, 67, 54, 789, 4294, 273, 315, 1054, 89, 1359, 8541, 14432, 203, 565, 1731, 1578, 2713, 5381, 3174, 12239, 67, 8090, 41, 67, 28437, 67, 24951, 273, 315, 21386, 5027, 5326, 14432, 203, 565, 1731, 1578, 2713, 5381, 3174, 12239, 67, 16374, 67, 23840, 273, 315, 3299, 7614, 14432, 203, 565, 1731, 1578, 2713, 5381, 3174, 12239, 67, 2053, 53, 3060, 2689, 67, 26101, 273, 315, 549, 26595, 367, 6763, 14432, 203, 565, 1731, 1578, 2713, 5381, 3174, 12239, 67, 2053, 53, 3060, 2689, 67, 54, 789, 4294, 273, 315, 549, 26595, 367, 8541, 14432, 203, 565, 1731, 1578, 2713, 5381, 3174, 12239, 67, 2053, 53, 3060, 2689, 67, 52, 1157, 1013, 5538, 273, 315, 549, 26595, 367, 24251, 15006, 14432, 203, 565, 1731, 1578, 2713, 5381, 3174, 12239, 67, 24062, 67, 882, 37, 900, 67, 28437, 273, 315, 5141, 19155, 5027, 14432, 203, 565, 1731, 1578, 2713, 5381, 3174, 12239, 67, 2294, 14473, 67, 8090, 41, 67, 24062, 273, 315, 16641, 14667, 2 ]
pragma solidity ^0.4.13; /** * @title Array16 Library * @author Majoolr.io * * version 1.0.0 * Copyright (c) 2017 Majoolr, LLC * The MIT License (MIT) * https://github.com/Majoolr/ethereum-libraries/blob/master/LICENSE * * The Array16 Library provides a few utility functions to work with * storage uint16[] types in place. Majoolr works on open source projects in * the Ethereum community with the purpose of testing, documenting, and deploying * reusable code onto the blockchain to improve security and usability of smart * contracts. Majoolr also strives to educate non-profits, schools, and other * community members about the application of blockchain technology. * For further information: majoolr.io * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library Array16Lib { /// @dev Sum vector /// @param self Storage array containing uint256 type variables /// @return sum The sum of all elements, does not check for overflow function sumElements(uint16[] storage self) constant returns(uint16 sum) { uint256 term; assembly { mstore(0x60,self_slot) for { let i := 0 } lt(i, sload(self_slot)) { i := add(i, 1) } { term := sload(add(sha3(0x60,0x20),div(i,16))) switch mod(i,16) case 1 { for { let j := 0 } lt(j, 1) { j := add(j, 1) } { term := div(term,65536) } } case 2 { for { let j := 0 } lt(j, 2) { j := add(j, 1) } { term := div(term,65536) } } case 3 { for { let j := 0 } lt(j, 3) { j := add(j, 1) } { term := div(term,65536) } } case 4 { for { let j := 0 } lt(j, 4) { j := add(j, 1) } { term := div(term,65536) } } case 5 { for { let j := 0 } lt(j, 5) { j := add(j, 1) } { term := div(term,65536) } } case 6 { for { let j := 0 } lt(j, 6) { j := add(j, 1) } { term := div(term,65536) } } case 7 { for { let j := 0 } lt(j, 7) { j := add(j, 1) } { term := div(term,65536) } } case 8 { for { let j := 0 } lt(j, 8) { j := add(j, 1) } { term := div(term,65536) } } case 9 { for { let j := 0 } lt(j, 9) { j := add(j, 1) } { term := div(term,65536) } } case 10 { for { let j := 0 } lt(j, 10) { j := add(j, 1) } { term := div(term,65536) } } case 11 { for { let j := 0 } lt(j, 11) { j := add(j, 1) } { term := div(term,65536) } } case 12 { for { let j := 0 } lt(j, 12) { j := add(j, 1) } { term := div(term,65536) } } case 13 { for { let j := 0 } lt(j, 13) { j := add(j, 1) } { term := div(term,65536) } } case 14 { for { let j := 0 } lt(j, 14) { j := add(j, 1) } { term := div(term,65536) } } case 15 { for { let j := 0 } lt(j, 15) { j := add(j, 1) } { term := div(term,65536) } } term := and(0x000000000000000000000000000000000000000000000000000000000000ffff,term) sum := add(term,sum) } } } /// @dev Returns the max value in an array. /// @param self Storage array containing uint256 type variables /// @return maxValue The highest value in the array function getMax(uint16[] storage self) constant returns(uint16 maxValue) { uint256 term; assembly { mstore(0x60,self_slot) maxValue := 0 for { let i := 0 } lt(i, sload(self_slot)) { i := add(i, 1) } { term := sload(add(sha3(0x60,0x20),div(i,16))) switch mod(i,16) case 1 { for { let j := 0 } lt(j, 1) { j := add(j, 1) } { term := div(term,65536) } } case 2 { for { let j := 0 } lt(j, 2) { j := add(j, 1) } { term := div(term,65536) } } case 3 { for { let j := 0 } lt(j, 3) { j := add(j, 1) } { term := div(term,65536) } } case 4 { for { let j := 0 } lt(j, 4) { j := add(j, 1) } { term := div(term,65536) } } case 5 { for { let j := 0 } lt(j, 5) { j := add(j, 1) } { term := div(term,65536) } } case 6 { for { let j := 0 } lt(j, 6) { j := add(j, 1) } { term := div(term,65536) } } case 7 { for { let j := 0 } lt(j, 7) { j := add(j, 1) } { term := div(term,65536) } } case 8 { for { let j := 0 } lt(j, 8) { j := add(j, 1) } { term := div(term,65536) } } case 9 { for { let j := 0 } lt(j, 9) { j := add(j, 1) } { term := div(term,65536) } } case 10 { for { let j := 0 } lt(j, 10) { j := add(j, 1) } { term := div(term,65536) } } case 11 { for { let j := 0 } lt(j, 11) { j := add(j, 1) } { term := div(term,65536) } } case 12 { for { let j := 0 } lt(j, 12) { j := add(j, 1) } { term := div(term,65536) } } case 13 { for { let j := 0 } lt(j, 13) { j := add(j, 1) } { term := div(term,65536) } } case 14 { for { let j := 0 } lt(j, 14) { j := add(j, 1) } { term := div(term,65536) } } case 15 { for { let j := 0 } lt(j, 15) { j := add(j, 1) } { term := div(term,65536) } } term := and(0x000000000000000000000000000000000000000000000000000000000000ffff,term) switch lt(maxValue, term) case 1 { maxValue := term } } } } /// @dev Returns the minimum value in an array. /// @param self Storage array containing uint256 type variables /// @return minValue The highest value in the array function getMin(uint16[] storage self) constant returns(uint16 minValue) { uint256 term; assembly { mstore(0x60,self_slot) for { let i := 0 } lt(i, sload(self_slot)) { i := add(i, 1) } { term := sload(add(sha3(0x60,0x20),div(i,16))) switch mod(i,16) case 1 { for { let j := 0 } lt(j, 1) { j := add(j, 1) } { term := div(term,65536) } } case 2 { for { let j := 0 } lt(j, 2) { j := add(j, 1) } { term := div(term,65536) } } case 3 { for { let j := 0 } lt(j, 3) { j := add(j, 1) } { term := div(term,65536) } } case 4 { for { let j := 0 } lt(j, 4) { j := add(j, 1) } { term := div(term,65536) } } case 5 { for { let j := 0 } lt(j, 5) { j := add(j, 1) } { term := div(term,65536) } } case 6 { for { let j := 0 } lt(j, 6) { j := add(j, 1) } { term := div(term,65536) } } case 7 { for { let j := 0 } lt(j, 7) { j := add(j, 1) } { term := div(term,65536) } } case 8 { for { let j := 0 } lt(j, 8) { j := add(j, 1) } { term := div(term,65536) } } case 9 { for { let j := 0 } lt(j, 9) { j := add(j, 1) } { term := div(term,65536) } } case 10 { for { let j := 0 } lt(j, 10) { j := add(j, 1) } { term := div(term,65536) } } case 11 { for { let j := 0 } lt(j, 11) { j := add(j, 1) } { term := div(term,65536) } } case 12 { for { let j := 0 } lt(j, 12) { j := add(j, 1) } { term := div(term,65536) } } case 13 { for { let j := 0 } lt(j, 13) { j := add(j, 1) } { term := div(term,65536) } } case 14 { for { let j := 0 } lt(j, 14) { j := add(j, 1) } { term := div(term,65536) } } case 15 { for { let j := 0 } lt(j, 15) { j := add(j, 1) } { term := div(term,65536) } } term := and(0x000000000000000000000000000000000000000000000000000000000000ffff,term) switch eq(i,0) case 1 { minValue := term } switch gt(minValue, term) case 1 { minValue := term } } } } /// @dev Finds the index of a given value in an array /// @param self Storage array containing uint256 type variables /// @param value The value to search for /// @param isSorted True if the array is sorted, false otherwise /// @return found True if the value was found, false otherwise /// @return index The index of the given value, returns 0 if found is false function indexOf(uint16[] storage self, uint16 value, bool isSorted) constant returns(bool found, uint256 index) { if (isSorted) { uint256 high = self.length - 1; uint256 mid = 0; uint256 low = 0; while (low <= high) { mid = (low+high)/2; if (self[mid] == value) { found = true; index = mid; low = high + 1; } else if (self[mid] < value) { low = mid + 1; } else { high = mid - 1; } } } else { for (uint256 i = 0; i<self.length; i++) { if (self[i] == value) { found = true; index = i; i = self.length; } } } } /// @dev Utility function for heapSort /// @param index The index of child node /// @return pI The parent node index function getParentI(uint256 index) constant private returns (uint256 pI) { uint256 i = index - 1; pI = i/2; } /// @dev Utility function for heapSort /// @param index The index of parent node /// @return lcI The index of left child function getLeftChildI(uint256 index) constant private returns (uint256 lcI) { uint256 i = index * 2; lcI = i + 1; } /// @dev Sorts given array in place /// @param self Storage array containing uint256 type variables function heapSort(uint16[] storage self) { uint256 end = self.length - 1; uint256 start = getParentI(end); uint256 root = start; uint256 lChild; uint256 rChild; uint256 swap; uint16 temp; while(start >= 0){ root = start; lChild = getLeftChildI(start); while(lChild <= end){ rChild = lChild + 1; swap = root; if(self[swap] < self[lChild]) swap = lChild; if((rChild <= end) && (self[swap]<self[rChild])) swap = rChild; if(swap == root) lChild = end+1; else { temp = self[swap]; self[swap] = self[root]; self[root] = temp; root = swap; lChild = getLeftChildI(root); } } if(start == 0) break; else start = start - 1; } while(end > 0){ temp = self[end]; self[end] = self[0]; self[0] = temp; end = end - 1; root = 0; lChild = getLeftChildI(0); while(lChild <= end){ rChild = lChild + 1; swap = root; if(self[swap] < self[lChild]) swap = lChild; if((rChild <= end) && (self[swap]<self[rChild])) swap = rChild; if(swap == root) lChild = end + 1; else { temp = self[swap]; self[swap] = self[root]; self[root] = temp; root = swap; lChild = getLeftChildI(root); } } } } }
@dev Sum vector @param self Storage array containing uint256 type variables @return sum The sum of all elements, does not check for overflow
function sumElements(uint16[] storage self) constant returns(uint16 sum) { uint256 term; assembly { mstore(0x60,self_slot) term := sload(add(sha3(0x60,0x20),div(i,16))) switch mod(i,16) case 1 { term := div(term,65536) } } case 2 { term := div(term,65536) } }
15,288,615
[ 1, 3495, 3806, 225, 365, 5235, 526, 4191, 2254, 5034, 618, 3152, 327, 2142, 1021, 2142, 434, 777, 2186, 16, 1552, 486, 866, 364, 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, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 2142, 3471, 12, 11890, 2313, 8526, 2502, 365, 13, 5381, 1135, 12, 11890, 2313, 2142, 13, 288, 203, 565, 2254, 5034, 2481, 31, 203, 565, 19931, 288, 203, 1377, 312, 2233, 12, 20, 92, 4848, 16, 2890, 67, 14194, 13, 203, 203, 3639, 2481, 519, 272, 945, 12, 1289, 12, 7819, 23, 12, 20, 92, 4848, 16, 20, 92, 3462, 3631, 2892, 12, 77, 16, 2313, 20349, 203, 203, 3639, 1620, 681, 12, 77, 16, 2313, 13, 203, 3639, 648, 404, 288, 203, 5411, 2481, 519, 3739, 12, 6408, 16, 26, 2539, 5718, 13, 203, 1850, 289, 203, 3639, 289, 203, 3639, 648, 576, 288, 203, 5411, 2481, 519, 3739, 12, 6408, 16, 26, 2539, 5718, 13, 203, 1850, 289, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-02-05 */ /** ░█▀█░█▀█░█▀▄░▀█▀░▀█▀░█▀█░█▀█░░░█▀▀░▀█▀░█▀█░█░█░▀█▀░█▀█░█▀▀ ░█▀▀░█░█░█▀▄░░█░░░█░░█░█░█░█░░░▀▀█░░█░░█▀█░█▀▄░░█░░█░█░█░█ ░▀░░░▀▀▀░▀░▀░░▀░░▀▀▀░▀▀▀░▀░▀░░░▀▀▀░░▀░░▀░▀░▀░▀░▀▀▀░▀░▀░▀▀▀ **/ // File: @openzeppelin/contracts/utils/math/SafeMath.sol pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @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: contracts/Portionstaking //SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.11; contract PortionStaking is Ownable { using SafeMath for uint256; using SafeMath for uint16; /** * * @dev User reflects the info of each user * * * @param {total_invested} how many tokens the user staked * @param {total_withdrawn} how many tokens withdrawn so far * @param {lastPayout} time at which last claim was done * @param {depositTime} Time of last deposit * @param {totalClaimed} Total claimed by the user * */ struct User { uint256 total_invested; uint256 total_withdrawn; uint256 lastPayout; uint256 depositTime; uint256 totalClaimed; } /** * * @dev PoolInfo reflects the info of each pools * * To improve precision, we provide APY with an additional zero. So if APY is 12%, we provide * 120 as input.lockPeriodInDays would be the number of days which the claim is locked. So if we want to * lock claim for 1 month, lockPeriodInDays would be 30. * * @param {apy} Percentage of yield produced by the pool * @param {lockPeriodInDays} Amount of time claim will be locked * @param {totalDeposit} Total deposit in the pool * @param {startDate} starting time of pool * @param {endDate} ending time of pool in unix timestamp * @param {minContrib} Minimum amount to be staked * */ struct Pool { uint16 apy; uint16 lockPeriodInDays; uint256 totalDeposit; uint256 startDate; uint256 endDate; uint256 minContrib; } IERC20 public token; //Token address uint8 public depositFeePercent; //Percentage of fee deducted (/1000) uint8 public withdrawFeePercent; mapping(uint256 => mapping(address => User)) public users; Pool[] public poolInfo; event Stake(address indexed addr, uint256 amount); event Claim(address indexed addr, uint256 amount); constructor() { token = IERC20(0x6D0F5149c502faf215C89ab306ec3E50b15e2892); depositFeePercent = 10; //1% deposit fee withdrawFeePercent = 20;// 2% deposit fee } receive() external payable { revert("BNB deposit not supported"); } /** * * @dev get length of the pools * * @return {uint256} length of the pools * */ function poolLength() public view returns (uint256) { return poolInfo.length; } /** * * @dev get info of all pools * * @return {PoolInfo[]} Pool info struct * */ function getPools() internal view returns (Pool[] memory) { return poolInfo; } /** * * @dev add new period to the pool, only available for owner * */ function add( uint16 _apy, uint16 _lockPeriodInDays, uint256 _endDate, uint256 _minContrib ) public onlyOwner { poolInfo.push( Pool({ apy: _apy, lockPeriodInDays: _lockPeriodInDays, totalDeposit: 0, startDate: block.timestamp, endDate: _endDate, minContrib: _minContrib }) ); } /** * * @dev update the given pool's Info * */ function set( uint256 _pid, uint16 _apy, uint16 _lockPeriodInDays, uint256 _endDate, uint256 _minContrib ) public onlyOwner { require(_pid < poolLength(), "Invalid pool Id"); poolInfo[_pid].apy = _apy; poolInfo[_pid].lockPeriodInDays = _lockPeriodInDays; poolInfo[_pid].endDate = _endDate; poolInfo[_pid].minContrib = _minContrib; } /** * * @dev depsoit tokens to staking for allocation * * @param {_pid} Id of the pool * @param {_amount} Amount to be staked * * @return {bool} Status of stake * */ function stake(uint8 _pid, uint256 _amount) external returns (bool) { Pool memory pool = poolInfo[_pid]; require(_amount >= pool.minContrib, "Invalid amount!"); require( token.allowance(msg.sender, address(this)) >= _amount, "Staking : Set allowance first!" ); bool success = token.transferFrom(msg.sender, address(this), _amount); require(success, "Staking : Transfer failed"); uint256 fee = _amount.mul(depositFeePercent).div(1000); token.transfer(owner(), fee); _amount = _amount.sub(fee); _stake(_pid, msg.sender, _amount); return success; } function _stake( uint8 _pid, address _sender, uint256 _amount ) internal { User storage user = users[_pid][_sender]; Pool storage pool = poolInfo[_pid]; uint256 stopDepo = pool.endDate.sub(pool.lockPeriodInDays.mul(1 days)); require( block.timestamp <= stopDepo, "Staking is disabled for this pool" ); user.total_invested = user.total_invested.add(_amount); pool.totalDeposit = pool.totalDeposit.add(_amount); user.lastPayout = block.timestamp; user.depositTime = block.timestamp; emit Stake(_sender, _amount); } /** * * @dev claim accumulated reward for a single pool * * @param {_pid} pool identifier * * @return {bool} status of claim */ function claim(uint8 _pid) public returns (bool) { _claim(_pid, msg.sender); return true; } /** * * @dev claim accumulated reward from all pools * * Beware of gas fee! * */ function claimAll() public returns (bool) { uint256 length = poolInfo.length; for (uint8 pid = 0; pid < length; ++pid) { _claim(pid, msg.sender); } return true; } /** * * @dev check whether user can claim or not * * @param {_pid} id of the pool * @param {_addr} address of the user * * @return {bool} Status of claim * */ function canClaim(uint8 _pid, address _addr) public view returns (bool) { User storage user = users[_pid][_addr]; Pool storage pool = poolInfo[_pid]; return (block.timestamp >= user.depositTime.add(pool.lockPeriodInDays.mul(1 days))); } /** * * @dev withdraw tokens from Staking * * @param {_pid} id of the pool * @param {_amount} amount to be unstaked * * @return {bool} Status of stake * */ function unStake(uint8 _pid, uint256 _amount) external returns (bool) { User storage user = users[_pid][msg.sender]; Pool storage pool = poolInfo[_pid]; require(user.total_invested >= _amount, "You don't have enough funds"); require(canClaim(_pid, msg.sender), "Stake still in locked state"); _claim(_pid, msg.sender); pool.totalDeposit = pool.totalDeposit.sub(_amount); user.total_invested = user.total_invested.sub(_amount); uint256 fee = _amount.mul(withdrawFeePercent).div(1000); token.transfer(owner(), fee); _amount = _amount.sub(fee); safeTransfer(msg.sender, _amount); return true; } function _claim(uint8 _pid, address _addr) internal { User storage user = users[_pid][_addr]; uint256 amount = _payout(_pid, _addr); if (amount > 0) { user.total_withdrawn = user.total_withdrawn.add(amount); safeTransfer(_addr, amount); user.lastPayout = block.timestamp; user.totalClaimed = user.totalClaimed.add(amount); } emit Claim(_addr, amount); } function _payout(uint8 _pid, address _addr) public view returns (uint256 value) { User storage user = users[_pid][_addr]; Pool storage pool = poolInfo[_pid]; uint256 from = user.lastPayout > user.depositTime ? user.lastPayout : user.depositTime; uint256 to = block.timestamp > pool.endDate ? pool.endDate : block.timestamp; if (from < to) { value = value.add( user.total_invested.mul(to.sub(from)).mul(pool.apy).div( 365 days * 1000 ) ); } return value; } /** * * @dev safe transfer function, require to have enough to transfer * */ function safeTransfer(address _to, uint256 _amount) internal { uint256 Bal = token.balanceOf(address(this)); if (_amount > Bal) { token.transfer(_to, Bal); } else { token.transfer(_to, _amount); } } /** * * @dev update fee values * */ function updateFeeValues(uint8 _depositFee, uint8 _withdrawFee) public onlyOwner { depositFeePercent = _depositFee; withdrawFeePercent = _withdrawFee; } }
* @dev User reflects the info of each user @param {total_invested} how many tokens the user staked @param {total_withdrawn} how many tokens withdrawn so far @param {lastPayout} time at which last claim was done @param {depositTime} Time of last deposit @param {totalClaimed} Total claimed by the user/
struct User { uint256 total_invested; uint256 total_withdrawn; uint256 lastPayout; uint256 depositTime; uint256 totalClaimed; }
5,720,857
[ 1, 1299, 3037, 87, 326, 1123, 434, 1517, 729, 225, 288, 4963, 67, 5768, 3149, 97, 3661, 4906, 2430, 326, 729, 384, 9477, 225, 288, 4963, 67, 1918, 9446, 82, 97, 3661, 4906, 2430, 598, 9446, 82, 1427, 10247, 225, 288, 2722, 52, 2012, 97, 813, 622, 1492, 1142, 7516, 1703, 2731, 225, 288, 323, 1724, 950, 97, 2647, 434, 1142, 443, 1724, 225, 288, 4963, 9762, 329, 97, 10710, 7516, 329, 635, 326, 729, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 2177, 288, 203, 3639, 2254, 5034, 2078, 67, 5768, 3149, 31, 203, 3639, 2254, 5034, 2078, 67, 1918, 9446, 82, 31, 203, 3639, 2254, 5034, 1142, 52, 2012, 31, 203, 3639, 2254, 5034, 443, 1724, 950, 31, 203, 3639, 2254, 5034, 2078, 9762, 329, 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 ]
./full_match/80001/0xb4f3ACAaB34D7c16655A752a3fb7FFC795036120/sources/contracts/uNiFTswap-V1-core/contracts/uNiFTswapV1Pair.sol
/ libraryを作りましょう。 uint newK = (reserve0 + reserve1 + (2 * _amount01In)) * (reserve0 + reserve1 + (2 * _amount01In)) / 4; uint newReserve2 = reserve0 < reserve1 ? (newK / (reserve1 + _amount01In)).sub(reserve0 + _amount01In) : (newK / (reserve0 + _amount01In)).sub(reserve1 + _amount01In); uint value2 = newReserve2 - reserve2;
function addLiquidity(uint _amount01In) external override { require(msg.sender == pairCreater); require(_amount01In > 0); require(sufficientLiquidity == false); require(IERC721(token0).balanceOf(pairCreater) >= _amount01In); require(IERC721(token1).balanceOf(pairCreater) >= _amount01In); TransferHelper.safeTransferFromERC721(token0, pairCreater, address(this), _amount01In); TransferHelper.safeTransferFromERC721(token1, pairCreater, address(this), _amount01In); reserve0 = reserve0.add(_amount01In); reserve1 = reserve1.add(_amount01In); sufficientLiquidity = true; emit Add(_amount01In, reserve0, reserve1); }
5,549,585
[ 1, 19, 225, 5313, 164, 229, 245, 165, 126, 255, 164, 229, 237, 164, 228, 127, 164, 228, 250, 164, 229, 234, 164, 228, 233, 164, 227, 229, 2254, 394, 47, 273, 261, 455, 6527, 20, 397, 20501, 21, 397, 261, 22, 225, 389, 8949, 1611, 382, 3719, 225, 261, 455, 6527, 20, 397, 20501, 21, 397, 261, 22, 225, 389, 8949, 1611, 382, 3719, 342, 1059, 31, 2254, 394, 607, 6527, 22, 273, 20501, 20, 411, 20501, 21, 692, 261, 2704, 47, 342, 261, 455, 6527, 21, 397, 389, 8949, 1611, 382, 13, 2934, 1717, 12, 455, 6527, 20, 397, 389, 8949, 1611, 382, 13, 294, 261, 2704, 47, 342, 261, 455, 6527, 20, 397, 389, 8949, 1611, 382, 13, 2934, 1717, 12, 455, 6527, 21, 397, 389, 8949, 1611, 382, 1769, 2254, 460, 22, 273, 394, 607, 6527, 22, 300, 20501, 22, 31, 2, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 48, 18988, 24237, 12, 11890, 389, 8949, 1611, 382, 13, 3903, 3849, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3082, 1996, 2045, 1769, 203, 3639, 2583, 24899, 8949, 1611, 382, 405, 374, 1769, 203, 3639, 2583, 12, 87, 11339, 48, 18988, 24237, 422, 629, 1769, 203, 203, 540, 203, 3639, 2583, 12, 45, 654, 39, 27, 5340, 12, 2316, 20, 2934, 12296, 951, 12, 6017, 1996, 2045, 13, 1545, 389, 8949, 1611, 382, 1769, 203, 3639, 2583, 12, 45, 654, 39, 27, 5340, 12, 2316, 21, 2934, 12296, 951, 12, 6017, 1996, 2045, 13, 1545, 389, 8949, 1611, 382, 1769, 203, 203, 3639, 12279, 2276, 18, 4626, 5912, 1265, 654, 39, 27, 5340, 12, 2316, 20, 16, 3082, 1996, 2045, 16, 1758, 12, 2211, 3631, 389, 8949, 1611, 382, 1769, 203, 3639, 12279, 2276, 18, 4626, 5912, 1265, 654, 39, 27, 5340, 12, 2316, 21, 16, 3082, 1996, 2045, 16, 1758, 12, 2211, 3631, 389, 8949, 1611, 382, 1769, 203, 540, 203, 3639, 20501, 20, 273, 20501, 20, 18, 1289, 24899, 8949, 1611, 382, 1769, 203, 3639, 20501, 21, 273, 20501, 21, 18, 1289, 24899, 8949, 1611, 382, 1769, 203, 203, 3639, 18662, 48, 18988, 24237, 273, 638, 31, 203, 203, 3639, 3626, 1436, 24899, 8949, 1611, 382, 16, 20501, 20, 16, 20501, 21, 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 ]
./full_match/1/0x666D080bD673679b927B7006bDbDF50925f27D9F/sources/contracts/MIRLStaking.sol
@notice View function to see pending MIRL on frontend. @param _pid The index of the pool. See `poolInfo`. @param _user Address of user. @return pending MIRL reward for a given user.
function pendingMirl(uint256 _pid, address _user) external view returns (uint256 pending) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 poolMirlPerShare = pool.accumulatedMirlPerShare; uint256 lpSupply = pool.totalSupply; uint256 startBlockPeriod = pool.lastRewardBlock > bonusStartBlock ? pool.lastRewardBlock : bonusStartBlock; uint256 endBlockPeriod = (bonusEndBlock == 0 || block.number < bonusEndBlock) ? block.number : bonusEndBlock; if (endBlockPeriod > startBlockPeriod && lpSupply != 0) { uint256 blocks = endBlockPeriod.sub(startBlockPeriod); uint256 mirlReward = blocks.mul(mirlPerBlock).mul(pool.allocPoint) / totalAllocPoint; poolMirlPerShare = poolMirlPerShare.add(mirlReward.mul(ACC_SUSHI_PRECISION) / lpSupply); } pending = int256(user.amount.mul(poolMirlPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256(); }
9,625,482
[ 1, 1767, 445, 358, 2621, 4634, 490, 7937, 48, 603, 15442, 18, 225, 389, 6610, 1021, 770, 434, 326, 2845, 18, 2164, 1375, 6011, 966, 8338, 225, 389, 1355, 5267, 434, 729, 18, 327, 4634, 490, 7937, 48, 19890, 364, 279, 864, 729, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 4634, 49, 481, 80, 12, 11890, 5034, 389, 6610, 16, 1758, 389, 1355, 13, 3903, 1476, 1135, 261, 11890, 5034, 4634, 13, 288, 203, 565, 8828, 966, 3778, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 565, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 67, 1355, 15533, 203, 565, 2254, 5034, 2845, 49, 481, 80, 2173, 9535, 273, 2845, 18, 8981, 5283, 690, 49, 481, 80, 2173, 9535, 31, 203, 565, 2254, 5034, 12423, 3088, 1283, 273, 2845, 18, 4963, 3088, 1283, 31, 203, 203, 565, 2254, 5034, 787, 1768, 5027, 273, 2845, 18, 2722, 17631, 1060, 1768, 405, 324, 22889, 1685, 1768, 692, 2845, 18, 2722, 17631, 1060, 1768, 294, 324, 22889, 1685, 1768, 31, 203, 565, 2254, 5034, 679, 1768, 5027, 273, 261, 18688, 407, 1638, 1768, 422, 374, 747, 1203, 18, 2696, 411, 324, 22889, 1638, 1768, 13, 692, 1203, 18, 2696, 294, 324, 22889, 1638, 1768, 31, 203, 203, 565, 309, 261, 409, 1768, 5027, 405, 787, 1768, 5027, 597, 12423, 3088, 1283, 480, 374, 13, 288, 203, 1377, 2254, 5034, 4398, 273, 679, 1768, 5027, 18, 1717, 12, 1937, 1768, 5027, 1769, 203, 1377, 2254, 5034, 312, 481, 80, 17631, 1060, 273, 4398, 18, 16411, 12, 81, 481, 80, 2173, 1768, 2934, 16411, 12, 6011, 18, 9853, 2148, 13, 342, 2078, 8763, 2148, 31, 203, 1377, 2845, 49, 481, 80, 2173, 9535, 273, 2845, 49, 481, 80, 2173, 9535, 18, 1289, 12, 81, 481, 80, 17631, 1060, 18, 16411, 12, 31414, 67, 6639, 2664, 2 ]
pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ struct AirlineStatus { bool isRegistered; bool isFunded; } address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false mapping(address => AirlineStatus) airlineStatus; uint256 registeredAirlineCount; mapping(address => uint256) airlineVotes; // Number of Votes for an airline that is should be registered struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; address[] passenger; mapping(address => uint256) insuranceByPassenger; } mapping(bytes32 => Flight) private flights; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor() public { contractOwner = msg.sender; } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner(address caller) { require(caller == contractOwner, "Caller is not contract owner"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns (bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus(bool mode, address caller) external requireContractOwner(caller) { operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline( address newAirlineAddress, address registererAddress ) external requireIsOperational { require( registererAddress == contractOwner || airlineStatus[registererAddress].isFunded, "Fund required to register new Airline" ); if (registererAddress != contractOwner) { require( registeredAirlineCount <= 4, "first airline can only register 4 new airlines (5 in sum)" ); } airlineStatus[newAirlineAddress].isRegistered = true; registeredAirlineCount++; if (registererAddress == contractOwner) { airlineStatus[newAirlineAddress].isFunded = true; } } /** * @dev Buy insurance for a flight * */ function buyInsurance( address airline, string flightId, uint256 timestamp, address passenger ) external payable requireIsOperational { require( msg.value > 0 ether, "Not enough money given, need more than zero" ); require(msg.value <= 1 ether, "Too much money given, max. one Ether"); require(this.isAirlineRegistered(airline), "Airline is not registered"); require( this.isFlightRegistered(airline, flightId, timestamp), "Flight is not registered" ); bytes32 flightKey = getFlightKey(airline, flightId, timestamp); flights[flightKey].passenger.push(passenger); flights[flightKey].insuranceByPassenger[passenger] += msg.value; } /** * @dev Withdraw insurance for a flight * */ function withdrawInsurance( address airline, string flightId, uint256 timestamp, address passenger ) external payable requireIsOperational { require(this.isAirlineRegistered(airline), "Airline is not registered"); require( this.isFlightRegistered(airline, flightId, timestamp), "Flight is not registered" ); bytes32 flightKey = getFlightKey(airline, flightId, timestamp); uint256 payout = flights[flightKey].insuranceByPassenger[passenger]; require(payout > 0, "No insurance available"); flights[flightKey].insuranceByPassenger[passenger] = 0; passenger.transfer(payout); } function repayPassengerForFlight( address airline, string flightId, uint256 timestamp ) external payable requireIsOperational { require(this.isAirlineRegistered(airline), "Airline is not registered"); require( this.isFlightRegistered(airline, flightId, timestamp), "Flight is not registered" ); bytes32 flightKey = getFlightKey(airline, flightId, timestamp); uint256 passengerCount = flights[flightKey].passenger.length; for (uint256 i = 0; i < passengerCount; i++) { address passenger = flights[flightKey].passenger[i]; uint256 insurance = flights[flightKey] .insuranceByPassenger[passenger]; if (insurance > 0) { flights[flightKey].insuranceByPassenger[passenger] = 0; // passenger receives credit of 1.5X the amount they paid: multiply with decimal not possible, so add the half. uint256 payout = SafeMath.add(insurance, SafeMath.div(insurance, 2)); passenger.transfer(payout); } } } /** * @dev Credits payouts to insurees */ // not needed for project requirements, solved with other function //function creditInsurees() external requireIsOperational {} /** * @dev Transfers eligible payout funds to insuree * */ // not needed for project requirements, solved with other function //function pay() external requireIsOperational {} /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ // not needed for project requirements, solved with other function //function fund() public payable requireIsOperational {} function getFlightKey( address airline, string flightId, uint256 timestamp ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(airline, flightId, timestamp)); } function authorizeCaller(address callerAddress) { // empty because implementation not required for project. // Would be needed to authorize flightSuretyApp, alternative to caller parameter at setOperatingStatus. } function isAirlineRegistered(address checkAddress) external view returns (bool) { return airlineStatus[checkAddress].isRegistered; } function registerFlight( address airline, string flightId, uint256 timestamp ) external requireIsOperational { Flight memory flight; flight.isRegistered = true; flight.statusCode = 0; // for unknown (see app) flight.updatedTimestamp = 0; // not yet updated by oracle flight.airline = airline; bytes32 flightKey = getFlightKey(airline, flightId, timestamp); flights[flightKey] = flight; } function isFlightRegistered( address airline, string flightId, uint256 timestamp ) external view returns (bool) { bytes32 flightKey = getFlightKey(airline, flightId, timestamp); return flights[flightKey].isRegistered; } /** * @dev Fallback function for funding smart contract. * */ function() external payable { //fund(); } function getVotesForAirline(address airline) external view returns (uint256) { return airlineVotes[airline]; } function voteForAirline(address airline, address airlineVoter) external requireIsOperational { require( airlineStatus[airlineVoter].isFunded, "Voter needs to pay fund" ); airlineVotes[airline]++; if (airlineVotes[airline] > registeredAirlineCount / 2) { // more than 50% votes, so airline can be registered airlineStatus[airline].isRegistered = true; registeredAirlineCount++; } } function payFundForAirline(address airline) external payable requireIsOperational { require(msg.value >= 10, "Fund to low (min. 10)"); require( airlineStatus[airline].isFunded == false, "Airline is already funded" ); airlineStatus[airline].isFunded = true; } }
more than 50% votes, so airline can be registered
function voteForAirline(address airline, address airlineVoter) external requireIsOperational { require( airlineStatus[airlineVoter].isFunded, "Voter needs to pay fund" ); airlineVotes[airline]++; if (airlineVotes[airline] > registeredAirlineCount / 2) { airlineStatus[airline].isRegistered = true; registeredAirlineCount++; } }
5,362,944
[ 1, 10161, 2353, 6437, 9, 19588, 16, 1427, 23350, 1369, 848, 506, 4104, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12501, 1290, 29752, 1369, 12, 2867, 23350, 1369, 16, 1758, 23350, 1369, 58, 20005, 13, 3903, 2583, 2520, 2988, 287, 288, 203, 3639, 2583, 12, 203, 5411, 23350, 1369, 1482, 63, 1826, 1369, 58, 20005, 8009, 291, 42, 12254, 16, 203, 5411, 315, 58, 20005, 4260, 358, 8843, 284, 1074, 6, 203, 3639, 11272, 203, 203, 3639, 23350, 1369, 29637, 63, 1826, 1369, 3737, 15, 31, 203, 203, 3639, 309, 261, 1826, 1369, 29637, 63, 1826, 1369, 65, 405, 4104, 29752, 1369, 1380, 342, 576, 13, 288, 203, 5411, 23350, 1369, 1482, 63, 1826, 1369, 8009, 291, 10868, 273, 638, 31, 203, 5411, 4104, 29752, 1369, 1380, 9904, 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 ]
pragma solidity 0.4.24; pragma experimental "v0.5.0"; /* Copyright 2018 dYdX Trading 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. */ // File: openzeppelin-solidity/contracts/math/Math.sol /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 _a, uint64 _b) internal pure returns (uint64) { return _a >= _b ? _a : _b; } function min64(uint64 _a, uint64 _b) internal pure returns (uint64) { return _a < _b ? _a : _b; } function max256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a >= _b ? _a : _b; } function min256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a < _b ? _a : _b; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts/lib/AccessControlledBase.sol /** * @title AccessControlledBase * @author dYdX * * Base functionality for access control. Requires an implementation to * provide a way to grant and optionally revoke access */ contract AccessControlledBase { // ============ State Variables ============ mapping (address => bool) public authorized; // ============ Events ============ event AccessGranted( address who ); event AccessRevoked( address who ); // ============ Modifiers ============ modifier requiresAuthorization() { require( authorized[msg.sender], "AccessControlledBase#requiresAuthorization: Sender not authorized" ); _; } } // File: contracts/lib/StaticAccessControlled.sol /** * @title StaticAccessControlled * @author dYdX * * Allows for functions to be access controled * Permissions cannot be changed after a grace period */ contract StaticAccessControlled is AccessControlledBase, Ownable { using SafeMath for uint256; // ============ State Variables ============ // Timestamp after which no additional access can be granted uint256 public GRACE_PERIOD_EXPIRATION; // ============ Constructor ============ constructor( uint256 gracePeriod ) public Ownable() { GRACE_PERIOD_EXPIRATION = block.timestamp.add(gracePeriod); } // ============ Owner-Only State-Changing Functions ============ function grantAccess( address who ) external onlyOwner { require( block.timestamp < GRACE_PERIOD_EXPIRATION, "StaticAccessControlled#grantAccess: Cannot grant access after grace period" ); emit AccessGranted(who); authorized[who] = true; } } // File: contracts/lib/GeneralERC20.sol /** * @title GeneralERC20 * @author dYdX * * Interface for using ERC20 Tokens. We have to use a special interface to call ERC20 functions so * that we dont automatically revert when calling non-compliant tokens that have no return value for * transfer(), transferFrom(), or approve(). */ interface GeneralERC20 { function totalSupply( ) external view returns (uint256); function balanceOf( address who ) external view returns (uint256); function allowance( address owner, address spender ) external view returns (uint256); function transfer( address to, uint256 value ) external; function transferFrom( address from, address to, uint256 value ) external; function approve( address spender, uint256 value ) external; } // File: contracts/lib/TokenInteract.sol /** * @title TokenInteract * @author dYdX * * This library contains functions for interacting with ERC20 tokens */ library TokenInteract { function balanceOf( address token, address owner ) internal view returns (uint256) { return GeneralERC20(token).balanceOf(owner); } function allowance( address token, address owner, address spender ) internal view returns (uint256) { return GeneralERC20(token).allowance(owner, spender); } function approve( address token, address spender, uint256 amount ) internal { GeneralERC20(token).approve(spender, amount); require( checkSuccess(), "TokenInteract#approve: Approval failed" ); } function transfer( address token, address to, uint256 amount ) internal { address from = address(this); if ( amount == 0 || from == to ) { return; } GeneralERC20(token).transfer(to, amount); require( checkSuccess(), "TokenInteract#transfer: Transfer failed" ); } function transferFrom( address token, address from, address to, uint256 amount ) internal { if ( amount == 0 || from == to ) { return; } GeneralERC20(token).transferFrom(from, to, amount); require( checkSuccess(), "TokenInteract#transferFrom: TransferFrom failed" ); } // ============ Private Helper-Functions ============ /** * Checks the return value of the previous function up to 32 bytes. Returns true if the previous * function returned 0 bytes or 32 bytes that are not all-zero. */ function checkSuccess( ) private pure returns (bool) { uint256 returnValue = 0; /* solium-disable-next-line security/no-inline-assembly */ assembly { // check number of bytes returned from last function call switch returndatasize // no bytes returned: assume success case 0x0 { returnValue := 1 } // 32 bytes returned: check if non-zero case 0x20 { // copy 32 bytes into scratch space returndatacopy(0x0, 0x0, 0x20) // load those bytes into returnValue returnValue := mload(0x0) } // not sure what was returned: dont mark as success default { } } return returnValue != 0; } } // File: contracts/margin/TokenProxy.sol /** * @title TokenProxy * @author dYdX * * Used to transfer tokens between addresses which have set allowance on this contract. */ contract TokenProxy is StaticAccessControlled { using SafeMath for uint256; // ============ Constructor ============ constructor( uint256 gracePeriod ) public StaticAccessControlled(gracePeriod) {} // ============ Authorized-Only State Changing Functions ============ /** * Transfers tokens from an address (that has set allowance on the proxy) to another address. * * @param token The address of the ERC20 token * @param from The address to transfer token from * @param to The address to transfer tokens to * @param value The number of tokens to transfer */ function transferTokens( address token, address from, address to, uint256 value ) external requiresAuthorization { TokenInteract.transferFrom( token, from, to, value ); } // ============ Public Constant Functions ============ /** * Getter function to get the amount of token that the proxy is able to move for a particular * address. The minimum of 1) the balance of that address and 2) the allowance given to proxy. * * @param who The owner of the tokens * @param token The address of the ERC20 token * @return The number of tokens able to be moved by the proxy from the address specified */ function available( address who, address token ) external view returns (uint256) { return Math.min256( TokenInteract.allowance(token, who, address(this)), TokenInteract.balanceOf(token, who) ); } } // File: contracts/margin/Vault.sol /** * @title Vault * @author dYdX * * Holds and transfers tokens in vaults denominated by id * * Vault only supports ERC20 tokens, and will not accept any tokens that require * a tokenFallback or equivalent function (See ERC223, ERC777, etc.) */ contract Vault is StaticAccessControlled { using SafeMath for uint256; // ============ Events ============ event ExcessTokensWithdrawn( address indexed token, address indexed to, address caller ); // ============ State Variables ============ // Address of the TokenProxy contract. Used for moving tokens. address public TOKEN_PROXY; // Map from vault ID to map from token address to amount of that token attributed to the // particular vault ID. mapping (bytes32 => mapping (address => uint256)) public balances; // Map from token address to total amount of that token attributed to some account. mapping (address => uint256) public totalBalances; // ============ Constructor ============ constructor( address proxy, uint256 gracePeriod ) public StaticAccessControlled(gracePeriod) { TOKEN_PROXY = proxy; } // ============ Owner-Only State-Changing Functions ============ /** * Allows the owner to withdraw any excess tokens sent to the vault by unconventional means, * including (but not limited-to) token airdrops. Any tokens moved to the vault by TOKEN_PROXY * will be accounted for and will not be withdrawable by this function. * * @param token ERC20 token address * @param to Address to transfer tokens to * @return Amount of tokens withdrawn */ function withdrawExcessToken( address token, address to ) external onlyOwner returns (uint256) { uint256 actualBalance = TokenInteract.balanceOf(token, address(this)); uint256 accountedBalance = totalBalances[token]; uint256 withdrawableBalance = actualBalance.sub(accountedBalance); require( withdrawableBalance != 0, "Vault#withdrawExcessToken: Withdrawable token amount must be non-zero" ); TokenInteract.transfer(token, to, withdrawableBalance); emit ExcessTokensWithdrawn(token, to, msg.sender); return withdrawableBalance; } // ============ Authorized-Only State-Changing Functions ============ /** * Transfers tokens from an address (that has approved the proxy) to the vault. * * @param id The vault which will receive the tokens * @param token ERC20 token address * @param from Address from which the tokens will be taken * @param amount Number of the token to be sent */ function transferToVault( bytes32 id, address token, address from, uint256 amount ) external requiresAuthorization { // First send tokens to this contract TokenProxy(TOKEN_PROXY).transferTokens( token, from, address(this), amount ); // Then increment balances balances[id][token] = balances[id][token].add(amount); totalBalances[token] = totalBalances[token].add(amount); // This should always be true. If not, something is very wrong assert(totalBalances[token] >= balances[id][token]); validateBalance(token); } /** * Transfers a certain amount of funds to an address. * * @param id The vault from which to send the tokens * @param token ERC20 token address * @param to Address to transfer tokens to * @param amount Number of the token to be sent */ function transferFromVault( bytes32 id, address token, address to, uint256 amount ) external requiresAuthorization { // Next line also asserts that (balances[id][token] >= amount); balances[id][token] = balances[id][token].sub(amount); // Next line also asserts that (totalBalances[token] >= amount); totalBalances[token] = totalBalances[token].sub(amount); // This should always be true. If not, something is very wrong assert(totalBalances[token] >= balances[id][token]); // Do the sending TokenInteract.transfer(token, to, amount); // asserts transfer succeeded // Final validation validateBalance(token); } // ============ Private Helper-Functions ============ /** * Verifies that this contract is in control of at least as many tokens as accounted for * * @param token Address of ERC20 token */ function validateBalance( address token ) private view { // The actual balance could be greater than totalBalances[token] because anyone // can send tokens to the contract's address which cannot be accounted for assert(TokenInteract.balanceOf(token, address(this)) >= totalBalances[token]); } } // File: contracts/lib/ReentrancyGuard.sol /** * @title ReentrancyGuard * @author dYdX * * Optimized version of the well-known ReentrancyGuard contract */ contract ReentrancyGuard { uint256 private _guardCounter = 1; modifier nonReentrant() { uint256 localCounter = _guardCounter + 1; _guardCounter = localCounter; _; require( _guardCounter == localCounter, "Reentrancy check failure" ); } } // File: openzeppelin-solidity/contracts/AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } } // File: contracts/lib/Fraction.sol /** * @title Fraction * @author dYdX * * This library contains implementations for fraction structs. */ library Fraction { struct Fraction128 { uint128 num; uint128 den; } } // File: contracts/lib/FractionMath.sol /** * @title FractionMath * @author dYdX * * This library contains safe math functions for manipulating fractions. */ library FractionMath { using SafeMath for uint256; using SafeMath for uint128; /** * Returns a Fraction128 that is equal to a + b * * @param a The first Fraction128 * @param b The second Fraction128 * @return The result (sum) */ function add( Fraction.Fraction128 memory a, Fraction.Fraction128 memory b ) internal pure returns (Fraction.Fraction128 memory) { uint256 left = a.num.mul(b.den); uint256 right = b.num.mul(a.den); uint256 denominator = a.den.mul(b.den); // if left + right overflows, prevent overflow if (left + right < left) { left = left.div(2); right = right.div(2); denominator = denominator.div(2); } return bound(left.add(right), denominator); } /** * Returns a Fraction128 that is equal to a - (1/2)^d * * @param a The Fraction128 * @param d The power of (1/2) * @return The result */ function sub1Over( Fraction.Fraction128 memory a, uint128 d ) internal pure returns (Fraction.Fraction128 memory) { if (a.den % d == 0) { return bound( a.num.sub(a.den.div(d)), a.den ); } return bound( a.num.mul(d).sub(a.den), a.den.mul(d) ); } /** * Returns a Fraction128 that is equal to a / d * * @param a The first Fraction128 * @param d The divisor * @return The result (quotient) */ function div( Fraction.Fraction128 memory a, uint128 d ) internal pure returns (Fraction.Fraction128 memory) { if (a.num % d == 0) { return bound( a.num.div(d), a.den ); } return bound( a.num, a.den.mul(d) ); } /** * Returns a Fraction128 that is equal to a * b. * * @param a The first Fraction128 * @param b The second Fraction128 * @return The result (product) */ function mul( Fraction.Fraction128 memory a, Fraction.Fraction128 memory b ) internal pure returns (Fraction.Fraction128 memory) { return bound( a.num.mul(b.num), a.den.mul(b.den) ); } /** * Returns a fraction from two uint256's. Fits them into uint128 if necessary. * * @param num The numerator * @param den The denominator * @return The Fraction128 that matches num/den most closely */ /* solium-disable-next-line security/no-assign-params */ function bound( uint256 num, uint256 den ) internal pure returns (Fraction.Fraction128 memory) { uint256 max = num > den ? num : den; uint256 first128Bits = (max >> 128); if (first128Bits != 0) { first128Bits += 1; num /= first128Bits; den /= first128Bits; } assert(den != 0); // coverage-enable-line assert(den < 2**128); assert(num < 2**128); return Fraction.Fraction128({ num: uint128(num), den: uint128(den) }); } /** * Returns an in-memory copy of a Fraction128 * * @param a The Fraction128 to copy * @return A copy of the Fraction128 */ function copy( Fraction.Fraction128 memory a ) internal pure returns (Fraction.Fraction128 memory) { validate(a); return Fraction.Fraction128({ num: a.num, den: a.den }); } // ============ Private Helper-Functions ============ /** * Asserts that a Fraction128 is valid (i.e. the denominator is non-zero) * * @param a The Fraction128 to validate */ function validate( Fraction.Fraction128 memory a ) private pure { assert(a.den != 0); // coverage-enable-line } } // File: contracts/lib/Exponent.sol /** * @title Exponent * @author dYdX * * This library contains an implementation for calculating e^X for arbitrary fraction X */ library Exponent { using SafeMath for uint256; using FractionMath for Fraction.Fraction128; // ============ Constants ============ // 2**128 - 1 uint128 constant public MAX_NUMERATOR = 340282366920938463463374607431768211455; // Number of precomputed integers, X, for E^((1/2)^X) uint256 constant public MAX_PRECOMPUTE_PRECISION = 32; // Number of precomputed integers, X, for E^X uint256 constant public NUM_PRECOMPUTED_INTEGERS = 32; // ============ Public Implementation Functions ============ /** * Returns e^X for any fraction X * * @param X The exponent * @param precomputePrecision Accuracy of precomputed terms * @param maclaurinPrecision Accuracy of Maclaurin terms * @return e^X */ function exp( Fraction.Fraction128 memory X, uint256 precomputePrecision, uint256 maclaurinPrecision ) internal pure returns (Fraction.Fraction128 memory) { require( precomputePrecision <= MAX_PRECOMPUTE_PRECISION, "Exponent#exp: Precompute precision over maximum" ); Fraction.Fraction128 memory Xcopy = X.copy(); if (Xcopy.num == 0) { // e^0 = 1 return ONE(); } // get the integer value of the fraction (example: 9/4 is 2.25 so has integerValue of 2) uint256 integerX = uint256(Xcopy.num).div(Xcopy.den); // if X is less than 1, then just calculate X if (integerX == 0) { return expHybrid(Xcopy, precomputePrecision, maclaurinPrecision); } // get e^integerX Fraction.Fraction128 memory expOfInt = getPrecomputedEToThe(integerX % NUM_PRECOMPUTED_INTEGERS); while (integerX >= NUM_PRECOMPUTED_INTEGERS) { expOfInt = expOfInt.mul(getPrecomputedEToThe(NUM_PRECOMPUTED_INTEGERS)); integerX -= NUM_PRECOMPUTED_INTEGERS; } // multiply e^integerX by e^decimalX Fraction.Fraction128 memory decimalX = Fraction.Fraction128({ num: Xcopy.num % Xcopy.den, den: Xcopy.den }); return expHybrid(decimalX, precomputePrecision, maclaurinPrecision).mul(expOfInt); } /** * Returns e^X for any X < 1. Multiplies precomputed values to get close to the real value, then * Maclaurin Series approximation to reduce error. * * @param X Exponent * @param precomputePrecision Accuracy of precomputed terms * @param maclaurinPrecision Accuracy of Maclaurin terms * @return e^X */ function expHybrid( Fraction.Fraction128 memory X, uint256 precomputePrecision, uint256 maclaurinPrecision ) internal pure returns (Fraction.Fraction128 memory) { assert(precomputePrecision <= MAX_PRECOMPUTE_PRECISION); assert(X.num < X.den); // will also throw if precomputePrecision is larger than the array length in getDenominator Fraction.Fraction128 memory Xtemp = X.copy(); if (Xtemp.num == 0) { // e^0 = 1 return ONE(); } Fraction.Fraction128 memory result = ONE(); uint256 d = 1; // 2^i for (uint256 i = 1; i <= precomputePrecision; i++) { d *= 2; // if Fraction > 1/d, subtract 1/d and multiply result by precomputed e^(1/d) if (d.mul(Xtemp.num) >= Xtemp.den) { Xtemp = Xtemp.sub1Over(uint128(d)); result = result.mul(getPrecomputedEToTheHalfToThe(i)); } } return result.mul(expMaclaurin(Xtemp, maclaurinPrecision)); } /** * Returns e^X for any X, using Maclaurin Series approximation * * e^X = SUM(X^n / n!) for n >= 0 * e^X = 1 + X/1! + X^2/2! + X^3/3! ... * * @param X Exponent * @param precision Accuracy of Maclaurin terms * @return e^X */ function expMaclaurin( Fraction.Fraction128 memory X, uint256 precision ) internal pure returns (Fraction.Fraction128 memory) { Fraction.Fraction128 memory Xcopy = X.copy(); if (Xcopy.num == 0) { // e^0 = 1 return ONE(); } Fraction.Fraction128 memory result = ONE(); Fraction.Fraction128 memory Xtemp = ONE(); for (uint256 i = 1; i <= precision; i++) { Xtemp = Xtemp.mul(Xcopy.div(uint128(i))); result = result.add(Xtemp); } return result; } /** * Returns a fraction roughly equaling E^((1/2)^x) for integer x */ function getPrecomputedEToTheHalfToThe( uint256 x ) internal pure returns (Fraction.Fraction128 memory) { assert(x <= MAX_PRECOMPUTE_PRECISION); uint128 denominator = [ 125182886983370532117250726298150828301, 206391688497133195273760705512282642279, 265012173823417992016237332255925138361, 300298134811882980317033350418940119802, 319665700530617779809390163992561606014, 329812979126047300897653247035862915816, 335006777809430963166468914297166288162, 337634268532609249517744113622081347950, 338955731696479810470146282672867036734, 339618401537809365075354109784799900812, 339950222128463181389559457827561204959, 340116253979683015278260491021941090650, 340199300311581465057079429423749235412, 340240831081268226777032180141478221816, 340261598367316729254995498374473399540, 340271982485676106947851156443492415142, 340277174663693808406010255284800906112, 340279770782412691177936847400746725466, 340281068849199706686796915841848278311, 340281717884450116236033378667952410919, 340282042402539547492367191008339680733, 340282204661700319870089970029119685699, 340282285791309720262481214385569134454, 340282326356121674011576912006427792656, 340282346638529464274601981200276914173, 340282356779733812753265346086924801364, 340282361850336100329388676752133324799, 340282364385637272451648746721404212564, 340282365653287865596328444437856608255, 340282366287113163939555716675618384724, 340282366604025813553891209601455838559, 340282366762482138471739420386372790954, 340282366841710300958333641874363209044 ][x]; return Fraction.Fraction128({ num: MAX_NUMERATOR, den: denominator }); } /** * Returns a fraction roughly equaling E^(x) for integer x */ function getPrecomputedEToThe( uint256 x ) internal pure returns (Fraction.Fraction128 memory) { assert(x <= NUM_PRECOMPUTED_INTEGERS); uint128 denominator = [ 340282366920938463463374607431768211455, 125182886983370532117250726298150828301, 46052210507670172419625860892627118820, 16941661466271327126146327822211253888, 6232488952727653950957829210887653621, 2292804553036637136093891217529878878, 843475657686456657683449904934172134, 310297353591408453462393329342695980, 114152017036184782947077973323212575, 41994180235864621538772677139808695, 15448795557622704876497742989562086, 5683294276510101335127414470015662, 2090767122455392675095471286328463, 769150240628514374138961856925097, 282954560699298259527814398449860, 104093165666968799599694528310221, 38293735615330848145349245349513, 14087478058534870382224480725096, 5182493555688763339001418388912, 1906532833141383353974257736699, 701374233231058797338605168652, 258021160973090761055471434334, 94920680509187392077350434438, 34919366901332874995585576427, 12846117181722897538509298435, 4725822410035083116489797150, 1738532907279185132707372378, 639570514388029575350057932, 235284843422800231081973821, 86556456714490055457751527, 31842340925906738090071268, 11714142585413118080082437, 4309392228124372433711936 ][x]; return Fraction.Fraction128({ num: MAX_NUMERATOR, den: denominator }); } // ============ Private Helper-Functions ============ function ONE() private pure returns (Fraction.Fraction128 memory) { return Fraction.Fraction128({ num: 1, den: 1 }); } } // File: contracts/lib/MathHelpers.sol /** * @title MathHelpers * @author dYdX * * This library helps with common math functions in Solidity */ library MathHelpers { using SafeMath for uint256; /** * Calculates partial value given a numerator and denominator. * * @param numerator Numerator * @param denominator Denominator * @param target Value to calculate partial of * @return target * numerator / denominator */ function getPartialAmount( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256) { return numerator.mul(target).div(denominator); } /** * Calculates partial value given a numerator and denominator, rounded up. * * @param numerator Numerator * @param denominator Denominator * @param target Value to calculate partial of * @return Rounded-up result of target * numerator / denominator */ function getPartialAmountRoundedUp( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256) { return divisionRoundedUp(numerator.mul(target), denominator); } /** * Calculates division given a numerator and denominator, rounded up. * * @param numerator Numerator. * @param denominator Denominator. * @return Rounded-up result of numerator / denominator */ function divisionRoundedUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { assert(denominator != 0); // coverage-enable-line if (numerator == 0) { return 0; } return numerator.sub(1).div(denominator).add(1); } /** * Calculates and returns the maximum value for a uint256 in solidity * * @return The maximum value for uint256 */ function maxUint256( ) internal pure returns (uint256) { return 2 ** 256 - 1; } /** * Calculates and returns the maximum value for a uint256 in solidity * * @return The maximum value for uint256 */ function maxUint32( ) internal pure returns (uint32) { return 2 ** 32 - 1; } /** * Returns the number of bits in a uint256. That is, the lowest number, x, such that n >> x == 0 * * @param n The uint256 to get the number of bits in * @return The number of bits in n */ function getNumBits( uint256 n ) internal pure returns (uint256) { uint256 first = 0; uint256 last = 256; while (first < last) { uint256 check = (first + last) / 2; if ((n >> check) == 0) { last = check; } else { first = check + 1; } } assert(first <= 256); return first; } } // File: contracts/margin/impl/InterestImpl.sol /** * @title InterestImpl * @author dYdX * * A library that calculates continuously compounded interest for principal, time period, and * interest rate. */ library InterestImpl { using SafeMath for uint256; using FractionMath for Fraction.Fraction128; // ============ Constants ============ uint256 constant DEFAULT_PRECOMPUTE_PRECISION = 11; uint256 constant DEFAULT_MACLAURIN_PRECISION = 5; uint256 constant MAXIMUM_EXPONENT = 80; uint128 constant E_TO_MAXIUMUM_EXPONENT = 55406223843935100525711733958316613; // ============ Public Implementation Functions ============ /** * Returns total tokens owed after accruing interest. Continuously compounding and accurate to * roughly 10^18 decimal places. Continuously compounding interest follows the formula: * I = P * e^(R*T) * * @param principal Principal of the interest calculation * @param interestRate Annual nominal interest percentage times 10**6. * (example: 5% = 5e6) * @param secondsOfInterest Number of seconds that interest has been accruing * @return Total amount of tokens owed. Greater than tokenAmount. */ function getCompoundedInterest( uint256 principal, uint256 interestRate, uint256 secondsOfInterest ) public pure returns (uint256) { uint256 numerator = interestRate.mul(secondsOfInterest); uint128 denominator = (10**8) * (365 * 1 days); // interestRate and secondsOfInterest should both be uint32 assert(numerator < 2**128); // fraction representing (Rate * Time) Fraction.Fraction128 memory rt = Fraction.Fraction128({ num: uint128(numerator), den: denominator }); // calculate e^(RT) Fraction.Fraction128 memory eToRT; if (numerator.div(denominator) >= MAXIMUM_EXPONENT) { // degenerate case: cap calculation eToRT = Fraction.Fraction128({ num: E_TO_MAXIUMUM_EXPONENT, den: 1 }); } else { // normal case: calculate e^(RT) eToRT = Exponent.exp( rt, DEFAULT_PRECOMPUTE_PRECISION, DEFAULT_MACLAURIN_PRECISION ); } // e^X for positive X should be greater-than or equal to 1 assert(eToRT.num >= eToRT.den); return safeMultiplyUint256ByFraction(principal, eToRT); } // ============ Private Helper-Functions ============ /** * Returns n * f, trying to prevent overflow as much as possible. Assumes that the numerator * and denominator of f are less than 2**128. */ function safeMultiplyUint256ByFraction( uint256 n, Fraction.Fraction128 memory f ) private pure returns (uint256) { uint256 term1 = n.div(2 ** 128); // first 128 bits uint256 term2 = n % (2 ** 128); // second 128 bits // uncommon scenario, requires n >= 2**128. calculates term1 = term1 * f if (term1 > 0) { term1 = term1.mul(f.num); uint256 numBits = MathHelpers.getNumBits(term1); // reduce rounding error by shifting all the way to the left before dividing term1 = MathHelpers.divisionRoundedUp( term1 << (uint256(256).sub(numBits)), f.den); // continue shifting or reduce shifting to get the right number if (numBits > 128) { term1 = term1 << (numBits.sub(128)); } else if (numBits < 128) { term1 = term1 >> (uint256(128).sub(numBits)); } } // calculates term2 = term2 * f term2 = MathHelpers.getPartialAmountRoundedUp( f.num, f.den, term2 ); return term1.add(term2); } } // File: contracts/margin/impl/MarginState.sol /** * @title MarginState * @author dYdX * * Contains state for the Margin contract. Also used by libraries that implement Margin functions. */ library MarginState { struct State { // Address of the Vault contract address VAULT; // Address of the TokenProxy contract address TOKEN_PROXY; // Mapping from loanHash -> amount, which stores the amount of a loan which has // already been filled. mapping (bytes32 => uint256) loanFills; // Mapping from loanHash -> amount, which stores the amount of a loan which has // already been canceled. mapping (bytes32 => uint256) loanCancels; // Mapping from positionId -> Position, which stores all the open margin positions. mapping (bytes32 => MarginCommon.Position) positions; // Mapping from positionId -> bool, which stores whether the position has previously been // open, but is now closed. mapping (bytes32 => bool) closedPositions; // Mapping from positionId -> uint256, which stores the total amount of owedToken that has // ever been repaid to the lender for each position. Does not reset. mapping (bytes32 => uint256) totalOwedTokenRepaidToLender; } } // File: contracts/margin/interfaces/lender/LoanOwner.sol /** * @title LoanOwner * @author dYdX * * Interface that smart contracts must implement in order to own loans on behalf of other accounts. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface LoanOwner { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive ownership of a loan sell via the * transferLoan function or the atomic-assign to the "owner" field in a loan offering. * * @param from Address of the previous owner * @param positionId Unique ID of the position * @return This address to keep ownership, a different address to pass-on ownership */ function receiveLoanOwnership( address from, bytes32 positionId ) external /* onlyMargin */ returns (address); } // File: contracts/margin/interfaces/owner/PositionOwner.sol /** * @title PositionOwner * @author dYdX * * Interface that smart contracts must implement in order to own position on behalf of other * accounts * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface PositionOwner { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive ownership of a position via the * transferPosition function or the atomic-assign to the "owner" field when opening a position. * * @param from Address of the previous owner * @param positionId Unique ID of the position * @return This address to keep ownership, a different address to pass-on ownership */ function receivePositionOwnership( address from, bytes32 positionId ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/TransferInternal.sol /** * @title TransferInternal * @author dYdX * * This library contains the implementation for transferring ownership of loans and positions. */ library TransferInternal { // ============ Events ============ /** * Ownership of a loan was transferred to a new address */ event LoanTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); /** * Ownership of a postion was transferred to a new address */ event PositionTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); // ============ Internal Implementation Functions ============ /** * Returns either the address of the new loan owner, or the address to which they wish to * pass ownership of the loan. This function does not actually set the state of the position * * @param positionId The Unique ID of the position * @param oldOwner The previous owner of the loan * @param newOwner The intended owner of the loan * @return The address that the intended owner wishes to assign the loan to (may be * the same as the intended owner). */ function grantLoanOwnership( bytes32 positionId, address oldOwner, address newOwner ) internal returns (address) { // log event except upon position creation if (oldOwner != address(0)) { emit LoanTransferred(positionId, oldOwner, newOwner); } if (AddressUtils.isContract(newOwner)) { address nextOwner = LoanOwner(newOwner).receiveLoanOwnership(oldOwner, positionId); if (nextOwner != newOwner) { return grantLoanOwnership(positionId, newOwner, nextOwner); } } require( newOwner != address(0), "TransferInternal#grantLoanOwnership: New owner did not consent to owning loan" ); return newOwner; } /** * Returns either the address of the new position owner, or the address to which they wish to * pass ownership of the position. This function does not actually set the state of the position * * @param positionId The Unique ID of the position * @param oldOwner The previous owner of the position * @param newOwner The intended owner of the position * @return The address that the intended owner wishes to assign the position to (may * be the same as the intended owner). */ function grantPositionOwnership( bytes32 positionId, address oldOwner, address newOwner ) internal returns (address) { // log event except upon position creation if (oldOwner != address(0)) { emit PositionTransferred(positionId, oldOwner, newOwner); } if (AddressUtils.isContract(newOwner)) { address nextOwner = PositionOwner(newOwner).receivePositionOwnership(oldOwner, positionId); if (nextOwner != newOwner) { return grantPositionOwnership(positionId, newOwner, nextOwner); } } require( newOwner != address(0), "TransferInternal#grantPositionOwnership: New owner did not consent to owning position" ); return newOwner; } } // File: contracts/lib/TimestampHelper.sol /** * @title TimestampHelper * @author dYdX * * Helper to get block timestamps in other formats */ library TimestampHelper { function getBlockTimestamp32() internal view returns (uint32) { // Should not still be in-use in the year 2106 assert(uint256(uint32(block.timestamp)) == block.timestamp); assert(block.timestamp > 0); return uint32(block.timestamp); } } // File: contracts/margin/impl/MarginCommon.sol /** * @title MarginCommon * @author dYdX * * This library contains common functions for implementations of public facing Margin functions */ library MarginCommon { using SafeMath for uint256; // ============ Structs ============ struct Position { address owedToken; // Immutable address heldToken; // Immutable address lender; address owner; uint256 principal; uint256 requiredDeposit; uint32 callTimeLimit; // Immutable uint32 startTimestamp; // Immutable, cannot be 0 uint32 callTimestamp; uint32 maxDuration; // Immutable uint32 interestRate; // Immutable uint32 interestPeriod; // Immutable } struct LoanOffering { address owedToken; address heldToken; address payer; address owner; address taker; address positionOwner; address feeRecipient; address lenderFeeToken; address takerFeeToken; LoanRates rates; uint256 expirationTimestamp; uint32 callTimeLimit; uint32 maxDuration; uint256 salt; bytes32 loanHash; bytes signature; } struct LoanRates { uint256 maxAmount; uint256 minAmount; uint256 minHeldToken; uint256 lenderFee; uint256 takerFee; uint32 interestRate; uint32 interestPeriod; } // ============ Internal Implementation Functions ============ function storeNewPosition( MarginState.State storage state, bytes32 positionId, Position memory position, address loanPayer ) internal { assert(!positionHasExisted(state, positionId)); assert(position.owedToken != address(0)); assert(position.heldToken != address(0)); assert(position.owedToken != position.heldToken); assert(position.owner != address(0)); assert(position.lender != address(0)); assert(position.maxDuration != 0); assert(position.interestPeriod <= position.maxDuration); assert(position.callTimestamp == 0); assert(position.requiredDeposit == 0); state.positions[positionId].owedToken = position.owedToken; state.positions[positionId].heldToken = position.heldToken; state.positions[positionId].principal = position.principal; state.positions[positionId].callTimeLimit = position.callTimeLimit; state.positions[positionId].startTimestamp = TimestampHelper.getBlockTimestamp32(); state.positions[positionId].maxDuration = position.maxDuration; state.positions[positionId].interestRate = position.interestRate; state.positions[positionId].interestPeriod = position.interestPeriod; state.positions[positionId].owner = TransferInternal.grantPositionOwnership( positionId, (position.owner != msg.sender) ? msg.sender : address(0), position.owner ); state.positions[positionId].lender = TransferInternal.grantLoanOwnership( positionId, (position.lender != loanPayer) ? loanPayer : address(0), position.lender ); } function getPositionIdFromNonce( uint256 nonce ) internal view returns (bytes32) { return keccak256(abi.encodePacked(msg.sender, nonce)); } function getUnavailableLoanOfferingAmountImpl( MarginState.State storage state, bytes32 loanHash ) internal view returns (uint256) { return state.loanFills[loanHash].add(state.loanCancels[loanHash]); } function cleanupPosition( MarginState.State storage state, bytes32 positionId ) internal { delete state.positions[positionId]; state.closedPositions[positionId] = true; } function calculateOwedAmount( Position storage position, uint256 closeAmount, uint256 endTimestamp ) internal view returns (uint256) { uint256 timeElapsed = calculateEffectiveTimeElapsed(position, endTimestamp); return InterestImpl.getCompoundedInterest( closeAmount, position.interestRate, timeElapsed ); } /** * Calculates time elapsed rounded up to the nearest interestPeriod */ function calculateEffectiveTimeElapsed( Position storage position, uint256 timestamp ) internal view returns (uint256) { uint256 elapsed = timestamp.sub(position.startTimestamp); // round up to interestPeriod uint256 period = position.interestPeriod; if (period > 1) { elapsed = MathHelpers.divisionRoundedUp(elapsed, period).mul(period); } // bound by maxDuration return Math.min256( elapsed, position.maxDuration ); } function calculateLenderAmountForIncreasePosition( Position storage position, uint256 principalToAdd, uint256 endTimestamp ) internal view returns (uint256) { uint256 timeElapsed = calculateEffectiveTimeElapsedForNewLender(position, endTimestamp); return InterestImpl.getCompoundedInterest( principalToAdd, position.interestRate, timeElapsed ); } function getLoanOfferingHash( LoanOffering loanOffering ) internal view returns (bytes32) { return keccak256( abi.encodePacked( address(this), loanOffering.owedToken, loanOffering.heldToken, loanOffering.payer, loanOffering.owner, loanOffering.taker, loanOffering.positionOwner, loanOffering.feeRecipient, loanOffering.lenderFeeToken, loanOffering.takerFeeToken, getValuesHash(loanOffering) ) ); } function getPositionBalanceImpl( MarginState.State storage state, bytes32 positionId ) internal view returns(uint256) { return Vault(state.VAULT).balances(positionId, state.positions[positionId].heldToken); } function containsPositionImpl( MarginState.State storage state, bytes32 positionId ) internal view returns (bool) { return state.positions[positionId].startTimestamp != 0; } function positionHasExisted( MarginState.State storage state, bytes32 positionId ) internal view returns (bool) { return containsPositionImpl(state, positionId) || state.closedPositions[positionId]; } function getPositionFromStorage( MarginState.State storage state, bytes32 positionId ) internal view returns (Position storage) { Position storage position = state.positions[positionId]; require( position.startTimestamp != 0, "MarginCommon#getPositionFromStorage: The position does not exist" ); return position; } // ============ Private Helper-Functions ============ /** * Calculates time elapsed rounded down to the nearest interestPeriod */ function calculateEffectiveTimeElapsedForNewLender( Position storage position, uint256 timestamp ) private view returns (uint256) { uint256 elapsed = timestamp.sub(position.startTimestamp); // round down to interestPeriod uint256 period = position.interestPeriod; if (period > 1) { elapsed = elapsed.div(period).mul(period); } // bound by maxDuration return Math.min256( elapsed, position.maxDuration ); } function getValuesHash( LoanOffering loanOffering ) private pure returns (bytes32) { return keccak256( abi.encodePacked( loanOffering.rates.maxAmount, loanOffering.rates.minAmount, loanOffering.rates.minHeldToken, loanOffering.rates.lenderFee, loanOffering.rates.takerFee, loanOffering.expirationTimestamp, loanOffering.salt, loanOffering.callTimeLimit, loanOffering.maxDuration, loanOffering.rates.interestRate, loanOffering.rates.interestPeriod ) ); } } // File: contracts/margin/interfaces/PayoutRecipient.sol /** * @title PayoutRecipient * @author dYdX * * Interface that smart contracts must implement in order to be the payoutRecipient in a * closePosition transaction. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface PayoutRecipient { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive payout from being the payoutRecipient * in a closePosition transaction. May redistribute any payout as necessary. Throws on error. * * @param positionId Unique ID of the position * @param closeAmount Amount of the position that was closed * @param closer Address of the account or contract that closed the position * @param positionOwner Address of the owner of the position * @param heldToken Address of the ERC20 heldToken * @param payout Number of tokens received from the payout * @param totalHeldToken Total amount of heldToken removed from vault during close * @param payoutInHeldToken True if payout is in heldToken, false if in owedToken * @return True if approved by the receiver */ function receiveClosePositionPayout( bytes32 positionId, uint256 closeAmount, address closer, address positionOwner, address heldToken, uint256 payout, uint256 totalHeldToken, bool payoutInHeldToken ) external /* onlyMargin */ returns (bool); } // File: contracts/margin/interfaces/lender/CloseLoanDelegator.sol /** * @title CloseLoanDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses close a loan * owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface CloseLoanDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call * closeWithoutCounterparty(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that (at most) the specified amount of the loan was * successfully closed. * * @param closer Address of the caller of closeWithoutCounterparty() * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param positionId Unique ID of the position * @param requestedAmount Requested principal amount of the loan to close * @return 1) This address to accept, a different address to ask that contract * 2) The maximum amount that this contract is allowing */ function closeLoanOnBehalfOf( address closer, address payoutRecipient, bytes32 positionId, uint256 requestedAmount ) external /* onlyMargin */ returns (address, uint256); } // File: contracts/margin/interfaces/owner/ClosePositionDelegator.sol /** * @title ClosePositionDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses close a position * owned by the smart contract, allowing more complex logic to control positions. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface ClosePositionDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call closePosition(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that (at-most) the specified amount of the position * was successfully closed. * * @param closer Address of the caller of the closePosition() function * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param positionId Unique ID of the position * @param requestedAmount Requested principal amount of the position to close * @return 1) This address to accept, a different address to ask that contract * 2) The maximum amount that this contract is allowing */ function closeOnBehalfOf( address closer, address payoutRecipient, bytes32 positionId, uint256 requestedAmount ) external /* onlyMargin */ returns (address, uint256); } // File: contracts/margin/impl/ClosePositionShared.sol /** * @title ClosePositionShared * @author dYdX * * This library contains shared functionality between ClosePositionImpl and * CloseWithoutCounterpartyImpl */ library ClosePositionShared { using SafeMath for uint256; // ============ Structs ============ struct CloseTx { bytes32 positionId; uint256 originalPrincipal; uint256 closeAmount; uint256 owedTokenOwed; uint256 startingHeldTokenBalance; uint256 availableHeldToken; address payoutRecipient; address owedToken; address heldToken; address positionOwner; address positionLender; address exchangeWrapper; bool payoutInHeldToken; } // ============ Internal Implementation Functions ============ function closePositionStateUpdate( MarginState.State storage state, CloseTx memory transaction ) internal { // Delete the position, or just decrease the principal if (transaction.closeAmount == transaction.originalPrincipal) { MarginCommon.cleanupPosition(state, transaction.positionId); } else { assert( transaction.originalPrincipal == state.positions[transaction.positionId].principal ); state.positions[transaction.positionId].principal = transaction.originalPrincipal.sub(transaction.closeAmount); } } function sendTokensToPayoutRecipient( MarginState.State storage state, ClosePositionShared.CloseTx memory transaction, uint256 buybackCostInHeldToken, uint256 receivedOwedToken ) internal returns (uint256) { uint256 payout; if (transaction.payoutInHeldToken) { // Send remaining heldToken to payoutRecipient payout = transaction.availableHeldToken.sub(buybackCostInHeldToken); Vault(state.VAULT).transferFromVault( transaction.positionId, transaction.heldToken, transaction.payoutRecipient, payout ); } else { assert(transaction.exchangeWrapper != address(0)); payout = receivedOwedToken.sub(transaction.owedTokenOwed); TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, transaction.exchangeWrapper, transaction.payoutRecipient, payout ); } if (AddressUtils.isContract(transaction.payoutRecipient)) { require( PayoutRecipient(transaction.payoutRecipient).receiveClosePositionPayout( transaction.positionId, transaction.closeAmount, msg.sender, transaction.positionOwner, transaction.heldToken, payout, transaction.availableHeldToken, transaction.payoutInHeldToken ), "ClosePositionShared#sendTokensToPayoutRecipient: Payout recipient does not consent" ); } // The ending heldToken balance of the vault should be the starting heldToken balance // minus the available heldToken amount assert( MarginCommon.getPositionBalanceImpl(state, transaction.positionId) == transaction.startingHeldTokenBalance.sub(transaction.availableHeldToken) ); return payout; } function createCloseTx( MarginState.State storage state, bytes32 positionId, uint256 requestedAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bool isWithoutCounterparty ) internal returns (CloseTx memory) { // Validate require( payoutRecipient != address(0), "ClosePositionShared#createCloseTx: Payout recipient cannot be 0" ); require( requestedAmount > 0, "ClosePositionShared#createCloseTx: Requested close amount cannot be 0" ); MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); uint256 closeAmount = getApprovedAmount( position, positionId, requestedAmount, payoutRecipient, isWithoutCounterparty ); return parseCloseTx( state, position, positionId, closeAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, isWithoutCounterparty ); } // ============ Private Helper-Functions ============ function getApprovedAmount( MarginCommon.Position storage position, bytes32 positionId, uint256 requestedAmount, address payoutRecipient, bool requireLenderApproval ) private returns (uint256) { // Ensure enough principal uint256 allowedAmount = Math.min256(requestedAmount, position.principal); // Ensure owner consent allowedAmount = closePositionOnBehalfOfRecurse( position.owner, msg.sender, payoutRecipient, positionId, allowedAmount ); // Ensure lender consent if (requireLenderApproval) { allowedAmount = closeLoanOnBehalfOfRecurse( position.lender, msg.sender, payoutRecipient, positionId, allowedAmount ); } assert(allowedAmount > 0); assert(allowedAmount <= position.principal); assert(allowedAmount <= requestedAmount); return allowedAmount; } function closePositionOnBehalfOfRecurse( address contractAddr, address closer, address payoutRecipient, bytes32 positionId, uint256 closeAmount ) private returns (uint256) { // no need to ask for permission if (closer == contractAddr) { return closeAmount; } ( address newContractAddr, uint256 newCloseAmount ) = ClosePositionDelegator(contractAddr).closeOnBehalfOf( closer, payoutRecipient, positionId, closeAmount ); require( newCloseAmount <= closeAmount, "ClosePositionShared#closePositionRecurse: newCloseAmount is greater than closeAmount" ); require( newCloseAmount > 0, "ClosePositionShared#closePositionRecurse: newCloseAmount is zero" ); if (newContractAddr != contractAddr) { closePositionOnBehalfOfRecurse( newContractAddr, closer, payoutRecipient, positionId, newCloseAmount ); } return newCloseAmount; } function closeLoanOnBehalfOfRecurse( address contractAddr, address closer, address payoutRecipient, bytes32 positionId, uint256 closeAmount ) private returns (uint256) { // no need to ask for permission if (closer == contractAddr) { return closeAmount; } ( address newContractAddr, uint256 newCloseAmount ) = CloseLoanDelegator(contractAddr).closeLoanOnBehalfOf( closer, payoutRecipient, positionId, closeAmount ); require( newCloseAmount <= closeAmount, "ClosePositionShared#closeLoanRecurse: newCloseAmount is greater than closeAmount" ); require( newCloseAmount > 0, "ClosePositionShared#closeLoanRecurse: newCloseAmount is zero" ); if (newContractAddr != contractAddr) { closeLoanOnBehalfOfRecurse( newContractAddr, closer, payoutRecipient, positionId, newCloseAmount ); } return newCloseAmount; } // ============ Parsing Functions ============ function parseCloseTx( MarginState.State storage state, MarginCommon.Position storage position, bytes32 positionId, uint256 closeAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bool isWithoutCounterparty ) private view returns (CloseTx memory) { uint256 startingHeldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId); uint256 availableHeldToken = MathHelpers.getPartialAmount( closeAmount, position.principal, startingHeldTokenBalance ); uint256 owedTokenOwed = 0; if (!isWithoutCounterparty) { owedTokenOwed = MarginCommon.calculateOwedAmount( position, closeAmount, block.timestamp ); } return CloseTx({ positionId: positionId, originalPrincipal: position.principal, closeAmount: closeAmount, owedTokenOwed: owedTokenOwed, startingHeldTokenBalance: startingHeldTokenBalance, availableHeldToken: availableHeldToken, payoutRecipient: payoutRecipient, owedToken: position.owedToken, heldToken: position.heldToken, positionOwner: position.owner, positionLender: position.lender, exchangeWrapper: exchangeWrapper, payoutInHeldToken: payoutInHeldToken }); } } // File: contracts/margin/interfaces/ExchangeWrapper.sol /** * @title ExchangeWrapper * @author dYdX * * Contract interface that Exchange Wrapper smart contracts must implement in order to interface * with other smart contracts through a common interface. */ interface ExchangeWrapper { // ============ Public Functions ============ /** * Exchange some amount of takerToken for makerToken. * * @param tradeOriginator Address of the initiator of the trade (however, this value * cannot always be trusted as it is set at the discretion of the * msg.sender) * @param receiver Address to set allowance on once the trade has completed * @param makerToken Address of makerToken, the token to receive * @param takerToken Address of takerToken, the token to pay * @param requestedFillAmount Amount of takerToken being paid * @param orderData Arbitrary bytes data for any information to pass to the exchange * @return The amount of makerToken received */ function exchange( address tradeOriginator, address receiver, address makerToken, address takerToken, uint256 requestedFillAmount, bytes orderData ) external returns (uint256); /** * Get amount of takerToken required to buy a certain amount of makerToken for a given trade. * Should match the takerToken amount used in exchangeForAmount. If the order cannot provide * exactly desiredMakerToken, then it must return the price to buy the minimum amount greater * than desiredMakerToken * * @param makerToken Address of makerToken, the token to receive * @param takerToken Address of takerToken, the token to pay * @param desiredMakerToken Amount of makerToken requested * @param orderData Arbitrary bytes data for any information to pass to the exchange * @return Amount of takerToken the needed to complete the transaction */ function getExchangeCost( address makerToken, address takerToken, uint256 desiredMakerToken, bytes orderData ) external view returns (uint256); } // File: contracts/margin/impl/ClosePositionImpl.sol /** * @title ClosePositionImpl * @author dYdX * * This library contains the implementation for the closePosition function of Margin */ library ClosePositionImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); // ============ Public Implementation Functions ============ function closePositionImpl( MarginState.State storage state, bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bytes memory orderData ) public returns (uint256, uint256, uint256) { ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx( state, positionId, requestedCloseAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, false ); ( uint256 buybackCostInHeldToken, uint256 receivedOwedToken ) = returnOwedTokensToLender( state, transaction, orderData ); uint256 payout = ClosePositionShared.sendTokensToPayoutRecipient( state, transaction, buybackCostInHeldToken, receivedOwedToken ); ClosePositionShared.closePositionStateUpdate(state, transaction); logEventOnClose( transaction, buybackCostInHeldToken, payout ); return ( transaction.closeAmount, payout, transaction.owedTokenOwed ); } // ============ Private Helper-Functions ============ function returnOwedTokensToLender( MarginState.State storage state, ClosePositionShared.CloseTx memory transaction, bytes memory orderData ) private returns (uint256, uint256) { uint256 buybackCostInHeldToken = 0; uint256 receivedOwedToken = 0; uint256 lenderOwedToken = transaction.owedTokenOwed; // Setting exchangeWrapper to 0x000... indicates owedToken should be taken directly // from msg.sender if (transaction.exchangeWrapper == address(0)) { require( transaction.payoutInHeldToken, "ClosePositionImpl#returnOwedTokensToLender: Cannot payout in owedToken" ); // No DEX Order; send owedTokens directly from the closer to the lender TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, msg.sender, transaction.positionLender, lenderOwedToken ); } else { // Buy back owedTokens using DEX Order and send to lender (buybackCostInHeldToken, receivedOwedToken) = buyBackOwedToken( state, transaction, orderData ); // If no owedToken needed for payout: give lender all owedToken, even if more than owed if (transaction.payoutInHeldToken) { assert(receivedOwedToken >= lenderOwedToken); lenderOwedToken = receivedOwedToken; } // Transfer owedToken from the exchange wrapper to the lender TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, transaction.exchangeWrapper, transaction.positionLender, lenderOwedToken ); } state.totalOwedTokenRepaidToLender[transaction.positionId] = state.totalOwedTokenRepaidToLender[transaction.positionId].add(lenderOwedToken); return (buybackCostInHeldToken, receivedOwedToken); } function buyBackOwedToken( MarginState.State storage state, ClosePositionShared.CloseTx transaction, bytes memory orderData ) private returns (uint256, uint256) { // Ask the exchange wrapper the cost in heldToken to buy back the close // amount of owedToken uint256 buybackCostInHeldToken; if (transaction.payoutInHeldToken) { buybackCostInHeldToken = ExchangeWrapper(transaction.exchangeWrapper) .getExchangeCost( transaction.owedToken, transaction.heldToken, transaction.owedTokenOwed, orderData ); // Require enough available heldToken to pay for the buyback require( buybackCostInHeldToken <= transaction.availableHeldToken, "ClosePositionImpl#buyBackOwedToken: Not enough available heldToken" ); } else { buybackCostInHeldToken = transaction.availableHeldToken; } // Send the requisite heldToken to do the buyback from vault to exchange wrapper Vault(state.VAULT).transferFromVault( transaction.positionId, transaction.heldToken, transaction.exchangeWrapper, buybackCostInHeldToken ); // Trade the heldToken for the owedToken uint256 receivedOwedToken = ExchangeWrapper(transaction.exchangeWrapper).exchange( msg.sender, state.TOKEN_PROXY, transaction.owedToken, transaction.heldToken, buybackCostInHeldToken, orderData ); require( receivedOwedToken >= transaction.owedTokenOwed, "ClosePositionImpl#buyBackOwedToken: Did not receive enough owedToken" ); return (buybackCostInHeldToken, receivedOwedToken); } function logEventOnClose( ClosePositionShared.CloseTx transaction, uint256 buybackCostInHeldToken, uint256 payout ) private { emit PositionClosed( transaction.positionId, msg.sender, transaction.payoutRecipient, transaction.closeAmount, transaction.originalPrincipal.sub(transaction.closeAmount), transaction.owedTokenOwed, payout, buybackCostInHeldToken, transaction.payoutInHeldToken ); } } // File: contracts/margin/impl/CloseWithoutCounterpartyImpl.sol /** * @title CloseWithoutCounterpartyImpl * @author dYdX * * This library contains the implementation for the closeWithoutCounterpartyImpl function of * Margin */ library CloseWithoutCounterpartyImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); // ============ Public Implementation Functions ============ function closeWithoutCounterpartyImpl( MarginState.State storage state, bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) public returns (uint256, uint256) { ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx( state, positionId, requestedCloseAmount, payoutRecipient, address(0), true, true ); uint256 heldTokenPayout = ClosePositionShared.sendTokensToPayoutRecipient( state, transaction, 0, // No buyback cost 0 // Did not receive any owedToken ); ClosePositionShared.closePositionStateUpdate(state, transaction); logEventOnCloseWithoutCounterparty(transaction); return ( transaction.closeAmount, heldTokenPayout ); } // ============ Private Helper-Functions ============ function logEventOnCloseWithoutCounterparty( ClosePositionShared.CloseTx transaction ) private { emit PositionClosed( transaction.positionId, msg.sender, transaction.payoutRecipient, transaction.closeAmount, transaction.originalPrincipal.sub(transaction.closeAmount), 0, transaction.availableHeldToken, 0, true ); } } // File: contracts/margin/interfaces/owner/DepositCollateralDelegator.sol /** * @title DepositCollateralDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses deposit heldTokens * into a position owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface DepositCollateralDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call depositCollateral(). * * @param depositor Address of the caller of the depositCollateral() function * @param positionId Unique ID of the position * @param amount Requested deposit amount * @return This address to accept, a different address to ask that contract */ function depositCollateralOnBehalfOf( address depositor, bytes32 positionId, uint256 amount ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/DepositCollateralImpl.sol /** * @title DepositCollateralImpl * @author dYdX * * This library contains the implementation for the deposit function of Margin */ library DepositCollateralImpl { using SafeMath for uint256; // ============ Events ============ /** * Additional collateral for a position was posted by the owner */ event AdditionalCollateralDeposited( bytes32 indexed positionId, uint256 amount, address depositor ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); // ============ Public Implementation Functions ============ function depositCollateralImpl( MarginState.State storage state, bytes32 positionId, uint256 depositAmount ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( depositAmount > 0, "DepositCollateralImpl#depositCollateralImpl: Deposit amount cannot be 0" ); // Ensure owner consent depositCollateralOnBehalfOfRecurse( position.owner, msg.sender, positionId, depositAmount ); Vault(state.VAULT).transferToVault( positionId, position.heldToken, msg.sender, depositAmount ); // cancel margin call if applicable bool marginCallCanceled = false; uint256 requiredDeposit = position.requiredDeposit; if (position.callTimestamp > 0 && requiredDeposit > 0) { if (depositAmount >= requiredDeposit) { position.requiredDeposit = 0; position.callTimestamp = 0; marginCallCanceled = true; } else { position.requiredDeposit = position.requiredDeposit.sub(depositAmount); } } emit AdditionalCollateralDeposited( positionId, depositAmount, msg.sender ); if (marginCallCanceled) { emit MarginCallCanceled( positionId, position.lender, msg.sender, depositAmount ); } } // ============ Private Helper-Functions ============ function depositCollateralOnBehalfOfRecurse( address contractAddr, address depositor, bytes32 positionId, uint256 amount ) private { // no need to ask for permission if (depositor == contractAddr) { return; } address newContractAddr = DepositCollateralDelegator(contractAddr).depositCollateralOnBehalfOf( depositor, positionId, amount ); // if not equal, recurse if (newContractAddr != contractAddr) { depositCollateralOnBehalfOfRecurse( newContractAddr, depositor, positionId, amount ); } } } // File: contracts/margin/interfaces/lender/ForceRecoverCollateralDelegator.sol /** * @title ForceRecoverCollateralDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses * forceRecoverCollateral() a loan owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface ForceRecoverCollateralDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call * forceRecoverCollateral(). * * NOTE: If not returning zero address (or not reverting), this contract must assume that Margin * will either revert the entire transaction or that the collateral was forcibly recovered. * * @param recoverer Address of the caller of the forceRecoverCollateral() function * @param positionId Unique ID of the position * @param recipient Address to send the recovered tokens to * @return This address to accept, a different address to ask that contract */ function forceRecoverCollateralOnBehalfOf( address recoverer, bytes32 positionId, address recipient ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/ForceRecoverCollateralImpl.sol /** * @title ForceRecoverCollateralImpl * @author dYdX * * This library contains the implementation for the forceRecoverCollateral function of Margin */ library ForceRecoverCollateralImpl { using SafeMath for uint256; // ============ Events ============ /** * Collateral for a position was forcibly recovered */ event CollateralForceRecovered( bytes32 indexed positionId, address indexed recipient, uint256 amount ); // ============ Public Implementation Functions ============ function forceRecoverCollateralImpl( MarginState.State storage state, bytes32 positionId, address recipient ) public returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); // Can only force recover after either: // 1) The loan was called and the call period has elapsed // 2) The maxDuration of the position has elapsed require( /* solium-disable-next-line */ ( position.callTimestamp > 0 && block.timestamp >= uint256(position.callTimestamp).add(position.callTimeLimit) ) || ( block.timestamp >= uint256(position.startTimestamp).add(position.maxDuration) ), "ForceRecoverCollateralImpl#forceRecoverCollateralImpl: Cannot recover yet" ); // Ensure lender consent forceRecoverCollateralOnBehalfOfRecurse( position.lender, msg.sender, positionId, recipient ); // Send the tokens uint256 heldTokenRecovered = MarginCommon.getPositionBalanceImpl(state, positionId); Vault(state.VAULT).transferFromVault( positionId, position.heldToken, recipient, heldTokenRecovered ); // Delete the position // NOTE: Since position is a storage pointer, this will also set all fields on // the position variable to 0 MarginCommon.cleanupPosition( state, positionId ); // Log an event emit CollateralForceRecovered( positionId, recipient, heldTokenRecovered ); return heldTokenRecovered; } // ============ Private Helper-Functions ============ function forceRecoverCollateralOnBehalfOfRecurse( address contractAddr, address recoverer, bytes32 positionId, address recipient ) private { // no need to ask for permission if (recoverer == contractAddr) { return; } address newContractAddr = ForceRecoverCollateralDelegator(contractAddr).forceRecoverCollateralOnBehalfOf( recoverer, positionId, recipient ); if (newContractAddr != contractAddr) { forceRecoverCollateralOnBehalfOfRecurse( newContractAddr, recoverer, positionId, recipient ); } } } // File: contracts/lib/TypedSignature.sol /** * @title TypedSignature * @author dYdX * * Allows for ecrecovery of signed hashes with three different prepended messages: * 1) "" * 2) "\x19Ethereum Signed Message:\n32" * 3) "\x19Ethereum Signed Message:\n\x20" */ library TypedSignature { // Solidity does not offer guarantees about enum values, so we define them explicitly uint8 private constant SIGTYPE_INVALID = 0; uint8 private constant SIGTYPE_ECRECOVER_DEC = 1; uint8 private constant SIGTYPE_ECRECOVER_HEX = 2; uint8 private constant SIGTYPE_UNSUPPORTED = 3; // prepended message with the length of the signed hash in hexadecimal bytes constant private PREPEND_HEX = "\x19Ethereum Signed Message:\n\x20"; // prepended message with the length of the signed hash in decimal bytes constant private PREPEND_DEC = "\x19Ethereum Signed Message:\n32"; /** * Gives the address of the signer of a hash. Allows for three common prepended strings. * * @param hash Hash that was signed (does not include prepended message) * @param signatureWithType Type and ECDSA signature with structure: {1:type}{1:v}{32:r}{32:s} * @return address of the signer of the hash */ function recover( bytes32 hash, bytes signatureWithType ) internal pure returns (address) { require( signatureWithType.length == 66, "SignatureValidator#validateSignature: invalid signature length" ); uint8 sigType = uint8(signatureWithType[0]); require( sigType > uint8(SIGTYPE_INVALID), "SignatureValidator#validateSignature: invalid signature type" ); require( sigType < uint8(SIGTYPE_UNSUPPORTED), "SignatureValidator#validateSignature: unsupported signature type" ); uint8 v = uint8(signatureWithType[1]); bytes32 r; bytes32 s; /* solium-disable-next-line security/no-inline-assembly */ assembly { r := mload(add(signatureWithType, 34)) s := mload(add(signatureWithType, 66)) } bytes32 signedHash; if (sigType == SIGTYPE_ECRECOVER_DEC) { signedHash = keccak256(abi.encodePacked(PREPEND_DEC, hash)); } else { assert(sigType == SIGTYPE_ECRECOVER_HEX); signedHash = keccak256(abi.encodePacked(PREPEND_HEX, hash)); } return ecrecover( signedHash, v, r, s ); } } // File: contracts/margin/interfaces/LoanOfferingVerifier.sol /** * @title LoanOfferingVerifier * @author dYdX * * Interface that smart contracts must implement to be able to make off-chain generated * loan offerings. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface LoanOfferingVerifier { /** * Function a smart contract must implement to be able to consent to a loan. The loan offering * will be generated off-chain. The "loan owner" address will own the loan-side of the resulting * position. * * If true is returned, and no errors are thrown by the Margin contract, the loan will have * occurred. This means that verifyLoanOffering can also be used to update internal contract * state on a loan. * * @param addresses Array of addresses: * * [0] = owedToken * [1] = heldToken * [2] = loan payer * [3] = loan owner * [4] = loan taker * [5] = loan positionOwner * [6] = loan fee recipient * [7] = loan lender fee token * [8] = loan taker fee token * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param positionId Unique ID of the position * @param signature Arbitrary bytes; may or may not be an ECDSA signature * @return This address to accept, a different address to ask that contract */ function verifyLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/BorrowShared.sol /** * @title BorrowShared * @author dYdX * * This library contains shared functionality between OpenPositionImpl and IncreasePositionImpl. * Both use a Loan Offering and a DEX Order to open or increase a position. */ library BorrowShared { using SafeMath for uint256; // ============ Structs ============ struct Tx { bytes32 positionId; address owner; uint256 principal; uint256 lenderAmount; MarginCommon.LoanOffering loanOffering; address exchangeWrapper; bool depositInHeldToken; uint256 depositAmount; uint256 collateralAmount; uint256 heldTokenFromSell; } // ============ Internal Implementation Functions ============ /** * Validate the transaction before exchanging heldToken for owedToken */ function validateTxPreSell( MarginState.State storage state, Tx memory transaction ) internal { assert(transaction.lenderAmount >= transaction.principal); require( transaction.principal > 0, "BorrowShared#validateTxPreSell: Positions with 0 principal are not allowed" ); // If the taker is 0x0 then any address can take it. Otherwise only the taker can use it. if (transaction.loanOffering.taker != address(0)) { require( msg.sender == transaction.loanOffering.taker, "BorrowShared#validateTxPreSell: Invalid loan offering taker" ); } // If the positionOwner is 0x0 then any address can be set as the position owner. // Otherwise only the specified positionOwner can be set as the position owner. if (transaction.loanOffering.positionOwner != address(0)) { require( transaction.owner == transaction.loanOffering.positionOwner, "BorrowShared#validateTxPreSell: Invalid position owner" ); } // Require the loan offering to be approved by the payer if (AddressUtils.isContract(transaction.loanOffering.payer)) { getConsentFromSmartContractLender(transaction); } else { require( transaction.loanOffering.payer == TypedSignature.recover( transaction.loanOffering.loanHash, transaction.loanOffering.signature ), "BorrowShared#validateTxPreSell: Invalid loan offering signature" ); } // Validate the amount is <= than max and >= min uint256 unavailable = MarginCommon.getUnavailableLoanOfferingAmountImpl( state, transaction.loanOffering.loanHash ); require( transaction.lenderAmount.add(unavailable) <= transaction.loanOffering.rates.maxAmount, "BorrowShared#validateTxPreSell: Loan offering does not have enough available" ); require( transaction.lenderAmount >= transaction.loanOffering.rates.minAmount, "BorrowShared#validateTxPreSell: Lender amount is below loan offering minimum amount" ); require( transaction.loanOffering.owedToken != transaction.loanOffering.heldToken, "BorrowShared#validateTxPreSell: owedToken cannot be equal to heldToken" ); require( transaction.owner != address(0), "BorrowShared#validateTxPreSell: Position owner cannot be 0" ); require( transaction.loanOffering.owner != address(0), "BorrowShared#validateTxPreSell: Loan owner cannot be 0" ); require( transaction.loanOffering.expirationTimestamp > block.timestamp, "BorrowShared#validateTxPreSell: Loan offering is expired" ); require( transaction.loanOffering.maxDuration > 0, "BorrowShared#validateTxPreSell: Loan offering has 0 maximum duration" ); require( transaction.loanOffering.rates.interestPeriod <= transaction.loanOffering.maxDuration, "BorrowShared#validateTxPreSell: Loan offering interestPeriod > maxDuration" ); // The minimum heldToken is validated after executing the sell // Position and loan ownership is validated in TransferInternal } /** * Validate the transaction after exchanging heldToken for owedToken, pay out fees, and store * how much of the loan was used. */ function doPostSell( MarginState.State storage state, Tx memory transaction ) internal { validateTxPostSell(transaction); // Transfer feeTokens from trader and lender transferLoanFees(state, transaction); // Update global amounts for the loan state.loanFills[transaction.loanOffering.loanHash] = state.loanFills[transaction.loanOffering.loanHash].add(transaction.lenderAmount); } /** * Sells the owedToken from the lender (and from the deposit if in owedToken) using the * exchangeWrapper, then puts the resulting heldToken into the vault. Only trades for * maxHeldTokenToBuy of heldTokens at most. */ function doSell( MarginState.State storage state, Tx transaction, bytes orderData, uint256 maxHeldTokenToBuy ) internal returns (uint256) { // Move owedTokens from lender to exchange wrapper pullOwedTokensFromLender(state, transaction); // Sell just the lender's owedToken (if trader deposit is in heldToken) // Otherwise sell both the lender's owedToken and the trader's deposit in owedToken uint256 sellAmount = transaction.depositInHeldToken ? transaction.lenderAmount : transaction.lenderAmount.add(transaction.depositAmount); // Do the trade, taking only the maxHeldTokenToBuy if more is returned uint256 heldTokenFromSell = Math.min256( maxHeldTokenToBuy, ExchangeWrapper(transaction.exchangeWrapper).exchange( msg.sender, state.TOKEN_PROXY, transaction.loanOffering.heldToken, transaction.loanOffering.owedToken, sellAmount, orderData ) ); // Move the tokens to the vault Vault(state.VAULT).transferToVault( transaction.positionId, transaction.loanOffering.heldToken, transaction.exchangeWrapper, heldTokenFromSell ); // Update collateral amount transaction.collateralAmount = transaction.collateralAmount.add(heldTokenFromSell); return heldTokenFromSell; } /** * Take the owedToken deposit from the trader and give it to the exchange wrapper so that it can * be sold for heldToken. */ function doDepositOwedToken( MarginState.State storage state, Tx transaction ) internal { TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.loanOffering.owedToken, msg.sender, transaction.exchangeWrapper, transaction.depositAmount ); } /** * Take the heldToken deposit from the trader and move it to the vault. */ function doDepositHeldToken( MarginState.State storage state, Tx transaction ) internal { Vault(state.VAULT).transferToVault( transaction.positionId, transaction.loanOffering.heldToken, msg.sender, transaction.depositAmount ); // Update collateral amount transaction.collateralAmount = transaction.collateralAmount.add(transaction.depositAmount); } // ============ Private Helper-Functions ============ function validateTxPostSell( Tx transaction ) private pure { uint256 expectedCollateral = transaction.depositInHeldToken ? transaction.heldTokenFromSell.add(transaction.depositAmount) : transaction.heldTokenFromSell; assert(transaction.collateralAmount == expectedCollateral); uint256 loanOfferingMinimumHeldToken = MathHelpers.getPartialAmountRoundedUp( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.minHeldToken ); require( transaction.collateralAmount >= loanOfferingMinimumHeldToken, "BorrowShared#validateTxPostSell: Loan offering minimum held token not met" ); } function getConsentFromSmartContractLender( Tx transaction ) private { verifyLoanOfferingRecurse( transaction.loanOffering.payer, getLoanOfferingAddresses(transaction), getLoanOfferingValues256(transaction), getLoanOfferingValues32(transaction), transaction.positionId, transaction.loanOffering.signature ); } function verifyLoanOfferingRecurse( address contractAddr, address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) private { address newContractAddr = LoanOfferingVerifier(contractAddr).verifyLoanOffering( addresses, values256, values32, positionId, signature ); if (newContractAddr != contractAddr) { verifyLoanOfferingRecurse( newContractAddr, addresses, values256, values32, positionId, signature ); } } function pullOwedTokensFromLender( MarginState.State storage state, Tx transaction ) private { // Transfer owedToken to the exchange wrapper TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.loanOffering.owedToken, transaction.loanOffering.payer, transaction.exchangeWrapper, transaction.lenderAmount ); } function transferLoanFees( MarginState.State storage state, Tx transaction ) private { // 0 fee address indicates no fees if (transaction.loanOffering.feeRecipient == address(0)) { return; } TokenProxy proxy = TokenProxy(state.TOKEN_PROXY); uint256 lenderFee = MathHelpers.getPartialAmount( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.lenderFee ); uint256 takerFee = MathHelpers.getPartialAmount( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.takerFee ); if (lenderFee > 0) { proxy.transferTokens( transaction.loanOffering.lenderFeeToken, transaction.loanOffering.payer, transaction.loanOffering.feeRecipient, lenderFee ); } if (takerFee > 0) { proxy.transferTokens( transaction.loanOffering.takerFeeToken, msg.sender, transaction.loanOffering.feeRecipient, takerFee ); } } function getLoanOfferingAddresses( Tx transaction ) private pure returns (address[9]) { return [ transaction.loanOffering.owedToken, transaction.loanOffering.heldToken, transaction.loanOffering.payer, transaction.loanOffering.owner, transaction.loanOffering.taker, transaction.loanOffering.positionOwner, transaction.loanOffering.feeRecipient, transaction.loanOffering.lenderFeeToken, transaction.loanOffering.takerFeeToken ]; } function getLoanOfferingValues256( Tx transaction ) private pure returns (uint256[7]) { return [ transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.minAmount, transaction.loanOffering.rates.minHeldToken, transaction.loanOffering.rates.lenderFee, transaction.loanOffering.rates.takerFee, transaction.loanOffering.expirationTimestamp, transaction.loanOffering.salt ]; } function getLoanOfferingValues32( Tx transaction ) private pure returns (uint32[4]) { return [ transaction.loanOffering.callTimeLimit, transaction.loanOffering.maxDuration, transaction.loanOffering.rates.interestRate, transaction.loanOffering.rates.interestPeriod ]; } } // File: contracts/margin/interfaces/lender/IncreaseLoanDelegator.sol /** * @title IncreaseLoanDelegator * @author dYdX * * Interface that smart contracts must implement in order to own loans on behalf of other accounts. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface IncreaseLoanDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to allow additional value to be added onto * an owned loan. Margin will call this on the owner of a loan during increasePosition(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the loan size was successfully increased. * * @param payer Lender adding additional funds to the position * @param positionId Unique ID of the position * @param principalAdded Principal amount to be added to the position * @param lentAmount Amount of owedToken lent by the lender (principal plus interest, or * zero if increaseWithoutCounterparty() is used). * @return This address to accept, a different address to ask that contract */ function increaseLoanOnBehalfOf( address payer, bytes32 positionId, uint256 principalAdded, uint256 lentAmount ) external /* onlyMargin */ returns (address); } // File: contracts/margin/interfaces/owner/IncreasePositionDelegator.sol /** * @title IncreasePositionDelegator * @author dYdX * * Interface that smart contracts must implement in order to own position on behalf of other * accounts * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface IncreasePositionDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to allow additional value to be added onto * an owned position. Margin will call this on the owner of a position during increasePosition() * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the position size was successfully increased. * * @param trader Address initiating the addition of funds to the position * @param positionId Unique ID of the position * @param principalAdded Amount of principal to be added to the position * @return This address to accept, a different address to ask that contract */ function increasePositionOnBehalfOf( address trader, bytes32 positionId, uint256 principalAdded ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/IncreasePositionImpl.sol /** * @title IncreasePositionImpl * @author dYdX * * This library contains the implementation for the increasePosition function of Margin */ library IncreasePositionImpl { using SafeMath for uint256; // ============ Events ============ /* * A position was increased */ event PositionIncreased( bytes32 indexed positionId, address indexed trader, address indexed lender, address positionOwner, address loanOwner, bytes32 loanHash, address loanFeeRecipient, uint256 amountBorrowed, uint256 principalAdded, uint256 heldTokenFromSell, uint256 depositAmount, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function increasePositionImpl( MarginState.State storage state, bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature, bytes orderData ) public returns (uint256) { // Also ensures that the position exists MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); BorrowShared.Tx memory transaction = parseIncreasePositionTx( position, positionId, addresses, values256, values32, depositInHeldToken, signature ); validateIncrease(state, transaction, position); doBorrowAndSell(state, transaction, orderData); updateState( position, transaction.positionId, transaction.principal, transaction.lenderAmount, transaction.loanOffering.payer ); // LOG EVENT recordPositionIncreased(transaction, position); return transaction.lenderAmount; } function increaseWithoutCounterpartyImpl( MarginState.State storage state, bytes32 positionId, uint256 principalToAdd ) public returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); // Disallow adding 0 principal require( principalToAdd > 0, "IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot add 0 principal" ); // Disallow additions after maximum duration require( block.timestamp < uint256(position.startTimestamp).add(position.maxDuration), "IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot increase after maxDuration" ); uint256 heldTokenAmount = getCollateralNeededForAddedPrincipal( state, position, positionId, principalToAdd ); Vault(state.VAULT).transferToVault( positionId, position.heldToken, msg.sender, heldTokenAmount ); updateState( position, positionId, principalToAdd, 0, // lent amount msg.sender ); emit PositionIncreased( positionId, msg.sender, msg.sender, position.owner, position.lender, "", address(0), 0, principalToAdd, 0, heldTokenAmount, true ); return heldTokenAmount; } // ============ Private Helper-Functions ============ function doBorrowAndSell( MarginState.State storage state, BorrowShared.Tx memory transaction, bytes orderData ) private { // Calculate the number of heldTokens to add uint256 collateralToAdd = getCollateralNeededForAddedPrincipal( state, state.positions[transaction.positionId], transaction.positionId, transaction.principal ); // Do pre-exchange validations BorrowShared.validateTxPreSell(state, transaction); // Calculate and deposit owedToken uint256 maxHeldTokenFromSell = MathHelpers.maxUint256(); if (!transaction.depositInHeldToken) { transaction.depositAmount = getOwedTokenDeposit(transaction, collateralToAdd, orderData); BorrowShared.doDepositOwedToken(state, transaction); maxHeldTokenFromSell = collateralToAdd; } // Sell owedToken for heldToken using the exchange wrapper transaction.heldTokenFromSell = BorrowShared.doSell( state, transaction, orderData, maxHeldTokenFromSell ); // Calculate and deposit heldToken if (transaction.depositInHeldToken) { require( transaction.heldTokenFromSell <= collateralToAdd, "IncreasePositionImpl#doBorrowAndSell: DEX order gives too much heldToken" ); transaction.depositAmount = collateralToAdd.sub(transaction.heldTokenFromSell); BorrowShared.doDepositHeldToken(state, transaction); } // Make sure the actual added collateral is what is expected assert(transaction.collateralAmount == collateralToAdd); // Do post-exchange validations BorrowShared.doPostSell(state, transaction); } function getOwedTokenDeposit( BorrowShared.Tx transaction, uint256 collateralToAdd, bytes orderData ) private view returns (uint256) { uint256 totalOwedToken = ExchangeWrapper(transaction.exchangeWrapper).getExchangeCost( transaction.loanOffering.heldToken, transaction.loanOffering.owedToken, collateralToAdd, orderData ); require( transaction.lenderAmount <= totalOwedToken, "IncreasePositionImpl#getOwedTokenDeposit: Lender amount is more than required" ); return totalOwedToken.sub(transaction.lenderAmount); } function validateIncrease( MarginState.State storage state, BorrowShared.Tx transaction, MarginCommon.Position storage position ) private view { assert(MarginCommon.containsPositionImpl(state, transaction.positionId)); require( position.callTimeLimit <= transaction.loanOffering.callTimeLimit, "IncreasePositionImpl#validateIncrease: Loan callTimeLimit is less than the position" ); // require the position to end no later than the loanOffering's maximum acceptable end time uint256 positionEndTimestamp = uint256(position.startTimestamp).add(position.maxDuration); uint256 offeringEndTimestamp = block.timestamp.add(transaction.loanOffering.maxDuration); require( positionEndTimestamp <= offeringEndTimestamp, "IncreasePositionImpl#validateIncrease: Loan end timestamp is less than the position" ); require( block.timestamp < positionEndTimestamp, "IncreasePositionImpl#validateIncrease: Position has passed its maximum duration" ); } function getCollateralNeededForAddedPrincipal( MarginState.State storage state, MarginCommon.Position storage position, bytes32 positionId, uint256 principalToAdd ) private view returns (uint256) { uint256 heldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId); return MathHelpers.getPartialAmountRoundedUp( principalToAdd, position.principal, heldTokenBalance ); } function updateState( MarginCommon.Position storage position, bytes32 positionId, uint256 principalAdded, uint256 owedTokenLent, address loanPayer ) private { position.principal = position.principal.add(principalAdded); address owner = position.owner; address lender = position.lender; // Ensure owner consent increasePositionOnBehalfOfRecurse( owner, msg.sender, positionId, principalAdded ); // Ensure lender consent increaseLoanOnBehalfOfRecurse( lender, loanPayer, positionId, principalAdded, owedTokenLent ); } function increasePositionOnBehalfOfRecurse( address contractAddr, address trader, bytes32 positionId, uint256 principalAdded ) private { // Assume owner approval if not a smart contract and they increased their own position if (trader == contractAddr && !AddressUtils.isContract(contractAddr)) { return; } address newContractAddr = IncreasePositionDelegator(contractAddr).increasePositionOnBehalfOf( trader, positionId, principalAdded ); if (newContractAddr != contractAddr) { increasePositionOnBehalfOfRecurse( newContractAddr, trader, positionId, principalAdded ); } } function increaseLoanOnBehalfOfRecurse( address contractAddr, address payer, bytes32 positionId, uint256 principalAdded, uint256 amountLent ) private { // Assume lender approval if not a smart contract and they increased their own loan if (payer == contractAddr && !AddressUtils.isContract(contractAddr)) { return; } address newContractAddr = IncreaseLoanDelegator(contractAddr).increaseLoanOnBehalfOf( payer, positionId, principalAdded, amountLent ); if (newContractAddr != contractAddr) { increaseLoanOnBehalfOfRecurse( newContractAddr, payer, positionId, principalAdded, amountLent ); } } function recordPositionIncreased( BorrowShared.Tx transaction, MarginCommon.Position storage position ) private { emit PositionIncreased( transaction.positionId, msg.sender, transaction.loanOffering.payer, position.owner, position.lender, transaction.loanOffering.loanHash, transaction.loanOffering.feeRecipient, transaction.lenderAmount, transaction.principal, transaction.heldTokenFromSell, transaction.depositAmount, transaction.depositInHeldToken ); } // ============ Parsing Functions ============ function parseIncreasePositionTx( MarginCommon.Position storage position, bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature ) private view returns (BorrowShared.Tx memory) { uint256 principal = values256[7]; uint256 lenderAmount = MarginCommon.calculateLenderAmountForIncreasePosition( position, principal, block.timestamp ); assert(lenderAmount >= principal); BorrowShared.Tx memory transaction = BorrowShared.Tx({ positionId: positionId, owner: position.owner, principal: principal, lenderAmount: lenderAmount, loanOffering: parseLoanOfferingFromIncreasePositionTx( position, addresses, values256, values32, signature ), exchangeWrapper: addresses[6], depositInHeldToken: depositInHeldToken, depositAmount: 0, // set later collateralAmount: 0, // set later heldTokenFromSell: 0 // set later }); return transaction; } function parseLoanOfferingFromIncreasePositionTx( MarginCommon.Position storage position, address[7] addresses, uint256[8] values256, uint32[2] values32, bytes signature ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: position.owedToken, heldToken: position.heldToken, payer: addresses[0], owner: position.lender, taker: addresses[1], positionOwner: addresses[2], feeRecipient: addresses[3], lenderFeeToken: addresses[4], takerFeeToken: addresses[5], rates: parseLoanOfferingRatesFromIncreasePositionTx(position, values256), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: signature }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferingRatesFromIncreasePositionTx( MarginCommon.Position storage position, uint256[8] values256 ) private view returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], lenderFee: values256[3], takerFee: values256[4], interestRate: position.interestRate, interestPeriod: position.interestPeriod }); return rates; } } // File: contracts/margin/impl/MarginStorage.sol /** * @title MarginStorage * @author dYdX * * This contract serves as the storage for the entire state of MarginStorage */ contract MarginStorage { MarginState.State state; } // File: contracts/margin/impl/LoanGetters.sol /** * @title LoanGetters * @author dYdX * * A collection of public constant getter functions that allows reading of the state of any loan * offering stored in the dYdX protocol. */ contract LoanGetters is MarginStorage { // ============ Public Constant Functions ============ /** * Gets the principal amount of a loan offering that is no longer available. * * @param loanHash Unique hash of the loan offering * @return The total unavailable amount of the loan offering, which is equal to the * filled amount plus the canceled amount. */ function getLoanUnavailableAmount( bytes32 loanHash ) external view returns (uint256) { return MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanHash); } /** * Gets the total amount of owed token lent for a loan. * * @param loanHash Unique hash of the loan offering * @return The total filled amount of the loan offering. */ function getLoanFilledAmount( bytes32 loanHash ) external view returns (uint256) { return state.loanFills[loanHash]; } /** * Gets the amount of a loan offering that has been canceled. * * @param loanHash Unique hash of the loan offering * @return The total canceled amount of the loan offering. */ function getLoanCanceledAmount( bytes32 loanHash ) external view returns (uint256) { return state.loanCancels[loanHash]; } } // File: contracts/margin/interfaces/lender/CancelMarginCallDelegator.sol /** * @title CancelMarginCallDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses cancel a * margin-call for a loan owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface CancelMarginCallDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call cancelMarginCall(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the margin-call was successfully canceled. * * @param canceler Address of the caller of the cancelMarginCall function * @param positionId Unique ID of the position * @return This address to accept, a different address to ask that contract */ function cancelMarginCallOnBehalfOf( address canceler, bytes32 positionId ) external /* onlyMargin */ returns (address); } // File: contracts/margin/interfaces/lender/MarginCallDelegator.sol /** * @title MarginCallDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses margin-call a loan * owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface MarginCallDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call marginCall(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the loan was successfully margin-called. * * @param caller Address of the caller of the marginCall function * @param positionId Unique ID of the position * @param depositAmount Amount of heldToken deposit that will be required to cancel the call * @return This address to accept, a different address to ask that contract */ function marginCallOnBehalfOf( address caller, bytes32 positionId, uint256 depositAmount ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/LoanImpl.sol /** * @title LoanImpl * @author dYdX * * This library contains the implementation for the following functions of Margin: * * - marginCall * - cancelMarginCallImpl * - cancelLoanOffering */ library LoanImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was margin-called */ event MarginCallInitiated( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 requiredDeposit ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); /** * A loan offering was canceled before it was used. Any amount less than the * total for the loan offering can be canceled. */ event LoanOfferingCanceled( bytes32 indexed loanHash, address indexed payer, address indexed feeRecipient, uint256 cancelAmount ); // ============ Public Implementation Functions ============ function marginCallImpl( MarginState.State storage state, bytes32 positionId, uint256 requiredDeposit ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( position.callTimestamp == 0, "LoanImpl#marginCallImpl: The position has already been margin-called" ); // Ensure lender consent marginCallOnBehalfOfRecurse( position.lender, msg.sender, positionId, requiredDeposit ); position.callTimestamp = TimestampHelper.getBlockTimestamp32(); position.requiredDeposit = requiredDeposit; emit MarginCallInitiated( positionId, position.lender, position.owner, requiredDeposit ); } function cancelMarginCallImpl( MarginState.State storage state, bytes32 positionId ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( position.callTimestamp > 0, "LoanImpl#cancelMarginCallImpl: Position has not been margin-called" ); // Ensure lender consent cancelMarginCallOnBehalfOfRecurse( position.lender, msg.sender, positionId ); state.positions[positionId].callTimestamp = 0; state.positions[positionId].requiredDeposit = 0; emit MarginCallCanceled( positionId, position.lender, position.owner, 0 ); } function cancelLoanOfferingImpl( MarginState.State storage state, address[9] addresses, uint256[7] values256, uint32[4] values32, uint256 cancelAmount ) public returns (uint256) { MarginCommon.LoanOffering memory loanOffering = parseLoanOffering( addresses, values256, values32 ); require( msg.sender == loanOffering.payer, "LoanImpl#cancelLoanOfferingImpl: Only loan offering payer can cancel" ); require( loanOffering.expirationTimestamp > block.timestamp, "LoanImpl#cancelLoanOfferingImpl: Loan offering has already expired" ); uint256 remainingAmount = loanOffering.rates.maxAmount.sub( MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanOffering.loanHash) ); uint256 amountToCancel = Math.min256(remainingAmount, cancelAmount); // If the loan was already fully canceled, then just return 0 amount was canceled if (amountToCancel == 0) { return 0; } state.loanCancels[loanOffering.loanHash] = state.loanCancels[loanOffering.loanHash].add(amountToCancel); emit LoanOfferingCanceled( loanOffering.loanHash, loanOffering.payer, loanOffering.feeRecipient, amountToCancel ); return amountToCancel; } // ============ Private Helper-Functions ============ function marginCallOnBehalfOfRecurse( address contractAddr, address who, bytes32 positionId, uint256 requiredDeposit ) private { // no need to ask for permission if (who == contractAddr) { return; } address newContractAddr = MarginCallDelegator(contractAddr).marginCallOnBehalfOf( msg.sender, positionId, requiredDeposit ); if (newContractAddr != contractAddr) { marginCallOnBehalfOfRecurse( newContractAddr, who, positionId, requiredDeposit ); } } function cancelMarginCallOnBehalfOfRecurse( address contractAddr, address who, bytes32 positionId ) private { // no need to ask for permission if (who == contractAddr) { return; } address newContractAddr = CancelMarginCallDelegator(contractAddr).cancelMarginCallOnBehalfOf( msg.sender, positionId ); if (newContractAddr != contractAddr) { cancelMarginCallOnBehalfOfRecurse( newContractAddr, who, positionId ); } } // ============ Parsing Functions ============ function parseLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32 ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: addresses[0], heldToken: addresses[1], payer: addresses[2], owner: addresses[3], taker: addresses[4], positionOwner: addresses[5], feeRecipient: addresses[6], lenderFeeToken: addresses[7], takerFeeToken: addresses[8], rates: parseLoanOfferRates(values256, values32), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: new bytes(0) }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferRates( uint256[7] values256, uint32[4] values32 ) private pure returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], interestRate: values32[2], lenderFee: values256[3], takerFee: values256[4], interestPeriod: values32[3] }); return rates; } } // File: contracts/margin/impl/MarginAdmin.sol /** * @title MarginAdmin * @author dYdX * * Contains admin functions for the Margin contract * The owner can put Margin into various close-only modes, which will disallow new position creation */ contract MarginAdmin is Ownable { // ============ Enums ============ // All functionality enabled uint8 private constant OPERATION_STATE_OPERATIONAL = 0; // Only closing functions + cancelLoanOffering allowed (marginCall, closePosition, // cancelLoanOffering, closePositionDirectly, forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY = 1; // Only closing functions allowed (marginCall, closePosition, closePositionDirectly, // forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_ONLY = 2; // Only closing functions allowed (marginCall, closePositionDirectly, forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_DIRECTLY_ONLY = 3; // This operation state (and any higher) is invalid uint8 private constant OPERATION_STATE_INVALID = 4; // ============ Events ============ /** * Event indicating the operation state has changed */ event OperationStateChanged( uint8 from, uint8 to ); // ============ State Variables ============ uint8 public operationState; // ============ Constructor ============ constructor() public Ownable() { operationState = OPERATION_STATE_OPERATIONAL; } // ============ Modifiers ============ modifier onlyWhileOperational() { require( operationState == OPERATION_STATE_OPERATIONAL, "MarginAdmin#onlyWhileOperational: Can only call while operational" ); _; } modifier cancelLoanOfferingStateControl() { require( operationState == OPERATION_STATE_OPERATIONAL || operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY, "MarginAdmin#cancelLoanOfferingStateControl: Invalid operation state" ); _; } modifier closePositionStateControl() { require( operationState == OPERATION_STATE_OPERATIONAL || operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY || operationState == OPERATION_STATE_CLOSE_ONLY, "MarginAdmin#closePositionStateControl: Invalid operation state" ); _; } modifier closePositionDirectlyStateControl() { _; } // ============ Owner-Only State-Changing Functions ============ function setOperationState( uint8 newState ) external onlyOwner { require( newState < OPERATION_STATE_INVALID, "MarginAdmin#setOperationState: newState is not a valid operation state" ); if (newState != operationState) { emit OperationStateChanged( operationState, newState ); operationState = newState; } } } // File: contracts/margin/impl/MarginEvents.sol /** * @title MarginEvents * @author dYdX * * Contains events for the Margin contract. * * NOTE: Any Margin function libraries that use events will need to both define the event here * and copy the event into the library itself as libraries don't support sharing events */ contract MarginEvents { // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); /* * A position was increased */ event PositionIncreased( bytes32 indexed positionId, address indexed trader, address indexed lender, address positionOwner, address loanOwner, bytes32 loanHash, address loanFeeRecipient, uint256 amountBorrowed, uint256 principalAdded, uint256 heldTokenFromSell, uint256 depositAmount, bool depositInHeldToken ); /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); /** * Collateral for a position was forcibly recovered */ event CollateralForceRecovered( bytes32 indexed positionId, address indexed recipient, uint256 amount ); /** * A position was margin-called */ event MarginCallInitiated( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 requiredDeposit ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); /** * A loan offering was canceled before it was used. Any amount less than the * total for the loan offering can be canceled. */ event LoanOfferingCanceled( bytes32 indexed loanHash, address indexed payer, address indexed feeRecipient, uint256 cancelAmount ); /** * Additional collateral for a position was posted by the owner */ event AdditionalCollateralDeposited( bytes32 indexed positionId, uint256 amount, address depositor ); /** * Ownership of a loan was transferred to a new address */ event LoanTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); /** * Ownership of a position was transferred to a new address */ event PositionTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); } // File: contracts/margin/impl/OpenPositionImpl.sol /** * @title OpenPositionImpl * @author dYdX * * This library contains the implementation for the openPosition function of Margin */ library OpenPositionImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function openPositionImpl( MarginState.State storage state, address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature, bytes orderData ) public returns (bytes32) { BorrowShared.Tx memory transaction = parseOpenTx( addresses, values256, values32, depositInHeldToken, signature ); require( !MarginCommon.positionHasExisted(state, transaction.positionId), "OpenPositionImpl#openPositionImpl: positionId already exists" ); doBorrowAndSell(state, transaction, orderData); // Before doStoreNewPosition() so that PositionOpened event is before Transferred events recordPositionOpened( transaction ); doStoreNewPosition( state, transaction ); return transaction.positionId; } // ============ Private Helper-Functions ============ function doBorrowAndSell( MarginState.State storage state, BorrowShared.Tx memory transaction, bytes orderData ) private { BorrowShared.validateTxPreSell(state, transaction); if (transaction.depositInHeldToken) { BorrowShared.doDepositHeldToken(state, transaction); } else { BorrowShared.doDepositOwedToken(state, transaction); } transaction.heldTokenFromSell = BorrowShared.doSell( state, transaction, orderData, MathHelpers.maxUint256() ); BorrowShared.doPostSell(state, transaction); } function doStoreNewPosition( MarginState.State storage state, BorrowShared.Tx memory transaction ) private { MarginCommon.storeNewPosition( state, transaction.positionId, MarginCommon.Position({ owedToken: transaction.loanOffering.owedToken, heldToken: transaction.loanOffering.heldToken, lender: transaction.loanOffering.owner, owner: transaction.owner, principal: transaction.principal, requiredDeposit: 0, callTimeLimit: transaction.loanOffering.callTimeLimit, startTimestamp: 0, callTimestamp: 0, maxDuration: transaction.loanOffering.maxDuration, interestRate: transaction.loanOffering.rates.interestRate, interestPeriod: transaction.loanOffering.rates.interestPeriod }), transaction.loanOffering.payer ); } function recordPositionOpened( BorrowShared.Tx transaction ) private { emit PositionOpened( transaction.positionId, msg.sender, transaction.loanOffering.payer, transaction.loanOffering.loanHash, transaction.loanOffering.owedToken, transaction.loanOffering.heldToken, transaction.loanOffering.feeRecipient, transaction.principal, transaction.heldTokenFromSell, transaction.depositAmount, transaction.loanOffering.rates.interestRate, transaction.loanOffering.callTimeLimit, transaction.loanOffering.maxDuration, transaction.depositInHeldToken ); } // ============ Parsing Functions ============ function parseOpenTx( address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature ) private view returns (BorrowShared.Tx memory) { BorrowShared.Tx memory transaction = BorrowShared.Tx({ positionId: MarginCommon.getPositionIdFromNonce(values256[9]), owner: addresses[0], principal: values256[7], lenderAmount: values256[7], loanOffering: parseLoanOffering( addresses, values256, values32, signature ), exchangeWrapper: addresses[10], depositInHeldToken: depositInHeldToken, depositAmount: values256[8], collateralAmount: 0, // set later heldTokenFromSell: 0 // set later }); return transaction; } function parseLoanOffering( address[11] addresses, uint256[10] values256, uint32[4] values32, bytes signature ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: addresses[1], heldToken: addresses[2], payer: addresses[3], owner: addresses[4], taker: addresses[5], positionOwner: addresses[6], feeRecipient: addresses[7], lenderFeeToken: addresses[8], takerFeeToken: addresses[9], rates: parseLoanOfferRates(values256, values32), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: signature }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferRates( uint256[10] values256, uint32[4] values32 ) private pure returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], lenderFee: values256[3], takerFee: values256[4], interestRate: values32[2], interestPeriod: values32[3] }); return rates; } } // File: contracts/margin/impl/OpenWithoutCounterpartyImpl.sol /** * @title OpenWithoutCounterpartyImpl * @author dYdX * * This library contains the implementation for the openWithoutCounterparty * function of Margin */ library OpenWithoutCounterpartyImpl { // ============ Structs ============ struct Tx { bytes32 positionId; address positionOwner; address owedToken; address heldToken; address loanOwner; uint256 principal; uint256 deposit; uint32 callTimeLimit; uint32 maxDuration; uint32 interestRate; uint32 interestPeriod; } // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function openWithoutCounterpartyImpl( MarginState.State storage state, address[4] addresses, uint256[3] values256, uint32[4] values32 ) public returns (bytes32) { Tx memory openTx = parseTx( addresses, values256, values32 ); validate( state, openTx ); Vault(state.VAULT).transferToVault( openTx.positionId, openTx.heldToken, msg.sender, openTx.deposit ); recordPositionOpened( openTx ); doStoreNewPosition( state, openTx ); return openTx.positionId; } // ============ Private Helper-Functions ============ function doStoreNewPosition( MarginState.State storage state, Tx memory openTx ) private { MarginCommon.storeNewPosition( state, openTx.positionId, MarginCommon.Position({ owedToken: openTx.owedToken, heldToken: openTx.heldToken, lender: openTx.loanOwner, owner: openTx.positionOwner, principal: openTx.principal, requiredDeposit: 0, callTimeLimit: openTx.callTimeLimit, startTimestamp: 0, callTimestamp: 0, maxDuration: openTx.maxDuration, interestRate: openTx.interestRate, interestPeriod: openTx.interestPeriod }), msg.sender ); } function validate( MarginState.State storage state, Tx memory openTx ) private view { require( !MarginCommon.positionHasExisted(state, openTx.positionId), "openWithoutCounterpartyImpl#validate: positionId already exists" ); require( openTx.principal > 0, "openWithoutCounterpartyImpl#validate: principal cannot be 0" ); require( openTx.owedToken != address(0), "openWithoutCounterpartyImpl#validate: owedToken cannot be 0" ); require( openTx.owedToken != openTx.heldToken, "openWithoutCounterpartyImpl#validate: owedToken cannot be equal to heldToken" ); require( openTx.positionOwner != address(0), "openWithoutCounterpartyImpl#validate: positionOwner cannot be 0" ); require( openTx.loanOwner != address(0), "openWithoutCounterpartyImpl#validate: loanOwner cannot be 0" ); require( openTx.maxDuration > 0, "openWithoutCounterpartyImpl#validate: maxDuration cannot be 0" ); require( openTx.interestPeriod <= openTx.maxDuration, "openWithoutCounterpartyImpl#validate: interestPeriod must be <= maxDuration" ); } function recordPositionOpened( Tx memory openTx ) private { emit PositionOpened( openTx.positionId, msg.sender, msg.sender, bytes32(0), openTx.owedToken, openTx.heldToken, address(0), openTx.principal, 0, openTx.deposit, openTx.interestRate, openTx.callTimeLimit, openTx.maxDuration, true ); } // ============ Parsing Functions ============ function parseTx( address[4] addresses, uint256[3] values256, uint32[4] values32 ) private view returns (Tx memory) { Tx memory openTx = Tx({ positionId: MarginCommon.getPositionIdFromNonce(values256[2]), positionOwner: addresses[0], owedToken: addresses[1], heldToken: addresses[2], loanOwner: addresses[3], principal: values256[0], deposit: values256[1], callTimeLimit: values32[0], maxDuration: values32[1], interestRate: values32[2], interestPeriod: values32[3] }); return openTx; } } // File: contracts/margin/impl/PositionGetters.sol /** * @title PositionGetters * @author dYdX * * A collection of public constant getter functions that allows reading of the state of any position * stored in the dYdX protocol. */ contract PositionGetters is MarginStorage { using SafeMath for uint256; // ============ Public Constant Functions ============ /** * Gets if a position is currently open. * * @param positionId Unique ID of the position * @return True if the position is exists and is open */ function containsPosition( bytes32 positionId ) external view returns (bool) { return MarginCommon.containsPositionImpl(state, positionId); } /** * Gets if a position is currently margin-called. * * @param positionId Unique ID of the position * @return True if the position is margin-called */ function isPositionCalled( bytes32 positionId ) external view returns (bool) { return (state.positions[positionId].callTimestamp > 0); } /** * Gets if a position was previously open and is now closed. * * @param positionId Unique ID of the position * @return True if the position is now closed */ function isPositionClosed( bytes32 positionId ) external view returns (bool) { return state.closedPositions[positionId]; } /** * Gets the total amount of owedToken ever repaid to the lender for a position. * * @param positionId Unique ID of the position * @return Total amount of owedToken ever repaid */ function getTotalOwedTokenRepaidToLender( bytes32 positionId ) external view returns (uint256) { return state.totalOwedTokenRepaidToLender[positionId]; } /** * Gets the amount of heldToken currently locked up in Vault for a particular position. * * @param positionId Unique ID of the position * @return The amount of heldToken */ function getPositionBalance( bytes32 positionId ) external view returns (uint256) { return MarginCommon.getPositionBalanceImpl(state, positionId); } /** * Gets the time until the interest fee charged for the position will increase. * Returns 1 if the interest fee increases every second. * Returns 0 if the interest fee will never increase again. * * @param positionId Unique ID of the position * @return The number of seconds until the interest fee will increase */ function getTimeUntilInterestIncrease( bytes32 positionId ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); uint256 effectiveTimeElapsed = MarginCommon.calculateEffectiveTimeElapsed( position, block.timestamp ); uint256 absoluteTimeElapsed = block.timestamp.sub(position.startTimestamp); if (absoluteTimeElapsed > effectiveTimeElapsed) { // past maxDuration return 0; } else { // nextStep is the final second at which the calculated interest fee is the same as it // is currently, so add 1 to get the correct value return effectiveTimeElapsed.add(1).sub(absoluteTimeElapsed); } } /** * Gets the amount of owedTokens currently needed to close the position completely, including * interest fees. * * @param positionId Unique ID of the position * @return The number of owedTokens */ function getPositionOwedAmount( bytes32 positionId ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); return MarginCommon.calculateOwedAmount( position, position.principal, block.timestamp ); } /** * Gets the amount of owedTokens needed to close a given principal amount of the position at a * given time, including interest fees. * * @param positionId Unique ID of the position * @param principalToClose Amount of principal being closed * @param timestamp Block timestamp in seconds of close * @return The number of owedTokens owed */ function getPositionOwedAmountAtTime( bytes32 positionId, uint256 principalToClose, uint32 timestamp ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( timestamp >= position.startTimestamp, "PositionGetters#getPositionOwedAmountAtTime: Requested time before position started" ); return MarginCommon.calculateOwedAmount( position, principalToClose, timestamp ); } /** * Gets the amount of owedTokens that can be borrowed from a lender to add a given principal * amount to the position at a given time. * * @param positionId Unique ID of the position * @param principalToAdd Amount being added to principal * @param timestamp Block timestamp in seconds of addition * @return The number of owedTokens that will be borrowed */ function getLenderAmountForIncreasePositionAtTime( bytes32 positionId, uint256 principalToAdd, uint32 timestamp ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( timestamp >= position.startTimestamp, "PositionGetters#getLenderAmountForIncreasePositionAtTime: timestamp < position start" ); return MarginCommon.calculateLenderAmountForIncreasePosition( position, principalToAdd, timestamp ); } // ============ All Properties ============ /** * Get a Position by id. This does not validate the position exists. If the position does not * exist, all 0's will be returned. * * @param positionId Unique ID of the position * @return Addresses corresponding to: * * [0] = owedToken * [1] = heldToken * [2] = lender * [3] = owner * * Values corresponding to: * * [0] = principal * [1] = requiredDeposit * * Values corresponding to: * * [0] = callTimeLimit * [1] = startTimestamp * [2] = callTimestamp * [3] = maxDuration * [4] = interestRate * [5] = interestPeriod */ function getPosition( bytes32 positionId ) external view returns ( address[4], uint256[2], uint32[6] ) { MarginCommon.Position storage position = state.positions[positionId]; return ( [ position.owedToken, position.heldToken, position.lender, position.owner ], [ position.principal, position.requiredDeposit ], [ position.callTimeLimit, position.startTimestamp, position.callTimestamp, position.maxDuration, position.interestRate, position.interestPeriod ] ); } // ============ Individual Properties ============ function getPositionLender( bytes32 positionId ) external view returns (address) { return state.positions[positionId].lender; } function getPositionOwner( bytes32 positionId ) external view returns (address) { return state.positions[positionId].owner; } function getPositionHeldToken( bytes32 positionId ) external view returns (address) { return state.positions[positionId].heldToken; } function getPositionOwedToken( bytes32 positionId ) external view returns (address) { return state.positions[positionId].owedToken; } function getPositionPrincipal( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].principal; } function getPositionInterestRate( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].interestRate; } function getPositionRequiredDeposit( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].requiredDeposit; } function getPositionStartTimestamp( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].startTimestamp; } function getPositionCallTimestamp( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].callTimestamp; } function getPositionCallTimeLimit( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].callTimeLimit; } function getPositionMaxDuration( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].maxDuration; } function getPositioninterestPeriod( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].interestPeriod; } } // File: contracts/margin/impl/TransferImpl.sol /** * @title TransferImpl * @author dYdX * * This library contains the implementation for the transferPosition and transferLoan functions of * Margin */ library TransferImpl { // ============ Public Implementation Functions ============ function transferLoanImpl( MarginState.State storage state, bytes32 positionId, address newLender ) public { require( MarginCommon.containsPositionImpl(state, positionId), "TransferImpl#transferLoanImpl: Position does not exist" ); address originalLender = state.positions[positionId].lender; require( msg.sender == originalLender, "TransferImpl#transferLoanImpl: Only lender can transfer ownership" ); require( newLender != originalLender, "TransferImpl#transferLoanImpl: Cannot transfer ownership to self" ); // Doesn't change the state of positionId; figures out the final owner of loan. // That is, newLender may pass ownership to a different address. address finalLender = TransferInternal.grantLoanOwnership( positionId, originalLender, newLender); require( finalLender != originalLender, "TransferImpl#transferLoanImpl: Cannot ultimately transfer ownership to self" ); // Set state only after resolving the new owner (to reduce the number of storage calls) state.positions[positionId].lender = finalLender; } function transferPositionImpl( MarginState.State storage state, bytes32 positionId, address newOwner ) public { require( MarginCommon.containsPositionImpl(state, positionId), "TransferImpl#transferPositionImpl: Position does not exist" ); address originalOwner = state.positions[positionId].owner; require( msg.sender == originalOwner, "TransferImpl#transferPositionImpl: Only position owner can transfer ownership" ); require( newOwner != originalOwner, "TransferImpl#transferPositionImpl: Cannot transfer ownership to self" ); // Doesn't change the state of positionId; figures out the final owner of position. // That is, newOwner may pass ownership to a different address. address finalOwner = TransferInternal.grantPositionOwnership( positionId, originalOwner, newOwner); require( finalOwner != originalOwner, "TransferImpl#transferPositionImpl: Cannot ultimately transfer ownership to self" ); // Set state only after resolving the new owner (to reduce the number of storage calls) state.positions[positionId].owner = finalOwner; } } // File: contracts/margin/Margin.sol /** * @title Margin * @author dYdX * * This contract is used to facilitate margin trading as per the dYdX protocol */ contract Margin is ReentrancyGuard, MarginStorage, MarginEvents, MarginAdmin, LoanGetters, PositionGetters { using SafeMath for uint256; // ============ Constructor ============ constructor( address vault, address proxy ) public MarginAdmin() { state = MarginState.State({ VAULT: vault, TOKEN_PROXY: proxy }); } // ============ Public State Changing Functions ============ /** * Open a margin position. Called by the margin trader who must provide both a * signed loan offering as well as a DEX Order with which to sell the owedToken. * * @param addresses Addresses corresponding to: * * [0] = position owner * [1] = owedToken * [2] = heldToken * [3] = loan payer * [4] = loan owner * [5] = loan taker * [6] = loan position owner * [7] = loan fee recipient * [8] = loan lender fee token * [9] = loan taker fee token * [10] = exchange wrapper address * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * [7] = position amount of principal * [8] = deposit amount * [9] = nonce (used to calculate positionId) * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken. * False if the margin deposit will be in owedToken * and then sold along with the owedToken borrowed from the lender * @param signature If loan payer is an account, then this must be the tightly-packed * ECDSA V/R/S parameters from signing the loan hash. If loan payer * is a smart contract, these are arbitrary bytes that the contract * will recieve when choosing whether to approve the loan. * @param order Order object to be passed to the exchange wrapper * @return Unique ID for the new position */ function openPosition( address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature, bytes order ) external onlyWhileOperational nonReentrant returns (bytes32) { return OpenPositionImpl.openPositionImpl( state, addresses, values256, values32, depositInHeldToken, signature, order ); } /** * Open a margin position without a counterparty. The caller will serve as both the * lender and the position owner * * @param addresses Addresses corresponding to: * * [0] = position owner * [1] = owedToken * [2] = heldToken * [3] = loan owner * * @param values256 Values corresponding to: * * [0] = principal * [1] = deposit amount * [2] = nonce (used to calculate positionId) * * @param values32 Values corresponding to: * * [0] = call time limit (in seconds) * [1] = maxDuration (in seconds) * [2] = interest rate (annual nominal percentage times 10**6) * [3] = interest update period (in seconds) * * @return Unique ID for the new position */ function openWithoutCounterparty( address[4] addresses, uint256[3] values256, uint32[4] values32 ) external onlyWhileOperational nonReentrant returns (bytes32) { return OpenWithoutCounterpartyImpl.openWithoutCounterpartyImpl( state, addresses, values256, values32 ); } /** * Increase the size of a position. Funds will be borrowed from the loan payer and sold as per * the position. The amount of owedToken borrowed from the lender will be >= the amount of * principal added, as it will incorporate interest already earned by the position so far. * * @param positionId Unique ID of the position * @param addresses Addresses corresponding to: * * [0] = loan payer * [1] = loan taker * [2] = loan position owner * [3] = loan fee recipient * [4] = loan lender fee token * [5] = loan taker fee token * [6] = exchange wrapper address * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * [7] = amount of principal to add to the position (NOTE: the amount pulled from the lender * will be >= this amount) * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * * @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken. * False if the margin deposit will be pulled in owedToken * and then sold along with the owedToken borrowed from the lender * @param signature If loan payer is an account, then this must be the tightly-packed * ECDSA V/R/S parameters from signing the loan hash. If loan payer * is a smart contract, these are arbitrary bytes that the contract * will recieve when choosing whether to approve the loan. * @param order Order object to be passed to the exchange wrapper * @return Amount of owedTokens pulled from the lender */ function increasePosition( bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature, bytes order ) external onlyWhileOperational nonReentrant returns (uint256) { return IncreasePositionImpl.increasePositionImpl( state, positionId, addresses, values256, values32, depositInHeldToken, signature, order ); } /** * Increase a position directly by putting up heldToken. The caller will serve as both the * lender and the position owner * * @param positionId Unique ID of the position * @param principalToAdd Principal amount to add to the position * @return Amount of heldToken pulled from the msg.sender */ function increaseWithoutCounterparty( bytes32 positionId, uint256 principalToAdd ) external onlyWhileOperational nonReentrant returns (uint256) { return IncreasePositionImpl.increaseWithoutCounterpartyImpl( state, positionId, principalToAdd ); } /** * Close a position. May be called by the owner or with the approval of the owner. May provide * an order and exchangeWrapper to facilitate the closing of the position. The payoutRecipient * is sent the resulting payout. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param exchangeWrapper Address of the exchange wrapper * @param payoutInHeldToken True to pay out the payoutRecipient in heldToken, * False to pay out the payoutRecipient in owedToken * @param order Order object to be passed to the exchange wrapper * @return Values corresponding to: * 1) Principal of position closed * 2) Amount of tokens (heldToken if payoutInHeldtoken is true, * owedToken otherwise) received by the payoutRecipient * 3) Amount of owedToken paid (incl. interest fee) to the lender */ function closePosition( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bytes order ) external closePositionStateControl nonReentrant returns (uint256, uint256, uint256) { return ClosePositionImpl.closePositionImpl( state, positionId, requestedCloseAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, order ); } /** * Helper to close a position by paying owedToken directly rather than using an exchangeWrapper. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * @param payoutRecipient Address of the recipient of tokens paid out from closing * @return Values corresponding to: * 1) Principal amount of position closed * 2) Amount of heldToken received by the payoutRecipient * 3) Amount of owedToken paid (incl. interest fee) to the lender */ function closePositionDirectly( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) external closePositionDirectlyStateControl nonReentrant returns (uint256, uint256, uint256) { return ClosePositionImpl.closePositionImpl( state, positionId, requestedCloseAmount, payoutRecipient, address(0), true, new bytes(0) ); } /** * Reduce the size of a position and withdraw a proportional amount of heldToken from the vault. * Must be approved by both the position owner and lender. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * 3) The amount allowed by the lender if closer != lender * @return Values corresponding to: * 1) Principal amount of position closed * 2) Amount of heldToken received by the msg.sender */ function closeWithoutCounterparty( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) external closePositionStateControl nonReentrant returns (uint256, uint256) { return CloseWithoutCounterpartyImpl.closeWithoutCounterpartyImpl( state, positionId, requestedCloseAmount, payoutRecipient ); } /** * Margin-call a position. Only callable with the approval of the position lender. After the * call, the position owner will have time equal to the callTimeLimit of the position to close * the position. If the owner does not close the position, the lender can recover the collateral * in the position. * * @param positionId Unique ID of the position * @param requiredDeposit Amount of deposit the position owner will have to put up to cancel * the margin-call. Passing in 0 means the margin call cannot be * canceled by depositing */ function marginCall( bytes32 positionId, uint256 requiredDeposit ) external nonReentrant { LoanImpl.marginCallImpl( state, positionId, requiredDeposit ); } /** * Cancel a margin-call. Only callable with the approval of the position lender. * * @param positionId Unique ID of the position */ function cancelMarginCall( bytes32 positionId ) external onlyWhileOperational nonReentrant { LoanImpl.cancelMarginCallImpl(state, positionId); } /** * Used to recover the heldTokens held as collateral. Is callable after the maximum duration of * the loan has expired or the loan has been margin-called for the duration of the callTimeLimit * but remains unclosed. Only callable with the approval of the position lender. * * @param positionId Unique ID of the position * @param recipient Address to send the recovered tokens to * @return Amount of heldToken recovered */ function forceRecoverCollateral( bytes32 positionId, address recipient ) external nonReentrant returns (uint256) { return ForceRecoverCollateralImpl.forceRecoverCollateralImpl( state, positionId, recipient ); } /** * Deposit additional heldToken as collateral for a position. Cancels margin-call if: * 0 < position.requiredDeposit < depositAmount. Only callable by the position owner. * * @param positionId Unique ID of the position * @param depositAmount Additional amount in heldToken to deposit */ function depositCollateral( bytes32 positionId, uint256 depositAmount ) external onlyWhileOperational nonReentrant { DepositCollateralImpl.depositCollateralImpl( state, positionId, depositAmount ); } /** * Cancel an amount of a loan offering. Only callable by the loan offering's payer. * * @param addresses Array of addresses: * * [0] = owedToken * [1] = heldToken * [2] = loan payer * [3] = loan owner * [4] = loan taker * [5] = loan position owner * [6] = loan fee recipient * [7] = loan lender fee token * [8] = loan taker fee token * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param cancelAmount Amount to cancel * @return Amount that was canceled */ function cancelLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, uint256 cancelAmount ) external cancelLoanOfferingStateControl nonReentrant returns (uint256) { return LoanImpl.cancelLoanOfferingImpl( state, addresses, values256, values32, cancelAmount ); } /** * Transfer ownership of a loan to a new address. This new address will be entitled to all * payouts for this loan. Only callable by the lender for a position. If "who" is a contract, it * must implement the LoanOwner interface. * * @param positionId Unique ID of the position * @param who New owner of the loan */ function transferLoan( bytes32 positionId, address who ) external nonReentrant { TransferImpl.transferLoanImpl( state, positionId, who); } /** * Transfer ownership of a position to a new address. This new address will be entitled to all * payouts. Only callable by the owner of a position. If "who" is a contract, it must implement * the PositionOwner interface. * * @param positionId Unique ID of the position * @param who New owner of the position */ function transferPosition( bytes32 positionId, address who ) external nonReentrant { TransferImpl.transferPositionImpl( state, positionId, who); } // ============ Public Constant Functions ============ /** * Gets the address of the Vault contract that holds and accounts for tokens. * * @return The address of the Vault contract */ function getVaultAddress() external view returns (address) { return state.VAULT; } /** * Gets the address of the TokenProxy contract that accounts must set allowance on in order to * make loans or open/close positions. * * @return The address of the TokenProxy contract */ function getTokenProxyAddress() external view returns (address) { return state.TOKEN_PROXY; } } // File: contracts/margin/interfaces/OnlyMargin.sol /** * @title OnlyMargin * @author dYdX * * Contract to store the address of the main Margin contract and trust only that address to call * certain functions. */ contract OnlyMargin { // ============ Constants ============ // Address of the known and trusted Margin contract on the blockchain address public DYDX_MARGIN; // ============ Constructor ============ constructor( address margin ) public { DYDX_MARGIN = margin; } // ============ Modifiers ============ modifier onlyMargin() { require( msg.sender == DYDX_MARGIN, "OnlyMargin#onlyMargin: Only Margin can call" ); _; } } // File: contracts/margin/external/lib/LoanOfferingParser.sol /** * @title LoanOfferingParser * @author dYdX * * Contract for LoanOfferingVerifiers to parse arguments */ contract LoanOfferingParser { // ============ Parsing Functions ============ function parseLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes signature ) internal pure returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering; fillLoanOfferingAddresses(loanOffering, addresses); fillLoanOfferingValues256(loanOffering, values256); fillLoanOfferingValues32(loanOffering, values32); loanOffering.signature = signature; return loanOffering; } function fillLoanOfferingAddresses( MarginCommon.LoanOffering memory loanOffering, address[9] addresses ) private pure { loanOffering.owedToken = addresses[0]; loanOffering.heldToken = addresses[1]; loanOffering.payer = addresses[2]; loanOffering.owner = addresses[3]; loanOffering.taker = addresses[4]; loanOffering.positionOwner = addresses[5]; loanOffering.feeRecipient = addresses[6]; loanOffering.lenderFeeToken = addresses[7]; loanOffering.takerFeeToken = addresses[8]; } function fillLoanOfferingValues256( MarginCommon.LoanOffering memory loanOffering, uint256[7] values256 ) private pure { loanOffering.rates.maxAmount = values256[0]; loanOffering.rates.minAmount = values256[1]; loanOffering.rates.minHeldToken = values256[2]; loanOffering.rates.lenderFee = values256[3]; loanOffering.rates.takerFee = values256[4]; loanOffering.expirationTimestamp = values256[5]; loanOffering.salt = values256[6]; } function fillLoanOfferingValues32( MarginCommon.LoanOffering memory loanOffering, uint32[4] values32 ) private pure { loanOffering.callTimeLimit = values32[0]; loanOffering.maxDuration = values32[1]; loanOffering.rates.interestRate = values32[2]; loanOffering.rates.interestPeriod = values32[3]; } } // File: contracts/margin/external/lib/MarginHelper.sol /** * @title MarginHelper * @author dYdX * * This library contains helper functions for interacting with Margin */ library MarginHelper { function getPosition( address DYDX_MARGIN, bytes32 positionId ) internal view returns (MarginCommon.Position memory) { ( address[4] memory addresses, uint256[2] memory values256, uint32[6] memory values32 ) = Margin(DYDX_MARGIN).getPosition(positionId); return MarginCommon.Position({ owedToken: addresses[0], heldToken: addresses[1], lender: addresses[2], owner: addresses[3], principal: values256[0], requiredDeposit: values256[1], callTimeLimit: values32[0], startTimestamp: values32[1], callTimestamp: values32[2], maxDuration: values32[3], interestRate: values32[4], interestPeriod: values32[5] }); } } // File: contracts/margin/external/BucketLender/BucketLender.sol /** * @title BucketLender * @author dYdX * * On-chain shared lender that allows anyone to deposit tokens into this contract to be used to * lend tokens for a particular margin position. * * - Each bucket has three variables: * - Available Amount * - The available amount of tokens that the bucket has to lend out * - Outstanding Principal * - The amount of principal that the bucket is responsible for in the margin position * - Weight * - Used to keep track of each account's weighted ownership within a bucket * - Relative weight between buckets is meaningless * - Only accounts' relative weight within a bucket matters * * - Token Deposits: * - Go into a particular bucket, determined by time since the start of the position * - If the position has not started: bucket = 0 * - If the position has started: bucket = ceiling(time_since_start / BUCKET_TIME) * - This is always the highest bucket; no higher bucket yet exists * - Increase the bucket's Available Amount * - Increase the bucket's weight and the account's weight in that bucket * * - Token Withdrawals: * - Can be from any bucket with available amount * - Decrease the bucket's Available Amount * - Decrease the bucket's weight and the account's weight in that bucket * * - Increasing the Position (Lending): * - The lowest buckets with Available Amount are used first * - Decreases Available Amount * - Increases Outstanding Principal * * - Decreasing the Position (Being Paid-Back) * - The highest buckets with Outstanding Principal are paid back first * - Decreases Outstanding Principal * - Increases Available Amount * * * - Over time, this gives highest interest rates to earlier buckets, but disallows withdrawals from * those buckets for a longer period of time. * - Deposits in the same bucket earn the same interest rate. * - Lenders can withdraw their funds at any time if they are not being lent (and are therefore not * making the maximum interest). * - The highest bucket with Outstanding Principal is always less-than-or-equal-to the lowest bucket with Available Amount */ contract BucketLender is Ownable, OnlyMargin, LoanOwner, IncreaseLoanDelegator, MarginCallDelegator, CancelMarginCallDelegator, ForceRecoverCollateralDelegator, LoanOfferingParser, LoanOfferingVerifier, ReentrancyGuard { using SafeMath for uint256; using TokenInteract for address; // ============ Events ============ event Deposit( address indexed beneficiary, uint256 bucket, uint256 amount, uint256 weight ); event Withdraw( address indexed withdrawer, uint256 bucket, uint256 weight, uint256 owedTokenWithdrawn, uint256 heldTokenWithdrawn ); event PrincipalIncreased( uint256 principalTotal, uint256 bucketNumber, uint256 principalForBucket, uint256 amount ); event PrincipalDecreased( uint256 principalTotal, uint256 bucketNumber, uint256 principalForBucket, uint256 amount ); event AvailableIncreased( uint256 availableTotal, uint256 bucketNumber, uint256 availableForBucket, uint256 amount ); event AvailableDecreased( uint256 availableTotal, uint256 bucketNumber, uint256 availableForBucket, uint256 amount ); // ============ State Variables ============ /** * Available Amount is the amount of tokens that is available to be lent by each bucket. * These tokens are also available to be withdrawn by the accounts that have weight in the * bucket. */ // Available Amount for each bucket mapping(uint256 => uint256) public availableForBucket; // Total Available Amount uint256 public availableTotal; /** * Outstanding Principal is the share of the margin position's principal that each bucket * is responsible for. That is, each bucket with Outstanding Principal is owed * (Outstanding Principal)*E^(RT) owedTokens in repayment. */ // Outstanding Principal for each bucket mapping(uint256 => uint256) public principalForBucket; // Total Outstanding Principal uint256 public principalTotal; /** * Weight determines an account's proportional share of a bucket. Relative weights have no * meaning if they are not for the same bucket. Likewise, the relative weight of two buckets has * no meaning. However, the relative weight of two accounts within the same bucket is equal to * the accounts' shares in the bucket and are therefore proportional to the payout that they * should expect from withdrawing from that bucket. */ // Weight for each account in each bucket mapping(uint256 => mapping(address => uint256)) public weightForBucketForAccount; // Total Weight for each bucket mapping(uint256 => uint256) public weightForBucket; /** * The critical bucket is: * - Greater-than-or-equal-to The highest bucket with Outstanding Principal * - Less-than-or-equal-to the lowest bucket with Available Amount * * It is equal to both of these values in most cases except in an edge cases where the two * buckets are different. This value is cached to find such a bucket faster than looping through * all possible buckets. */ uint256 public criticalBucket = 0; /** * Latest cached value for totalOwedTokenRepaidToLender. * This number updates on the dYdX Margin base protocol whenever the position is * partially-closed, but this contract is not notified at that time. Therefore, it is updated * upon increasing the position or when depositing/withdrawing */ uint256 public cachedRepaidAmount = 0; // True if the position was closed from force-recovering the collateral bool public wasForceClosed = false; // ============ Constants ============ // Unique ID of the position bytes32 public POSITION_ID; // Address of the token held in the position as collateral address public HELD_TOKEN; // Address of the token being lent address public OWED_TOKEN; // Time between new buckets uint32 public BUCKET_TIME; // Interest rate of the position uint32 public INTEREST_RATE; // Interest period of the position uint32 public INTEREST_PERIOD; // Maximum duration of the position uint32 public MAX_DURATION; // Margin-call time-limit of the position uint32 public CALL_TIMELIMIT; // (NUMERATOR/DENOMINATOR) denotes the minimum collateralization ratio of the position uint32 public MIN_HELD_TOKEN_NUMERATOR; uint32 public MIN_HELD_TOKEN_DENOMINATOR; // Accounts that are permitted to margin-call positions (or cancel the margin call) mapping(address => bool) public TRUSTED_MARGIN_CALLERS; // Accounts that are permitted to withdraw on behalf of any address mapping(address => bool) public TRUSTED_WITHDRAWERS; // ============ Constructor ============ constructor( address margin, bytes32 positionId, address heldToken, address owedToken, uint32[7] parameters, address[] trustedMarginCallers, address[] trustedWithdrawers ) public OnlyMargin(margin) { POSITION_ID = positionId; HELD_TOKEN = heldToken; OWED_TOKEN = owedToken; require( parameters[0] != 0, "BucketLender#constructor: BUCKET_TIME cannot be zero" ); BUCKET_TIME = parameters[0]; INTEREST_RATE = parameters[1]; INTEREST_PERIOD = parameters[2]; MAX_DURATION = parameters[3]; CALL_TIMELIMIT = parameters[4]; MIN_HELD_TOKEN_NUMERATOR = parameters[5]; MIN_HELD_TOKEN_DENOMINATOR = parameters[6]; // Initialize TRUSTED_MARGIN_CALLERS and TRUSTED_WITHDRAWERS uint256 i = 0; for (i = 0; i < trustedMarginCallers.length; i++) { TRUSTED_MARGIN_CALLERS[trustedMarginCallers[i]] = true; } for (i = 0; i < trustedWithdrawers.length; i++) { TRUSTED_WITHDRAWERS[trustedWithdrawers[i]] = true; } // Set maximum allowance on proxy OWED_TOKEN.approve( Margin(margin).getTokenProxyAddress(), MathHelpers.maxUint256() ); } // ============ Modifiers ============ modifier onlyPosition(bytes32 positionId) { require( POSITION_ID == positionId, "BucketLender#onlyPosition: Incorrect position" ); _; } // ============ Margin-Only State-Changing Functions ============ /** * Function a smart contract must implement to be able to consent to a loan. The loan offering * will be generated off-chain. The "loan owner" address will own the loan-side of the resulting * position. * * @param addresses Loan offering addresses * @param values256 Loan offering uint256s * @param values32 Loan offering uint32s * @param positionId Unique ID of the position * @param signature Arbitrary bytes * @return This address to accept, a different address to ask that contract */ function verifyLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { require( Margin(DYDX_MARGIN).containsPosition(POSITION_ID), "BucketLender#verifyLoanOffering: This contract should not open a new position" ); MarginCommon.LoanOffering memory loanOffering = parseLoanOffering( addresses, values256, values32, signature ); // CHECK ADDRESSES assert(loanOffering.owedToken == OWED_TOKEN); assert(loanOffering.heldToken == HELD_TOKEN); assert(loanOffering.payer == address(this)); assert(loanOffering.owner == address(this)); require( loanOffering.taker == address(0), "BucketLender#verifyLoanOffering: loanOffering.taker is non-zero" ); require( loanOffering.feeRecipient == address(0), "BucketLender#verifyLoanOffering: loanOffering.feeRecipient is non-zero" ); require( loanOffering.positionOwner == address(0), "BucketLender#verifyLoanOffering: loanOffering.positionOwner is non-zero" ); require( loanOffering.lenderFeeToken == address(0), "BucketLender#verifyLoanOffering: loanOffering.lenderFeeToken is non-zero" ); require( loanOffering.takerFeeToken == address(0), "BucketLender#verifyLoanOffering: loanOffering.takerFeeToken is non-zero" ); // CHECK VALUES256 require( loanOffering.rates.maxAmount == MathHelpers.maxUint256(), "BucketLender#verifyLoanOffering: loanOffering.maxAmount is incorrect" ); require( loanOffering.rates.minAmount == 0, "BucketLender#verifyLoanOffering: loanOffering.minAmount is non-zero" ); require( loanOffering.rates.minHeldToken == 0, "BucketLender#verifyLoanOffering: loanOffering.minHeldToken is non-zero" ); require( loanOffering.rates.lenderFee == 0, "BucketLender#verifyLoanOffering: loanOffering.lenderFee is non-zero" ); require( loanOffering.rates.takerFee == 0, "BucketLender#verifyLoanOffering: loanOffering.takerFee is non-zero" ); require( loanOffering.expirationTimestamp == MathHelpers.maxUint256(), "BucketLender#verifyLoanOffering: expirationTimestamp is incorrect" ); require( loanOffering.salt == 0, "BucketLender#verifyLoanOffering: loanOffering.salt is non-zero" ); // CHECK VALUES32 require( loanOffering.callTimeLimit == MathHelpers.maxUint32(), "BucketLender#verifyLoanOffering: loanOffering.callTimelimit is incorrect" ); require( loanOffering.maxDuration == MathHelpers.maxUint32(), "BucketLender#verifyLoanOffering: loanOffering.maxDuration is incorrect" ); assert(loanOffering.rates.interestRate == INTEREST_RATE); assert(loanOffering.rates.interestPeriod == INTEREST_PERIOD); // no need to require anything about loanOffering.signature return address(this); } /** * Called by the Margin contract when anyone transfers ownership of a loan to this contract. * This function initializes this contract and returns this address to indicate to Margin * that it is willing to take ownership of the loan. * * @param from Address of the previous owner * @param positionId Unique ID of the position * @return This address on success, throw otherwise */ function receiveLoanOwnership( address from, bytes32 positionId ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { MarginCommon.Position memory position = MarginHelper.getPosition(DYDX_MARGIN, POSITION_ID); uint256 initialPrincipal = position.principal; uint256 minHeldToken = MathHelpers.getPartialAmount( uint256(MIN_HELD_TOKEN_NUMERATOR), uint256(MIN_HELD_TOKEN_DENOMINATOR), initialPrincipal ); assert(initialPrincipal > 0); assert(principalTotal == 0); assert(from != address(this)); // position must be opened without lending from this position require( position.owedToken == OWED_TOKEN, "BucketLender#receiveLoanOwnership: Position owedToken mismatch" ); require( position.heldToken == HELD_TOKEN, "BucketLender#receiveLoanOwnership: Position heldToken mismatch" ); require( position.maxDuration == MAX_DURATION, "BucketLender#receiveLoanOwnership: Position maxDuration mismatch" ); require( position.callTimeLimit == CALL_TIMELIMIT, "BucketLender#receiveLoanOwnership: Position callTimeLimit mismatch" ); require( position.interestRate == INTEREST_RATE, "BucketLender#receiveLoanOwnership: Position interestRate mismatch" ); require( position.interestPeriod == INTEREST_PERIOD, "BucketLender#receiveLoanOwnership: Position interestPeriod mismatch" ); require( Margin(DYDX_MARGIN).getPositionBalance(POSITION_ID) >= minHeldToken, "BucketLender#receiveLoanOwnership: Not enough heldToken as collateral" ); // set relevant constants principalForBucket[0] = initialPrincipal; principalTotal = initialPrincipal; weightForBucket[0] = weightForBucket[0].add(initialPrincipal); weightForBucketForAccount[0][from] = weightForBucketForAccount[0][from].add(initialPrincipal); return address(this); } /** * Called by Margin when additional value is added onto the position this contract * is lending for. Balance is added to the address that loaned the additional tokens. * * @param payer Address that loaned the additional tokens * @param positionId Unique ID of the position * @param principalAdded Amount that was added to the position * @param lentAmount Amount of owedToken lent * @return This address to accept, a different address to ask that contract */ function increaseLoanOnBehalfOf( address payer, bytes32 positionId, uint256 principalAdded, uint256 lentAmount ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { Margin margin = Margin(DYDX_MARGIN); require( payer == address(this), "BucketLender#increaseLoanOnBehalfOf: Other lenders cannot lend for this position" ); require( !margin.isPositionCalled(POSITION_ID), "BucketLender#increaseLoanOnBehalfOf: No lending while the position is margin-called" ); // This function is only called after the state has been updated in the base protocol; // thus, the principal in the base protocol will equal the principal after the increase uint256 principalAfterIncrease = margin.getPositionPrincipal(POSITION_ID); uint256 principalBeforeIncrease = principalAfterIncrease.sub(principalAdded); // principalTotal was the principal after the previous increase accountForClose(principalTotal.sub(principalBeforeIncrease)); accountForIncrease(principalAdded, lentAmount); assert(principalTotal == principalAfterIncrease); return address(this); } /** * Function a contract must implement in order to let other addresses call marginCall(). * * @param caller Address of the caller of the marginCall function * @param positionId Unique ID of the position * @param depositAmount Amount of heldToken deposit that will be required to cancel the call * @return This address to accept, a different address to ask that contract */ function marginCallOnBehalfOf( address caller, bytes32 positionId, uint256 depositAmount ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { require( TRUSTED_MARGIN_CALLERS[caller], "BucketLender#marginCallOnBehalfOf: Margin-caller must be trusted" ); require( depositAmount == 0, // prevents depositing from canceling the margin-call "BucketLender#marginCallOnBehalfOf: Deposit amount must be zero" ); return address(this); } /** * Function a contract must implement in order to let other addresses call cancelMarginCall(). * * @param canceler Address of the caller of the cancelMarginCall function * @param positionId Unique ID of the position * @return This address to accept, a different address to ask that contract */ function cancelMarginCallOnBehalfOf( address canceler, bytes32 positionId ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { require( TRUSTED_MARGIN_CALLERS[canceler], "BucketLender#cancelMarginCallOnBehalfOf: Margin-call-canceler must be trusted" ); return address(this); } /** * Function a contract must implement in order to let other addresses call * forceRecoverCollateral(). * * param recoverer Address of the caller of the forceRecoverCollateral() function * @param positionId Unique ID of the position * @param recipient Address to send the recovered tokens to * @return This address to accept, a different address to ask that contract */ function forceRecoverCollateralOnBehalfOf( address /* recoverer */, bytes32 positionId, address recipient ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { return forceRecoverCollateralInternal(recipient); } // ============ Public State-Changing Functions ============ /** * Allow anyone to recalculate the Outstanding Principal and Available Amount for the buckets if * part of the position has been closed since the last position increase. */ function rebalanceBuckets() external nonReentrant { rebalanceBucketsInternal(); } /** * Allows users to deposit owedToken into this contract. Allowance must be set on this contract * for "token" in at least the amount "amount". * * @param beneficiary The account that will be entitled to this depoit * @param amount The amount of owedToken to deposit * @return The bucket number that was deposited into */ function deposit( address beneficiary, uint256 amount ) external nonReentrant returns (uint256) { Margin margin = Margin(DYDX_MARGIN); bytes32 positionId = POSITION_ID; require( beneficiary != address(0), "BucketLender#deposit: Beneficiary cannot be the zero address" ); require( amount != 0, "BucketLender#deposit: Cannot deposit zero tokens" ); require( !margin.isPositionClosed(positionId), "BucketLender#deposit: Cannot deposit after the position is closed" ); require( !margin.isPositionCalled(positionId), "BucketLender#deposit: Cannot deposit while the position is margin-called" ); rebalanceBucketsInternal(); OWED_TOKEN.transferFrom( msg.sender, address(this), amount ); uint256 bucket = getCurrentBucket(); uint256 effectiveAmount = availableForBucket[bucket].add(getBucketOwedAmount(bucket)); uint256 weightToAdd = 0; if (effectiveAmount == 0) { weightToAdd = amount; // first deposit in bucket } else { weightToAdd = MathHelpers.getPartialAmount( amount, effectiveAmount, weightForBucket[bucket] ); } require( weightToAdd != 0, "BucketLender#deposit: Cannot deposit for zero weight" ); // update state updateAvailable(bucket, amount, true); weightForBucketForAccount[bucket][beneficiary] = weightForBucketForAccount[bucket][beneficiary].add(weightToAdd); weightForBucket[bucket] = weightForBucket[bucket].add(weightToAdd); emit Deposit( beneficiary, bucket, amount, weightToAdd ); return bucket; } /** * Allows users to withdraw their lent funds. An account can withdraw its weighted share of the * bucket. * * While the position is open, a bucket's share is equal to: * Owed Token: (Available Amount) + (Outstanding Principal) * (1 + interest) * Held Token: 0 * * After the position is closed, a bucket's share is equal to: * Owed Token: (Available Amount) * Held Token: (Held Token Balance) * (Outstanding Principal) / (Total Outstanding Principal) * * @param buckets The bucket numbers to withdraw from * @param maxWeights The maximum weight to withdraw from each bucket. The amount of tokens * withdrawn will be at least this amount, but not necessarily more. * Withdrawing the same weight from different buckets does not necessarily * return the same amounts from those buckets. In order to withdraw as many * tokens as possible, use the maximum uint256. * @param onBehalfOf The address to withdraw on behalf of * @return 1) The number of owedTokens withdrawn * 2) The number of heldTokens withdrawn */ function withdraw( uint256[] buckets, uint256[] maxWeights, address onBehalfOf ) external nonReentrant returns (uint256, uint256) { require( buckets.length == maxWeights.length, "BucketLender#withdraw: The lengths of the input arrays must match" ); if (onBehalfOf != msg.sender) { require( TRUSTED_WITHDRAWERS[msg.sender], "BucketLender#withdraw: Only trusted withdrawers can withdraw on behalf of others" ); } rebalanceBucketsInternal(); // decide if some bucket is unable to be withdrawn from (is locked) // the zero value represents no-lock uint256 lockedBucket = 0; if ( Margin(DYDX_MARGIN).containsPosition(POSITION_ID) && criticalBucket == getCurrentBucket() ) { lockedBucket = criticalBucket; } uint256[2] memory results; // [0] = totalOwedToken, [1] = totalHeldToken uint256 maxHeldToken = 0; if (wasForceClosed) { maxHeldToken = HELD_TOKEN.balanceOf(address(this)); } for (uint256 i = 0; i < buckets.length; i++) { uint256 bucket = buckets[i]; // prevent withdrawing from the current bucket if it is also the critical bucket if ((bucket != 0) && (bucket == lockedBucket)) { continue; } (uint256 owedTokenForBucket, uint256 heldTokenForBucket) = withdrawSingleBucket( onBehalfOf, bucket, maxWeights[i], maxHeldToken ); results[0] = results[0].add(owedTokenForBucket); results[1] = results[1].add(heldTokenForBucket); } // Transfer share of owedToken OWED_TOKEN.transfer(msg.sender, results[0]); HELD_TOKEN.transfer(msg.sender, results[1]); return (results[0], results[1]); } /** * Allows the owner to withdraw any excess tokens sent to the vault by unconventional means, * including (but not limited-to) token airdrops. Any tokens moved to this contract by calling * deposit() will be accounted for and will not be withdrawable by this function. * * @param token ERC20 token address * @param to Address to transfer tokens to * @return Amount of tokens withdrawn */ function withdrawExcessToken( address token, address to ) external onlyOwner returns (uint256) { rebalanceBucketsInternal(); uint256 amount = token.balanceOf(address(this)); if (token == OWED_TOKEN) { amount = amount.sub(availableTotal); } else if (token == HELD_TOKEN) { require( !wasForceClosed, "BucketLender#withdrawExcessToken: heldToken cannot be withdrawn if force-closed" ); } token.transfer(to, amount); return amount; } // ============ Public Getter Functions ============ /** * Get the current bucket number that funds will be deposited into. This is also the highest * bucket so far. * * @return The highest bucket and the one that funds will be deposited into */ function getCurrentBucket() public view returns (uint256) { // load variables from storage; Margin margin = Margin(DYDX_MARGIN); bytes32 positionId = POSITION_ID; uint32 bucketTime = BUCKET_TIME; assert(!margin.isPositionClosed(positionId)); // if position not created, allow deposits in the first bucket if (!margin.containsPosition(positionId)) { return 0; } // return the number of BUCKET_TIME periods elapsed since the position start, rounded-up uint256 startTimestamp = margin.getPositionStartTimestamp(positionId); return block.timestamp.sub(startTimestamp).div(bucketTime).add(1); } /** * Gets the outstanding amount of owedToken owed to a bucket. This is the principal amount of * the bucket multiplied by the interest accrued in the position. If the position is closed, * then any outstanding principal will never be repaid in the form of owedToken. * * @param bucket The bucket number * @return The amount of owedToken that this bucket expects to be paid-back if the posi */ function getBucketOwedAmount( uint256 bucket ) public view returns (uint256) { // if the position is completely closed, then the outstanding principal will never be repaid if (Margin(DYDX_MARGIN).isPositionClosed(POSITION_ID)) { return 0; } uint256 lentPrincipal = principalForBucket[bucket]; // the bucket has no outstanding principal if (lentPrincipal == 0) { return 0; } // get the total amount of owedToken that would be paid back at this time uint256 owedAmount = Margin(DYDX_MARGIN).getPositionOwedAmountAtTime( POSITION_ID, principalTotal, uint32(block.timestamp) ); // return the bucket's share return MathHelpers.getPartialAmount( lentPrincipal, principalTotal, owedAmount ); } // ============ Internal Functions ============ function forceRecoverCollateralInternal( address recipient ) internal returns (address) { require( recipient == address(this), "BucketLender#forceRecoverCollateralOnBehalfOf: Recipient must be this contract" ); rebalanceBucketsInternal(); wasForceClosed = true; return address(this); } // ============ Private Helper Functions ============ /** * Recalculates the Outstanding Principal and Available Amount for the buckets. Only changes the * state if part of the position has been closed since the last position increase. */ function rebalanceBucketsInternal() private { // if force-closed, don't update the outstanding principal values; they are needed to repay // lenders with heldToken if (wasForceClosed) { return; } uint256 marginPrincipal = Margin(DYDX_MARGIN).getPositionPrincipal(POSITION_ID); accountForClose(principalTotal.sub(marginPrincipal)); assert(principalTotal == marginPrincipal); } /** * Updates the state variables at any time. Only does anything after the position has been * closed or partially-closed since the last time this function was called. * * - Increases the available amount in the highest buckets with outstanding principal * - Decreases the principal amount in those buckets * * @param principalRemoved Amount of principal closed since the last update */ function accountForClose( uint256 principalRemoved ) private { if (principalRemoved == 0) { return; } uint256 newRepaidAmount = Margin(DYDX_MARGIN).getTotalOwedTokenRepaidToLender(POSITION_ID); assert(newRepaidAmount.sub(cachedRepaidAmount) >= principalRemoved); uint256 principalToSub = principalRemoved; uint256 availableToAdd = newRepaidAmount.sub(cachedRepaidAmount); uint256 criticalBucketTemp = criticalBucket; // loop over buckets in reverse order starting with the critical bucket for ( uint256 bucket = criticalBucketTemp; principalToSub > 0; bucket-- ) { assert(bucket <= criticalBucketTemp); // no underflow on bucket uint256 principalTemp = Math.min256(principalToSub, principalForBucket[bucket]); if (principalTemp == 0) { continue; } uint256 availableTemp = MathHelpers.getPartialAmount( principalTemp, principalToSub, availableToAdd ); updateAvailable(bucket, availableTemp, true); updatePrincipal(bucket, principalTemp, false); principalToSub = principalToSub.sub(principalTemp); availableToAdd = availableToAdd.sub(availableTemp); criticalBucketTemp = bucket; } assert(principalToSub == 0); assert(availableToAdd == 0); setCriticalBucket(criticalBucketTemp); cachedRepaidAmount = newRepaidAmount; } /** * Updates the state variables when a position is increased. * * - Decreases the available amount in the lowest buckets with available token * - Increases the principal amount in those buckets * * @param principalAdded Amount of principal added to the position * @param lentAmount Amount of owedToken lent */ function accountForIncrease( uint256 principalAdded, uint256 lentAmount ) private { require( lentAmount <= availableTotal, "BucketLender#accountForIncrease: No lending not-accounted-for funds" ); uint256 principalToAdd = principalAdded; uint256 availableToSub = lentAmount; uint256 criticalBucketTemp; // loop over buckets in order starting from the critical bucket uint256 lastBucket = getCurrentBucket(); for ( uint256 bucket = criticalBucket; principalToAdd > 0; bucket++ ) { assert(bucket <= lastBucket); // should never go past the last bucket uint256 availableTemp = Math.min256(availableToSub, availableForBucket[bucket]); if (availableTemp == 0) { continue; } uint256 principalTemp = MathHelpers.getPartialAmount( availableTemp, availableToSub, principalToAdd ); updateAvailable(bucket, availableTemp, false); updatePrincipal(bucket, principalTemp, true); principalToAdd = principalToAdd.sub(principalTemp); availableToSub = availableToSub.sub(availableTemp); criticalBucketTemp = bucket; } assert(principalToAdd == 0); assert(availableToSub == 0); setCriticalBucket(criticalBucketTemp); } /** * Withdraw * * @param onBehalfOf The account for which to withdraw for * @param bucket The bucket number to withdraw from * @param maxWeight The maximum weight to withdraw * @param maxHeldToken The total amount of heldToken that has been force-recovered * @return 1) The number of owedTokens withdrawn * 2) The number of heldTokens withdrawn */ function withdrawSingleBucket( address onBehalfOf, uint256 bucket, uint256 maxWeight, uint256 maxHeldToken ) private returns (uint256, uint256) { // calculate the user's share uint256 bucketWeight = weightForBucket[bucket]; if (bucketWeight == 0) { return (0, 0); } uint256 userWeight = weightForBucketForAccount[bucket][onBehalfOf]; uint256 weightToWithdraw = Math.min256(maxWeight, userWeight); if (weightToWithdraw == 0) { return (0, 0); } // update state weightForBucket[bucket] = weightForBucket[bucket].sub(weightToWithdraw); weightForBucketForAccount[bucket][onBehalfOf] = userWeight.sub(weightToWithdraw); // calculate for owedToken uint256 owedTokenToWithdraw = withdrawOwedToken( bucket, weightToWithdraw, bucketWeight ); // calculate for heldToken uint256 heldTokenToWithdraw = withdrawHeldToken( bucket, weightToWithdraw, bucketWeight, maxHeldToken ); emit Withdraw( onBehalfOf, bucket, weightToWithdraw, owedTokenToWithdraw, heldTokenToWithdraw ); return (owedTokenToWithdraw, heldTokenToWithdraw); } /** * Helper function to withdraw earned owedToken from this contract. * * @param bucket The bucket number to withdraw from * @param userWeight The amount of weight the user is using to withdraw * @param bucketWeight The total weight of the bucket * @return The amount of owedToken being withdrawn */ function withdrawOwedToken( uint256 bucket, uint256 userWeight, uint256 bucketWeight ) private returns (uint256) { // amount to return for the bucket uint256 owedTokenToWithdraw = MathHelpers.getPartialAmount( userWeight, bucketWeight, availableForBucket[bucket].add(getBucketOwedAmount(bucket)) ); // check that there is enough token to give back require( owedTokenToWithdraw <= availableForBucket[bucket], "BucketLender#withdrawOwedToken: There must be enough available owedToken" ); // update amounts updateAvailable(bucket, owedTokenToWithdraw, false); return owedTokenToWithdraw; } /** * Helper function to withdraw heldToken from this contract. * * @param bucket The bucket number to withdraw from * @param userWeight The amount of weight the user is using to withdraw * @param bucketWeight The total weight of the bucket * @param maxHeldToken The total amount of heldToken available to withdraw * @return The amount of heldToken being withdrawn */ function withdrawHeldToken( uint256 bucket, uint256 userWeight, uint256 bucketWeight, uint256 maxHeldToken ) private returns (uint256) { if (maxHeldToken == 0) { return 0; } // user's principal for the bucket uint256 principalForBucketForAccount = MathHelpers.getPartialAmount( userWeight, bucketWeight, principalForBucket[bucket] ); uint256 heldTokenToWithdraw = MathHelpers.getPartialAmount( principalForBucketForAccount, principalTotal, maxHeldToken ); updatePrincipal(bucket, principalForBucketForAccount, false); return heldTokenToWithdraw; } // ============ Setter Functions ============ /** * Changes the critical bucket variable * * @param bucket The value to set criticalBucket to */ function setCriticalBucket( uint256 bucket ) private { // don't spend the gas to sstore unless we need to change the value if (criticalBucket == bucket) { return; } criticalBucket = bucket; } /** * Changes the available owedToken amount. This changes both the variable to track the total * amount as well as the variable to track a particular bucket. * * @param bucket The bucket number * @param amount The amount to change the available amount by * @param increase True if positive change, false if negative change */ function updateAvailable( uint256 bucket, uint256 amount, bool increase ) private { if (amount == 0) { return; } uint256 newTotal; uint256 newForBucket; if (increase) { newTotal = availableTotal.add(amount); newForBucket = availableForBucket[bucket].add(amount); emit AvailableIncreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } else { newTotal = availableTotal.sub(amount); newForBucket = availableForBucket[bucket].sub(amount); emit AvailableDecreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } availableTotal = newTotal; availableForBucket[bucket] = newForBucket; } /** * Changes the principal amount. This changes both the variable to track the total * amount as well as the variable to track a particular bucket. * * @param bucket The bucket number * @param amount The amount to change the principal amount by * @param increase True if positive change, false if negative change */ function updatePrincipal( uint256 bucket, uint256 amount, bool increase ) private { if (amount == 0) { return; } uint256 newTotal; uint256 newForBucket; if (increase) { newTotal = principalTotal.add(amount); newForBucket = principalForBucket[bucket].add(amount); emit PrincipalIncreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } else { newTotal = principalTotal.sub(amount); newForBucket = principalForBucket[bucket].sub(amount); emit PrincipalDecreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } principalTotal = newTotal; principalForBucket[bucket] = newForBucket; } } // File: contracts/margin/external/BucketLender/BucketLenderFactory.sol /** * @title BucketLenderFactory * @author dYdX * * Contract that allows anyone to deploy a BucketLender contract by sending a transaction. */ contract BucketLenderFactory { // ============ Events ============ event BucketLenderCreated( address indexed creator, address indexed owner, bytes32 indexed positionId, address at ); // ============ State Variables ============ // Address of the Margin contract for the dYdX Margin Trading Protocol address public DYDX_MARGIN; // ============ Constructor ============ constructor( address margin ) public { DYDX_MARGIN = margin; } // ============ Public Functions ============ /** * Deploy a new BucketLender contract to the blockchain * * @param positionId Unique ID of the position * @param owner Address to which ownership of the BucketLender will be transferred * @param heldToken Address of the token held in the position as collateral * @param owedToken Address of the token being lent by the BucketLender * @param parameters Values corresponding to: * * [0] = number of seconds per bucket * [1] = interest rate * [2] = interest period * [3] = maximum loan duration * [4] = margin-call timelimit * [5] = numerator of minimum heldToken-per-owedToken * [6] = denominator of minimum heldToken-per-owedToken * * @param marginCallers Accounts that are permitted to margin-call positions (or cancel the margin call) * @return The address of the new BucketLender contract */ function createBucketLender( bytes32 positionId, address owner, address heldToken, address owedToken, uint32[7] parameters, address[] marginCallers, address[] withdrawers ) external returns (address) { address newBucketLender = new BucketLender( DYDX_MARGIN, positionId, heldToken, owedToken, parameters, marginCallers, withdrawers ); BucketLender(newBucketLender).transferOwnership(owner); emit BucketLenderCreated( msg.sender, owner, positionId, newBucketLender ); return newBucketLender; } }
* Transfer ownership of a loan to a new address. This new address will be entitled to all payouts for this loan. Only callable by the lender for a position. If "who" is a contract, it must implement the LoanOwner interface. @param positionId Unique ID of the position @param who New owner of the loan/
function transferLoan( bytes32 positionId, address who ) external nonReentrant { TransferImpl.transferLoanImpl( state, positionId, who); }
1,594,153
[ 1, 5912, 23178, 434, 279, 28183, 358, 279, 394, 1758, 18, 1220, 394, 1758, 903, 506, 3281, 305, 1259, 358, 777, 293, 2012, 87, 364, 333, 28183, 18, 5098, 4140, 635, 326, 328, 2345, 364, 279, 1754, 18, 971, 315, 3350, 83, 6, 353, 279, 6835, 16, 518, 1297, 2348, 326, 3176, 304, 5541, 1560, 18, 282, 1754, 548, 225, 14584, 1599, 434, 326, 1754, 282, 10354, 540, 1166, 3410, 434, 326, 28183, 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, 7412, 1504, 304, 12, 203, 3639, 1731, 1578, 1754, 548, 16, 203, 3639, 1758, 10354, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1661, 426, 8230, 970, 203, 565, 288, 203, 3639, 12279, 2828, 18, 13866, 1504, 304, 2828, 12, 203, 5411, 919, 16, 203, 5411, 1754, 548, 16, 203, 5411, 10354, 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 ]
// SPDX-License-Identifier: Apache-2.0 /* * Copyright 2020, Offchain 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.6.11; import "./aeERC20.sol"; import "./BytesParser.sol"; import "../arbitrum/IArbToken.sol"; /** * @title Standard (i.e., non-custom) contract used as a base for different L2 Gateways */ abstract contract L2GatewayToken is aeERC20, IArbToken { address public l2Gateway; address public override l1Address; modifier onlyGateway { require(msg.sender == l2Gateway, "ONLY_GATEWAY"); _; } /** * @notice initialize the token * @dev the L2 bridge assumes this does not fail or revert * @param _name ERC20 token name * @param _symbol ERC20 token symbol * @param _decimals ERC20 decimals * @param _l2Gateway L2 gateway this token communicates with * @param _l1Counterpart L1 address of ERC20 */ function _initialize( string memory _name, string memory _symbol, uint8 _decimals, address _l2Gateway, address _l1Counterpart ) internal virtual { require(_l2Gateway != address(0), "INVALID_GATEWAY"); require(l2Gateway == address(0), "ALREADY_INIT"); l2Gateway = _l2Gateway; l1Address = _l1Counterpart; aeERC20._initialize(_name, _symbol, _decimals); } /** * @notice Mint tokens on L2. Callable path is L1Gateway depositToken (which handles L1 escrow), which triggers L2Gateway, which calls this * @param account recipient of tokens * @param amount amount of tokens minted */ function bridgeMint(address account, uint256 amount) external virtual override onlyGateway { _mint(account, amount); } /** * @notice Burn tokens on L2. * @dev only the token bridge can call this * @param account owner of tokens * @param amount amount of tokens burnt */ function bridgeBurn(address account, uint256 amount) external virtual override onlyGateway { _burn(account, amount); } }
* @title Standard (i.e., non-custom) contract used as a base for different L2 Gateways/
abstract contract L2GatewayToken is aeERC20, IArbToken { address public l2Gateway; address public override l1Address; modifier onlyGateway { require(msg.sender == l2Gateway, "ONLY_GATEWAY"); _; } function _initialize( string memory _name, string memory _symbol, uint8 _decimals, address _l2Gateway, address _l1Counterpart ) internal virtual { require(_l2Gateway != address(0), "INVALID_GATEWAY"); require(l2Gateway == address(0), "ALREADY_INIT"); l2Gateway = _l2Gateway; l1Address = _l1Counterpart; aeERC20._initialize(_name, _symbol, _decimals); } function bridgeMint(address account, uint256 amount) external virtual override onlyGateway { _mint(account, amount); } function bridgeBurn(address account, uint256 amount) external virtual override onlyGateway { _burn(account, amount); } }
12,678,220
[ 1, 8336, 261, 77, 18, 73, 12990, 1661, 17, 3662, 13, 6835, 1399, 487, 279, 1026, 364, 3775, 511, 22, 31045, 3052, 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, 17801, 6835, 511, 22, 5197, 1345, 353, 14221, 654, 39, 3462, 16, 467, 686, 70, 1345, 288, 203, 565, 1758, 1071, 328, 22, 5197, 31, 203, 565, 1758, 1071, 3849, 328, 21, 1887, 31, 203, 203, 203, 203, 565, 9606, 1338, 5197, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 328, 22, 5197, 16, 315, 10857, 67, 26316, 18098, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 389, 11160, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 7175, 16, 203, 3639, 2254, 28, 389, 31734, 16, 203, 3639, 1758, 389, 80, 22, 5197, 16, 203, 3639, 1758, 389, 80, 21, 4789, 2680, 203, 565, 262, 2713, 5024, 288, 203, 3639, 2583, 24899, 80, 22, 5197, 480, 1758, 12, 20, 3631, 315, 9347, 67, 26316, 18098, 8863, 203, 3639, 2583, 12, 80, 22, 5197, 422, 1758, 12, 20, 3631, 315, 1013, 20305, 67, 12919, 8863, 203, 3639, 328, 22, 5197, 273, 389, 80, 22, 5197, 31, 203, 3639, 328, 21, 1887, 273, 389, 80, 21, 4789, 2680, 31, 203, 203, 3639, 14221, 654, 39, 3462, 6315, 11160, 24899, 529, 16, 389, 7175, 16, 389, 31734, 1769, 203, 565, 289, 203, 203, 565, 445, 10105, 49, 474, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 3903, 5024, 3849, 1338, 5197, 288, 203, 3639, 389, 81, 474, 12, 4631, 16, 3844, 1769, 203, 565, 289, 203, 203, 565, 445, 10105, 38, 321, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 3903, 5024, 3849, 1338, 5197, 288, 203, 2 ]
//Address: 0x5027880b5A4C5BBB88D229a334Aa8F31e6e67197 //Contract name: HDLContract //Balance: 0 Ether //Verification Date: 10/12/2017 //Transacion Count: 198 // CODE STARTS HERE pragma solidity ^0.4.13; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); 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) 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) returns (bool) { 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) constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) 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) returns (bool) { var _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) returns (bool) { // 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 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) 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() { 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 { require(newOwner != address(0)); owner = newOwner; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); event MintStarted(); bool public mintingActive = true; uint256 public maxTokenCount; modifier canMint() { require(mintingActive); _; } /** * @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) onlyOwner canMint returns (bool) { require(totalSupply <= maxTokenCount); totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function stopMinting() onlyOwner returns (bool) { mintingActive = false; MintFinished(); return true; } /** * @dev Function to start minting new tokens. * @return True if the operation was successful. */ function startMinting() onlyOwner returns (bool) { mintingActive = true; MintStarted(); return true; } } /** * HDL (Handelion) Token * */ contract HDLToken is MintableToken { string public constant name = "Handelion token"; string public constant symbol = "HDLT"; uint32 public constant decimals = 18; function HDLToken() { maxTokenCount = 29750000 * 1 ether; } } contract HDLContract is Ownable { using SafeMath for uint; // Contract owner addredd address _ownerAddress; // Contract vault address - all collected funds are moved to this address after successful sale address _vaultAddress; // Contains list of all investor addresses address[] public _investorAddresses; // contains list of all investors with transfered amount mapping (address => uint256) _investors; // Reference to HDL token. The token is created with this contract. HDLToken public token; // Sale period start date as unix timestamp uint _start; // Sale period in days uint _period; // Sale goal in tokens - how many tokens we are planning to sel under this contract uint public _goal; // Token/ether rate uint _rate; // Total amount of issued tokens under this contract uint256 public issuedTokens; // total amount of all collected funds under this contract uint256 public collectedFunds; // Identifies whether current contract is finished. If contract is finished no more funds can be sent to this contract. // When contract has been marked as finished it cannot be restarted. bool public isFinished = false; // Identifies whether contract is in refunding mode - Refunding is opened and investors can request their funds back. bool public isRefunding = false; // Raises when particular investor is refunded event InvestorRefunded(address indexed beneficiary, uint256 weiAmount); // Raises when particular investor bought some tokens from contract event FundingAccepted(address indexed investor, uint256 weiAmount, uint tokenAmount); // Raises when all investors were refunded event AllInvestorsRefunded(uint refundedInvestorCount); // Raises when all funds have been withdrawn event WithdrawAllFunds(uint256 withdrawnAmount); // Raises when crowdsale has been finished event CrowdsaleFinished(); // Raises when crowdsale goal has been reached event GoalReached(); function HDLContract(address aVaultAddress, uint aStart, uint aPeriod, uint aGoal, uint aRate) { _ownerAddress = msg.sender; _vaultAddress = aVaultAddress; token = new HDLToken(); _rate = aRate; _start = aStart; _period = aPeriod; _goal = aGoal * 1 ether; issuedTokens = 0; collectedFunds = 0; } /** * Transfers token ownership from Pre-sale to Sale */ function TransferTokenOwnership(address newTokenOwner) public onlyOwner { token.transferOwnership(newTokenOwner); } /** * Finishes PRE-ICO crowdsale and closes current contract. * Checks is goal is reached. If it is reached then withdraws all funds to vault address * Otherwise tries to refund investors or Opens contract for refunding. * */ function finish() public onlyOwner { require(!isFinished); token.stopMinting(); isFinished = true; if (issuedTokens < _goal) { isRefunding = true; } else { withdraw(); } CrowdsaleFinished(); } /** * Refunds investor. Should be called by investors. * If contract state is in Refunding state then returns to investor sent amount. * */ function requestRefunding() public { require(isRefunding); address investorAddress = msg.sender; refundInvestor(investorAddress); } /** * Accepts ethers from investor and sends back HDL tokens. */ function buyTokens() payable { require(!isFinished); require(isContractActive()); require(!isGoalReached()); uint tokens = _rate.mul(msg.value); token.mint(this, tokens); token.transfer(msg.sender, tokens); issuedTokens = issuedTokens.add(tokens); _investors[msg.sender] = _investors[msg.sender].add(msg.value); _investorAddresses.push(msg.sender); collectedFunds = collectedFunds.add(msg.value); FundingAccepted(msg.sender, msg.value, tokens); if (issuedTokens >= _goal) { GoalReached(); } } function() external payable { buyTokens(); } function closeContract() onlyOwner { token.stopMinting(); isFinished = true; } function withdraw() onlyOwner { if (this.balance > 0) { _vaultAddress.transfer(this.balance); } WithdrawAllFunds(this.balance); } function refundInvestor(address aInvestorAddress) onlyOwner returns(bool) { if (aInvestorAddress == 0x0) { return false; } uint256 depositedValue = _investors[aInvestorAddress]; if (depositedValue <= 0) { return false; } _investors[aInvestorAddress] = 0; aInvestorAddress.transfer(depositedValue); InvestorRefunded(aInvestorAddress, depositedValue); return true; } function isContractActive() returns (bool) { return (now > _start) && (now < (_start + _period * 1 days)); } function isGoalReached() returns (bool) { return issuedTokens >= _goal; } }
Contract owner addredd Contract vault address - all collected funds are moved to this address after successful sale Contains list of all investor addresses contains list of all investors with transfered amount Reference to HDL token. The token is created with this contract. Sale period start date as unix timestamp Sale period in days Sale goal in tokens - how many tokens we are planning to sel under this contract Token/ether rate Total amount of issued tokens under this contract total amount of all collected funds under this contract Identifies whether current contract is finished. If contract is finished no more funds can be sent to this contract. When contract has been marked as finished it cannot be restarted. Identifies whether contract is in refunding mode - Refunding is opened and investors can request their funds back. Raises when particular investor is refunded Raises when particular investor bought some tokens from contract Raises when all investors were refunded Raises when all funds have been withdrawn Raises when crowdsale has been finished Raises when crowdsale goal has been reached
contract HDLContract is Ownable { using SafeMath for uint; address _ownerAddress; address _vaultAddress; address[] public _investorAddresses; mapping (address => uint256) _investors; HDLToken public token; uint _start; uint _period; uint public _goal; uint _rate; uint256 public issuedTokens; uint256 public collectedFunds; bool public isFinished = false; bool public isRefunding = false; event InvestorRefunded(address indexed beneficiary, uint256 weiAmount); event FundingAccepted(address indexed investor, uint256 weiAmount, uint tokenAmount); event AllInvestorsRefunded(uint refundedInvestorCount); event WithdrawAllFunds(uint256 withdrawnAmount); event CrowdsaleFinished(); event GoalReached(); function HDLContract(address aVaultAddress, uint aStart, uint aPeriod, uint aGoal, uint aRate) { _ownerAddress = msg.sender; _vaultAddress = aVaultAddress; token = new HDLToken(); _rate = aRate; _start = aStart; _period = aPeriod; _goal = aGoal * 1 ether; issuedTokens = 0; collectedFunds = 0; } function TransferTokenOwnership(address newTokenOwner) public onlyOwner { token.transferOwnership(newTokenOwner); } function finish() public onlyOwner { require(!isFinished); token.stopMinting(); isFinished = true; if (issuedTokens < _goal) { isRefunding = true; } else { withdraw(); } CrowdsaleFinished(); } function finish() public onlyOwner { require(!isFinished); token.stopMinting(); isFinished = true; if (issuedTokens < _goal) { isRefunding = true; } else { withdraw(); } CrowdsaleFinished(); } function finish() public onlyOwner { require(!isFinished); token.stopMinting(); isFinished = true; if (issuedTokens < _goal) { isRefunding = true; } else { withdraw(); } CrowdsaleFinished(); } function requestRefunding() public { require(isRefunding); address investorAddress = msg.sender; refundInvestor(investorAddress); } function buyTokens() payable { require(!isFinished); require(isContractActive()); require(!isGoalReached()); uint tokens = _rate.mul(msg.value); token.mint(this, tokens); token.transfer(msg.sender, tokens); issuedTokens = issuedTokens.add(tokens); _investors[msg.sender] = _investors[msg.sender].add(msg.value); _investorAddresses.push(msg.sender); collectedFunds = collectedFunds.add(msg.value); FundingAccepted(msg.sender, msg.value, tokens); if (issuedTokens >= _goal) { GoalReached(); } } function buyTokens() payable { require(!isFinished); require(isContractActive()); require(!isGoalReached()); uint tokens = _rate.mul(msg.value); token.mint(this, tokens); token.transfer(msg.sender, tokens); issuedTokens = issuedTokens.add(tokens); _investors[msg.sender] = _investors[msg.sender].add(msg.value); _investorAddresses.push(msg.sender); collectedFunds = collectedFunds.add(msg.value); FundingAccepted(msg.sender, msg.value, tokens); if (issuedTokens >= _goal) { GoalReached(); } } function() external payable { buyTokens(); } function closeContract() onlyOwner { token.stopMinting(); isFinished = true; } function withdraw() onlyOwner { if (this.balance > 0) { _vaultAddress.transfer(this.balance); } WithdrawAllFunds(this.balance); } function withdraw() onlyOwner { if (this.balance > 0) { _vaultAddress.transfer(this.balance); } WithdrawAllFunds(this.balance); } function refundInvestor(address aInvestorAddress) onlyOwner returns(bool) { if (aInvestorAddress == 0x0) { return false; } uint256 depositedValue = _investors[aInvestorAddress]; if (depositedValue <= 0) { return false; } _investors[aInvestorAddress] = 0; aInvestorAddress.transfer(depositedValue); InvestorRefunded(aInvestorAddress, depositedValue); return true; } function refundInvestor(address aInvestorAddress) onlyOwner returns(bool) { if (aInvestorAddress == 0x0) { return false; } uint256 depositedValue = _investors[aInvestorAddress]; if (depositedValue <= 0) { return false; } _investors[aInvestorAddress] = 0; aInvestorAddress.transfer(depositedValue); InvestorRefunded(aInvestorAddress, depositedValue); return true; } function refundInvestor(address aInvestorAddress) onlyOwner returns(bool) { if (aInvestorAddress == 0x0) { return false; } uint256 depositedValue = _investors[aInvestorAddress]; if (depositedValue <= 0) { return false; } _investors[aInvestorAddress] = 0; aInvestorAddress.transfer(depositedValue); InvestorRefunded(aInvestorAddress, depositedValue); return true; } function isContractActive() returns (bool) { return (now > _start) && (now < (_start + _period * 1 days)); } function isGoalReached() returns (bool) { return issuedTokens >= _goal; } }
7,233,046
[ 1, 8924, 3410, 527, 266, 449, 13456, 9229, 1758, 300, 777, 12230, 284, 19156, 854, 10456, 358, 333, 1758, 1839, 6873, 272, 5349, 8398, 666, 434, 777, 2198, 395, 280, 6138, 1914, 666, 434, 777, 2198, 395, 1383, 598, 7412, 329, 3844, 6268, 358, 670, 8914, 1147, 18, 1021, 1147, 353, 2522, 598, 333, 6835, 18, 348, 5349, 3879, 787, 1509, 487, 9753, 2858, 348, 5349, 3879, 316, 4681, 348, 5349, 17683, 316, 2430, 300, 3661, 4906, 2430, 732, 854, 886, 10903, 358, 357, 3613, 333, 6835, 3155, 19, 2437, 4993, 10710, 3844, 434, 16865, 2430, 3613, 333, 6835, 2078, 3844, 434, 777, 12230, 284, 19156, 3613, 333, 6835, 13128, 5032, 2856, 783, 6835, 353, 6708, 18, 971, 6835, 353, 6708, 1158, 1898, 284, 19156, 848, 506, 3271, 358, 333, 6835, 18, 5203, 6835, 711, 2118, 9350, 487, 6708, 518, 2780, 506, 28893, 18, 13128, 5032, 2856, 6835, 353, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 670, 8914, 8924, 353, 14223, 6914, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 202, 2867, 389, 8443, 1887, 31, 203, 203, 565, 1758, 389, 26983, 1887, 31, 203, 203, 565, 1758, 8526, 1071, 389, 5768, 395, 280, 7148, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 389, 5768, 395, 1383, 31, 203, 203, 565, 670, 8914, 1345, 1071, 1147, 31, 203, 203, 565, 2254, 389, 1937, 31, 203, 203, 565, 2254, 389, 6908, 31, 203, 203, 565, 2254, 1071, 389, 27354, 31, 203, 203, 565, 2254, 389, 5141, 31, 203, 203, 565, 2254, 5034, 1071, 16865, 5157, 31, 203, 203, 565, 2254, 5034, 1071, 12230, 42, 19156, 31, 203, 203, 565, 1426, 1071, 353, 10577, 273, 629, 31, 203, 203, 565, 1426, 1071, 353, 1957, 14351, 273, 629, 31, 203, 203, 565, 871, 5454, 395, 280, 1957, 12254, 12, 2867, 8808, 27641, 74, 14463, 814, 16, 2254, 5034, 732, 77, 6275, 1769, 203, 203, 565, 871, 478, 14351, 18047, 12, 2867, 8808, 2198, 395, 280, 16, 2254, 5034, 732, 77, 6275, 16, 2254, 1147, 6275, 1769, 203, 203, 565, 871, 4826, 3605, 395, 1383, 1957, 12254, 12, 11890, 1278, 12254, 3605, 395, 280, 1380, 1769, 203, 203, 565, 871, 3423, 9446, 1595, 42, 19156, 12, 11890, 5034, 598, 9446, 82, 6275, 1769, 203, 203, 565, 871, 385, 492, 2377, 5349, 10577, 5621, 203, 203, 565, 871, 4220, 287, 23646, 5621, 203, 203, 565, 445, 670, 8914, 8924, 12, 2867, 279, 12003, 1887, 16, 2254, 279, 2 ]
pragma solidity ^0.5.11; pragma experimental ABIEncoderV2; import "./StorageDefinition.sol"; /** * @title EternalStorage * @dev An ownable contract that can be used as a storage where the variables * are stored in a set of mappings indexed by hash names. */ contract EternalStorage is StorageDefinition { // All users User[] internal users; mapping (bytes32 => address) private _projectOwner; // Mapping between userAddress and index mapping(address => uint256) userIndex; // User Directory mapping(address => User) internal userDirectory; // Mapping between userAddress and index mapping(string => uint256) public organizationIndex; // Mapping between userAddress and index mapping(address => uint256) public orgEmployeeIndex; // Organization Directory from organizationID mapping(string => Organization) internal organizationDirectory; // All Organizations Organization[] internal organizations; // Mapping between orgID and its Users mapping(string => User[]) internal orgEmployees; // mapping between partnershipType and Organization mapping (string => Organization[]) internal partners; // mapping between Project ID and project Details mapping (bytes32 => Project) internal projectRegistry; // mapping between ProjectId and Users mapping (bytes32 => User[]) internal consortium; // mapping between userPublicKey and Projects mapping (address => Project[]) internal myProjects; // mapping between projectID and user with their roles mapping(bytes32 => mapping (address => string)) internal projectRoles; Storage internal s; mapping(address => bool) internal registeredContracts; address public owner; /** * @dev The constructor sets the original `owner` of the * contract to the sender account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Throws if called by any account other than the registeredContract. */ modifier onlyRegisteredContract() { require((registeredContracts[msg.sender])||(msg.sender==address(this))); _; } modifier sameOrganization(address a, address b) { require(compareStrings(userDirectory[a].organizationID, userDirectory[b].organizationID)); _; } function compareStrings (string memory a, string memory b) internal pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))) ); } function _exists(bytes32 projectID) internal view returns (bool) { address owner = _projectOwner[projectID]; return owner != address(0); } /** * @dev Allows the current owner to transfer control of the contract to a * newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0x0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function addRegisteredContract(address contractAddress, string calldata contractType) external onlyOwner { require(contractAddress != address(0x0)); emit ContractRegistered(contractAddress, contractType, now); if(this.getAddress(keccak256(abi.encodePacked("ContractRegistry", contractType)))!=address(0x0)){ revokeRegisteredContract(this.getAddress(keccak256(abi.encodePacked("ContractRegistry", contractType))), contractType); } this.setAddress(keccak256(abi.encodePacked("ContractRegistry", contractType)), contractAddress); registeredContracts[contractAddress] = true; } function getRegisteredContractAddress(string calldata contractType) external view onlyRegisteredContract returns (address) { return this.getAddress(keccak256(abi.encodePacked("ContractRegistry", contractType))); } function isRegisteredContract(address contractAddress) external view onlyRegisteredContract returns (bool) { return ((registeredContracts[contractAddress])||(contractAddress==address(this))); } function revokeRegisteredContract(address contractAddress, string memory contractType) internal onlyOwner { require(contractAddress != address(0x0)); emit ContractRevoked(contractAddress, contractType, now); registeredContracts[contractAddress] = false; } /** * @dev Allows the owner to set a value for a boolean variable. * @param h The keccak256 hash of the variable name * @param v The value to be stored */ function setBoolean(bytes32 h, bool v) external onlyRegisteredContract { s._bool[h] = v; } /** * @dev Allows the owner to set a value for a boolean variable. * @param h The keccak256 hash of the variable name * @param v The value to be stored */ function setUint(bytes32 h, uint256 v) external onlyRegisteredContract { s._uint[h] = v; } /** * @dev Allows the owner to set a value for a address variable. * @param h The keccak256 hash of the variable name * @param v The value to be stored */ function setAddress(bytes32 h, address v) external onlyRegisteredContract { s._address[h] = v; } /** * @dev Allows the owner to set a value for a string variable. * @param h The keccak256 hash of the variable name * @param v The value to be stored */ function setString(bytes32 h, string calldata v) external onlyRegisteredContract { s._string[h] = v; } /** * @dev Get the value stored of a boolean variable by the hash name * @param h The keccak256 hash of the variable name */ function getBoolean(bytes32 h) external view returns (bool){ return s._bool[h]; } /** * @dev Get the value stored of a uint variable by the hash name * @param h The keccak256 hash of the variable name */ function getUint(bytes32 h) external view returns (uint256){ return s._uint[h]; } /** * @dev Get the value stored of a address variable by the hash name * @param h The keccak256 hash of the variable name */ function getAddress(bytes32 h) external view returns (address){ return s._address[h]; } /** * @dev Get the value stored of a string variable by the hash name * @param h The keccak256 hash of the variable name */ function getString(bytes32 h) external view returns (string memory){ return s._string[h]; } /**** Delete Methods ***********/ /// @param _key The key for the record function deleteAddress(bytes32 _key) onlyRegisteredContract external { delete s._address[_key]; } /// @param _key The key for the record function deleteUint(bytes32 _key) onlyRegisteredContract external { delete s._uint[_key]; } /// @param _key The key for the record function deleteString(bytes32 _key) onlyRegisteredContract external { delete s._string[_key]; } /// @param _key The key for the record function deleteBool(bytes32 _key) onlyRegisteredContract external { delete s._bool[_key]; } function setUser(string calldata organizationID, string calldata email, string calldata kycHash, roles role, bool adminApprovalStatus) external onlyRegisteredContract { User memory newUser; newUser.organizationID = organizationID; newUser.email = email; newUser.role = role; newUser.publicKey = tx.origin; newUser.status = KYCStatus.kycPending; newUser.kycHash = kycHash; newUser.adminApprovalStatus=adminApprovalStatus; userIndex[tx.origin] = users.length; userDirectory[tx.origin] = newUser; users.push(newUser); orgEmployees[organizationID].push(newUser); orgEmployeeIndex[tx.origin] = orgEmployees[organizationID].length; } function deleteUser(address userAddress,string calldata organizationID) external onlyRegisteredContract { uint256 lastTokenIndex = users.length - 1 ; uint256 tokenIndex = userIndex[userAddress]; if (tokenIndex != lastTokenIndex) { User memory lastTokenId = users[lastTokenIndex]; users[tokenIndex] = lastTokenId; userIndex[lastTokenId.publicKey] = tokenIndex; } delete userDirectory[userAddress]; users.length--; this.deleteAddress(keccak256(abi.encodePacked("EmailToPKMapping", orgEmployees[organizationID][orgEmployeeIndex[userAddress]-1].email))); if( orgEmployees[organizationID][orgEmployeeIndex[userAddress]-1].role == roles.admin){ deleteOrganization(organizationID); }else{ orgEmployees[organizationID][orgEmployeeIndex[userAddress]-1].status = KYCStatus.suspended; } } function deleteOrganization(string memory organizationID) internal { uint256 lastTokenIndex = organizations.length - 1 ; uint256 tokenIndex = organizationIndex[organizationID]; if (tokenIndex != lastTokenIndex) { Organization memory lastTokenId = organizations[lastTokenIndex]; organizations[tokenIndex] = lastTokenId; organizationIndex[lastTokenId.organizationID] = tokenIndex; } organizations.length--; delete orgEmployees[organizationID]; delete organizationDirectory[organizationID]; this.deleteBool(keccak256(abi.encodePacked("organizationExists", organizationID))); } function deleteOrganizationExt(string calldata organizationID) external onlyRegisteredContract { deleteOrganization(organizationID); } function setOrganization(string calldata organizationID, string calldata name, string calldata orgKYCHash) external onlyRegisteredContract { Organization memory newOrganization; newOrganization.organizationID =organizationID; newOrganization.name = name; newOrganization.kycHash = orgKYCHash; newOrganization.status = KYCStatus.kycPending; organizationDirectory[organizationID] = newOrganization; organizationIndex[organizationID] = organizations.length; organizations.push(newOrganization); } function getAllUsers() external view onlyRegisteredContract returns (User[] memory) { return users; } function getAllOrganizations() external view onlyRegisteredContract returns (Organization[] memory) { return organizations; } function getUserDetails() external view onlyRegisteredContract returns (User memory) { return (userDirectory[tx.origin]); } function getUserDetails(address userAddress) external view onlyRegisteredContract returns (User memory) { return (userDirectory[userAddress]); } function getOrganizationDetails() external view onlyRegisteredContract returns (Organization memory) { return (organizationDirectory[userDirectory[tx.origin].organizationID]); } function getOrganizationDetails(string calldata organizationID) external view onlyRegisteredContract returns (Organization memory) { return (organizationDirectory[organizationID]); } function getOrganizationDetails(address userAddress) external view onlyRegisteredContract returns (Organization memory) { return (organizationDirectory[userDirectory[userAddress].organizationID]); } function getUserOrganizationDetails() external view onlyRegisteredContract returns (User memory, Organization memory) { return (userDirectory[tx.origin], organizationDirectory[userDirectory[tx.origin].organizationID]); } function getOrganizationEmployees(string calldata organizationID) external view returns (User[] memory) { return orgEmployees[organizationID]; } function switchOrgAdmin(address externalKey) external onlyRegisteredContract sameOrganization(tx.origin, externalKey){ userDirectory[tx.origin].role = roles.regular; userDirectory[externalKey].role = roles.admin; } function updateUserRole(address externalKey, roles newRole) external onlyRegisteredContract sameOrganization(tx.origin, externalKey) { userDirectory[externalKey].role = newRole; } // function getPartnersByType(string calldata orgType) external onlyRegisteredContract view returns (Organization[] memory) { // return partners[orgType]; // } function updateUserKYC(string calldata kycHash) external onlyRegisteredContract returns (bool) { userDirectory[tx.origin].status = KYCStatus.kycPending; userDirectory[tx.origin].kycHash = kycHash; return true; } function updateOrganizationKYC(string calldata kycHash) external onlyRegisteredContract returns (bool) { organizationDirectory[userDirectory[tx.origin].organizationID].kycHash = kycHash; } function setOrganizationKYCStatus(string calldata organizationID, KYCStatus status) external onlyRegisteredContract returns (bool) { // if(status == KYCStatus.kycComplete){ // this.setBoolean(keccak256(abi.encodePacked("organizationExists", organizationID)), true); // } organizationDirectory[organizationID].status = status; return true; } function getOrganizationKYCStatus(string calldata organizationID) external view onlyRegisteredContract returns (KYCStatus status) { return organizationDirectory[organizationID].status; } function setUserKYCStatus(address userAddress, KYCStatus status) external onlyRegisteredContract returns (bool) { // if(status == KYCStatus.kycComplete){ // this.setAddress(keccak256(abi.encodePacked("EmailToPKMapping", userDirectory[userAddress].email)), userAddress); // } userDirectory[userAddress].status = status; return true; } function getUserKYCStatus() external view onlyRegisteredContract returns (KYCStatus status) { return userDirectory[tx.origin].status; } // function confirmPartnershipStatus(string calldata organizationID, string calldata partnershipType) external onlyRegisteredContract { // partners[partnershipType].push(organizationDirectory[organizationID]); // } function addNewProject(bytes32 projectID, string calldata name, string calldata description, string calldata industry) external onlyRegisteredContract { require(!_exists(projectID), "Name already exists!"); _projectOwner[projectID] = msg.sender; Project memory project; project.projectID = projectID; project.name = name; project.description = description; project.industry = industry; project.projectAdmin = tx.origin; projectRegistry[projectID] = project; } function addUserToProject(bytes32 projectID, address userAddress, string calldata partnerRole) external onlyRegisteredContract { consortium[projectID].push(this.getUserDetails(userAddress)); myProjects[userAddress].push(projectRegistry[projectID]); projectRoles[projectID][userAddress] = partnerRole; } function removeUserToProject(bytes32 projectID, address userAddress, string calldata partnerRole) external onlyRegisteredContract { delete consortium[projectID];//.pop(this.getUserDetails(userAddress)); delete myProjects[userAddress];//.pop(projectRegistry[projectID]); delete projectRoles[projectID][userAddress]; } function getProjectDetails(bytes32 projectID) external view onlyRegisteredContract returns (Project memory) { return (projectRegistry[projectID]); } function getMyProjects() external view onlyRegisteredContract returns (Project[] memory) { return myProjects[tx.origin]; } function getMyProjectsCount() external view onlyRegisteredContract returns (uint256) { return myProjects[tx.origin].length; } function getConsortiumMembers(bytes32 projectID) external view onlyRegisteredContract returns (User[] memory) { return (consortium[projectID]); } function getPartnerRole(bytes32 projectID, address publicKey) external view returns (string memory) { return projectRoles[projectID][publicKey]; } function getPartnerRole(bytes32 projectID) external view onlyRegisteredContract returns (string memory) { return projectRoles[projectID][tx.origin]; } }
* @dev Allows the owner to set a value for a string variable. @param h The keccak256 hash of the variable name @param v The value to be stored/
function setString(bytes32 h, string calldata v) external onlyRegisteredContract { s._string[h] = v; }
12,618,549
[ 1, 19132, 326, 3410, 358, 444, 279, 460, 364, 279, 533, 2190, 18, 225, 366, 1021, 417, 24410, 581, 5034, 1651, 434, 326, 2190, 508, 225, 331, 1021, 460, 358, 506, 4041, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 14600, 12, 3890, 1578, 366, 16, 533, 745, 892, 331, 13, 3903, 1338, 10868, 8924, 288, 203, 565, 272, 6315, 1080, 63, 76, 65, 273, 331, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache pragma solidity 0.8.10; //import "hardhat/console.sol"; interface IERC20 { function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } contract ExchangeHub { struct Donation { uint256 amount_dueTime80_v8; bytes32 r; bytes32 s; } address constant private BCHAddress = 0x0000000000000000000000000000000000002711; string private constant EIP712_DOMAIN = "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"; bytes32 private constant EIP712_DOMAIN_TYPEHASH = keccak256(abi.encodePacked(EIP712_DOMAIN)); bytes32 private constant NAME_HASH = keccak256(abi.encodePacked("exchange dapp")); bytes32 private constant VERSION_HASH = keccak256(abi.encodePacked("v0.1.0")); uint256 private constant CHAINID = 10000; // smartBCH mainnet bytes32 private constant SALT = keccak256(abi.encodePacked("Exchange")); bytes32 private constant TYPE_HASH = keccak256(abi.encodePacked("Exchange(uint256 coinsToMaker,uint256 coinsToTaker,uint256 campaignID,uint256 takerAddr_dueTime80)")); uint256 private constant MUL = 10**12; // number of picoseconds in one second uint256 private constant MaxClearCount = 10; //A maker can delegate an agent to sign coin-exchanging messages for him mapping(address => address) public makerToAgent; //To prevent replay of coin-exchanging messages, we use dueTime to identify a coin-exchanging message uniquely mapping(address => mapping(uint => uint)) public makerNextRecentDueTime; //the pointers of a linked-list mapping(address => uint) public makerRDTHeadTail; //the head and tail of a linked-list //A maker and a taker exchange their coins event Exchange(address indexed maker, uint256 coinsToMaker, uint256 coinsToTaker, uint256 takerAddr_dueTime80); //The following events are used in crowdfunding campaign event CampaignStart(uint256 indexed campaignID, uint256 takerAddr_startEndTime, uint256 totalCoinsToTaker, bytes32 introHash, bytes intro); event CampaignSuccess(uint256 indexed campaignID); event Donate(uint256 indexed campaignID, uint256 donatorAddr_timestamp, uint256 amount_dueTime80_v8, bytes32 r, bytes32 s, string words); function getEIP712Hash(uint256 coinsToMaker, uint256 coinsToTaker, uint256 campaignID, uint256 takerAddr_dueTime80) public view returns (bytes32) { bytes32 DOMAIN_SEPARATOR = keccak256(abi.encode( EIP712_DOMAIN_TYPEHASH, NAME_HASH, VERSION_HASH, CHAINID, address(this), SALT)); return keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode( TYPE_HASH, coinsToMaker, coinsToTaker, campaignID, takerAddr_dueTime80 )) )); } function getSigner(uint256 coinsToMaker, uint256 coinsToTaker, uint256 campaignID, uint256 takerAddr_dueTime80_v8, bytes32 r, bytes32 s) public view returns (address) { bytes32 eip712Hash = getEIP712Hash(coinsToMaker, coinsToTaker, campaignID, takerAddr_dueTime80_v8>>8); uint8 v = uint8(takerAddr_dueTime80_v8); //the lowest byte is v return ecrecover(eip712Hash, v, r, s); } //Returns recent recorded dueTimes of a maker function getRecentDueTimes(address makerAddr, uint maxCount) external view returns (uint[] memory) { uint head = makerRDTHeadTail[makerAddr]>>80; uint[] memory recentDueTimes = new uint[](maxCount); for(uint i=0; i<maxCount && head != 0; i++) { recentDueTimes[i] = head; head = makerNextRecentDueTime[makerAddr][head]; } return recentDueTimes; } //By adding a new dueTime entry in the linked-list, we can revoke a coin-exchanging message function addNewDueTime(uint newDueTime) external { require(newDueTime != 0, "invalid dueTime"); uint currTime = block.timestamp*MUL; clearOldDueTimesAndInsertNew(msg.sender, newDueTime, currTime); } //Delete some useless entries from the linked list function clearOldDueTimes(uint maxCount, address makerAddr) external { uint currTime = block.timestamp*MUL; uint headTail = makerRDTHeadTail[makerAddr]; (uint head, uint tail) = (headTail>>80, uint(uint80(headTail))); (head, tail) = _clearOldDueTimes(maxCount, makerAddr, currTime, head, tail); makerRDTHeadTail[makerAddr] = (head<<80) | tail; } //If a message's dueTime was recorded in the linked-list before, it is a replay and can't take effect function isReplay(address makerAddr, uint dueTime) external view returns (bool) { uint tail = uint80(makerRDTHeadTail[makerAddr]); return tail == dueTime || makerNextRecentDueTime[makerAddr][dueTime] != 0; } //Delete some useless entries from the linked list and insert a new one function clearOldDueTimesAndInsertNew(address makerAddr, uint newDueTime, uint currTime) private { uint headTail = makerRDTHeadTail[makerAddr]; (uint head, uint tail) = (headTail>>80, uint(uint80(headTail))); require(tail != newDueTime && makerNextRecentDueTime[makerAddr][newDueTime] == 0, "dueTime not new"); (head, tail) = _clearOldDueTimes(MaxClearCount, makerAddr, currTime, head, tail); (head, tail) = _addNewDueTime(makerAddr, newDueTime, head, tail); makerRDTHeadTail[makerAddr] = (head<<80) | tail; } // The linked-list: // No entries in queue: head = 0, tail = 0 // One entry in queue: head = dueTime, tail = dueTime // Two entries in queue: head = A, tail = B, makerNextRecentDueTime[makerAddr][A] = B function _clearOldDueTimes(uint maxCount, address makerAddr, uint currTime, uint head, uint tail) private returns (uint, uint) { for(uint i=0; i<maxCount && head<currTime && head!=0; i++) { uint newHead = makerNextRecentDueTime[makerAddr][head]; makerNextRecentDueTime[makerAddr][head] = 0; head = newHead; } if(head == 0) { tail = 0; } return (head, tail); } function _addNewDueTime(address makerAddr, uint dueTime, uint head, uint tail) private returns (uint, uint) { if(head == 0) { return (dueTime, dueTime); } makerNextRecentDueTime[makerAddr][tail] = dueTime; return (head, dueTime); } function setMakerAgent(address agent) external { makerToAgent[msg.sender] = agent; } // A taker exchanges with a maker, using a message signature generated by the maker's agent // This function is used by https://hongbao.click function exchangeWithAgentSig(uint256 coinsToMaker, uint256 coinsToTaker, uint256 takerAddr_dueTime80_v8, address makerAddr, bytes32 r, bytes32 s) payable external { _exchange(coinsToMaker, coinsToTaker, takerAddr_dueTime80_v8, makerAddr, r, s); } // A taker exchanges with a maker, using a message signature generated by the maker // This function is used by https://orders.cash function exchange(uint256 coinsToMaker, uint256 coinsToTaker, uint256 takerAddr_dueTime80_v8, bytes32 r, bytes32 s) payable external { _exchange(coinsToMaker, coinsToTaker, takerAddr_dueTime80_v8, address(0), r, s); } function _exchange(uint256 coinsToMaker, uint256 coinsToTaker, uint256 takerAddr_dueTime80_v8, address makerAddr, bytes32 r, bytes32 s) private { uint dueTime = uint80(takerAddr_dueTime80_v8>>8); uint currTime = block.timestamp*MUL; require(currTime < dueTime, "too late"); if(makerAddr == address(0)) { //called by "exchange" makerAddr = getSigner(coinsToMaker, coinsToTaker, uint(uint160(0)), takerAddr_dueTime80_v8, r, s); } else { //called by "exchangeWithAgentSig" address agentAddr = getSigner(coinsToMaker, coinsToTaker, uint(uint160(makerAddr)), takerAddr_dueTime80_v8, r, s); require(makerToAgent[makerAddr] == agentAddr, "invalid agent"); } clearOldDueTimesAndInsertNew(makerAddr, dueTime, currTime); address takerAddr = address(bytes20(uint160(takerAddr_dueTime80_v8>>(80+8)))); if(takerAddr == address(0)) { //if taker is not specified, anyone sending tx can be the taker takerAddr = msg.sender; } address coinTypeToMaker = address(bytes20(uint160(coinsToMaker>>96))); uint coinAmountToMaker = uint(uint96(coinsToMaker)); address coinTypeToTaker = address(bytes20(uint160(coinsToTaker>>96))); uint coinAmountToTaker = uint(uint96(coinsToTaker)); emit Exchange(makerAddr, coinsToMaker, coinsToTaker, takerAddr_dueTime80_v8>>8); if(coinAmountToTaker != 0) { (bool success, bytes memory _notUsed) = coinTypeToTaker.call( abi.encodeWithSignature("transferFrom(address,address,uint256)", makerAddr, takerAddr, coinAmountToTaker)); require(success, "transferFrom fail"); } if(coinAmountToMaker != 0) { if(coinTypeToMaker == BCHAddress) { require(msg.value == coinAmountToMaker, "bch not enough"); (bool success, bytes memory _notUsed) = makerAddr.call{gas: 9000, value: coinAmountToMaker}(""); require(success, "transfer fail"); } else { require(msg.value == 0, "no need for bch"); IERC20(coinTypeToMaker).transferFrom(takerAddr, makerAddr, coinAmountToMaker); } } } // The following functions are used by https://starter.money // Handle the donation from a supporter(maker) for a crowdfund campaign, by transferring coins from the maker // to the campaign's beneficiary(taker). function handleDonation(Donation calldata donation, uint currTime, address coinTypeToTaker, uint campaignID, address takerAddr) private returns (uint) { uint dueTime = uint80(donation.amount_dueTime80_v8>>8); require(currTime < dueTime, "too late"); uint coinsToTaker; uint takerAddr_dueTime80_v8; { uint amount = donation.amount_dueTime80_v8>>88; coinsToTaker = (uint(uint160(coinTypeToTaker))<<96) + amount; uint dueTime80_v8 = uint88(donation.amount_dueTime80_v8); takerAddr_dueTime80_v8 = (uint(uint160(takerAddr))<<88) + dueTime80_v8; } address makerAddr = getSigner(0/*zero coinsToMaker*/, coinsToTaker, campaignID, takerAddr_dueTime80_v8, donation.r, donation.s); clearOldDueTimesAndInsertNew(makerAddr, dueTime, currTime); uint amount = donation.amount_dueTime80_v8>>88; (bool success, bytes memory _notUsed) = coinTypeToTaker.call( abi.encodeWithSignature("transferFrom(address,address,uint256)", makerAddr, takerAddr, amount)); require(success, "transferFrom fail"); return amount; } // When the coins from "donations" are enough, the taker accepts all the donations. function endCampaign(uint takerAddr_startEndTime, uint totalCoinsToTaker, bytes32 introHash, Donation[] calldata donations) external { uint currTime = block.timestamp*MUL; address coinTypeToTaker = address(uint160(totalCoinsToTaker>>96)); uint campaignID = uint(keccak256(abi.encodePacked( takerAddr_startEndTime, totalCoinsToTaker, introHash))); address takerAddr = address(uint160(takerAddr_startEndTime>>96)); require(msg.sender == takerAddr, "not taker"); uint endTime = uint(uint48(takerAddr_startEndTime)); require(block.timestamp < endTime, "after deadline"); uint sumAmount = 0; for(uint i=0; i<donations.length; i++) { sumAmount += handleDonation(donations[i], currTime, coinTypeToTaker, campaignID, takerAddr); } uint totalAmount = uint(uint96(totalCoinsToTaker)); require(sumAmount >= totalAmount, "donation not enough"); emit CampaignSuccess(campaignID); } // Start a crowdfunding campaign by submitting its basic information onto the chain function startCampaign(uint48 endTime, uint totalCoinsToTaker, bytes calldata intro) external { uint takerAddr_startEndTime = (uint(uint160(msg.sender))<<96) + (block.timestamp<<48) + uint(endTime); bytes32 introHash = keccak256(intro); uint campaignID = uint(keccak256(abi.encodePacked( takerAddr_startEndTime, totalCoinsToTaker, introHash))); emit CampaignStart(campaignID, takerAddr_startEndTime, totalCoinsToTaker, introHash, intro); } // Offer a donation by submitting the signature of a coin-exchanging message onto the chain // Note that coins are not locked or transferred here. function donate(uint campaignID, uint256 amount_dueTime80_v8, bytes32 r, bytes32 s, string calldata words) external { uint donatorAddr_timestamp = (uint(uint160(msg.sender))<<64)|block.timestamp; emit Donate(campaignID, donatorAddr_timestamp, amount_dueTime80_v8, r, s, words); } }
the lowest byte is v
uint8 v = uint8(takerAddr_dueTime80_v8);
13,012,502
[ 1, 5787, 11981, 1160, 353, 331, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 202, 11890, 28, 331, 273, 2254, 28, 12, 88, 6388, 3178, 67, 24334, 950, 3672, 67, 90, 28, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "../interfaces/IInflow1155BC.sol"; contract Splitter is Ownable { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; event PayeeAdded(address account, uint256 shares_); event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); IERC20 private _collateral; uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; EnumerableSet.AddressSet private _payees; constructor( address collateral, address[] memory payees, uint256[] memory shares_ ) { require( payees.length == shares_.length, "Splitter: payees and shares length mismatch" ); require(payees.length > 0, "Splitter: no payees"); _collateral = IERC20(collateral); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } receive() external payable {} //////////////////////// /// PUBLIC FUNCTIONS /// //////////////////////// /// @dev Triggers a transfer to `account` of the amount of token they are owed, according to their percentage of the total shares and their previous withdrawals. /// @param account (address): Payee's address function release(address account) public { require(_shares[account] > 0, "Splitter: account has no shares"); IERC20 collateral = _collateral; uint256 totalReceived = collateral.balanceOf(address(this)) + _totalReleased; uint256 payment = (totalReceived * _shares[account]) / _totalShares - _released[account]; require(payment != 0, "Splitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; collateral.safeTransfer(account, payment); emit PaymentReleased(account, payment); } /// @dev Batch triggers transfers to `payees` of the amount of token they are owed, according to their percentage of the total shares and their previous withdrawals. /// @notice All payees must have shares or transaction will revert /// @param payees (address[] memory): Payees' addresses function batchRelease(address[] memory payees) public { for (uint256 i = 0; i < payees.length; i++) { release(payees[i]); } } /// @dev Update royalty account for Inflow1155BC contract, which implements raribleV2 royalties /// @param inflow1155BC (address): Inflow1155BC contract address /// @param tokenId (uint256): Numeric identifier of token /// @param account (address): New royalty account's address function updateRoyaltyAccount( address inflow1155BC, uint256 tokenId, address account ) public onlyOwner { IInflow1155BC(inflow1155BC).updateRoyaltyAccount( tokenId, address(this), account ); } /////////////////////////////// /// PUBLIC GETTER FUNCTIONS /// /////////////////////////////// /// @dev Getter for the total shares held by payees function totalShares() public view returns (uint256) { return _totalShares; } /// @dev Getter for the total amount of Ether already released function totalReleased() public view returns (uint256) { return _totalReleased; } /// @dev Getter for the amount of shares held by an account function shares(address account) public view returns (uint256) { return _shares[account]; } /// @dev Getter for the amount of Ether already released to a account function released(address account) public view returns (uint256) { return _released[account]; } /// @dev Getter for the address of the payee number `idx` function payee(uint256 idx) public view returns (address) { return _payees.at(idx); } ////////////////////////// /// INTERNAL FUNCTIONS /// ////////////////////////// /// @dev Add a new payee to the contract. /// @param account The address of the payee to add. /// @param shares_ The number of shares owned by the account function _addPayee(address account, uint256 shares_) private { require(account != address(0), "Splitter: account is the zero address"); require(shares_ > 0, "Splitter: shares are 0"); require(_shares[account] == 0, "Splitter: account already has shares"); _payees.add(account); _shares[account] = shares_; _totalShares += shares_; emit PayeeAdded(account, shares_); } }
@dev Add a new payee to the contract. @param account The address of the payee to add. @param shares_ The number of shares owned by the account
function _addPayee(address account, uint256 shares_) private { require(account != address(0), "Splitter: account is the zero address"); require(shares_ > 0, "Splitter: shares are 0"); require(_shares[account] == 0, "Splitter: account already has shares"); _payees.add(account); _shares[account] = shares_; _totalShares += shares_; emit PayeeAdded(account, shares_); }
12,826,898
[ 1, 986, 279, 394, 8843, 1340, 358, 326, 6835, 18, 225, 2236, 1021, 1758, 434, 326, 8843, 1340, 358, 527, 18, 225, 24123, 67, 1021, 1300, 434, 24123, 16199, 635, 326, 2236, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 1289, 9148, 1340, 12, 2867, 2236, 16, 2254, 5034, 24123, 67, 13, 3238, 288, 203, 565, 2583, 12, 4631, 480, 1758, 12, 20, 3631, 315, 26738, 30, 2236, 353, 326, 3634, 1758, 8863, 203, 565, 2583, 12, 30720, 67, 405, 374, 16, 315, 26738, 30, 24123, 854, 374, 8863, 203, 565, 2583, 24899, 30720, 63, 4631, 65, 422, 374, 16, 315, 26738, 30, 2236, 1818, 711, 24123, 8863, 203, 565, 389, 10239, 25521, 18, 1289, 12, 4631, 1769, 203, 565, 389, 30720, 63, 4631, 65, 273, 24123, 67, 31, 203, 565, 389, 4963, 24051, 1011, 24123, 67, 31, 203, 565, 3626, 13838, 1340, 8602, 12, 4631, 16, 24123, 67, 1769, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.25; /** .----------------. .----------------. .----------------. .----------------. | .--------------. || .--------------. || .--------------. || .--------------. | | | ____ ____ | || | ____ | || | _____ | || | ________ | | | | |_ || _| | || | .' `. | || | |_ _| | || | |_ ___ `. | | | | | |__| | | || | / .--. \ | || | | | | || | | | `. \ | | | | | __ | | || | | | | | | || | | | _ | || | | | | | | | | | _| | | |_ | || | \ `--' / | || | _| |__/ | | || | _| |___.' / | | | | |____||____| | || | `.____.' | || | |________| | || | |________.' | | | | | || | | || | | || | | | | '--------------' || '--------------' || '--------------' || '--------------' | '----------------' '----------------' '----------------' '----------------' */ ///// Version 6.4 ///// //// Contract 01 contract EthereumSmartContract { address EthereumNodes; constructor() public { EthereumNodes = msg.sender; } modifier restricted() { require(msg.sender == EthereumNodes); _; } function GetEthereumNodes() public view returns (address owner) { return EthereumNodes; } } //// Contract 02 contract ldoh is EthereumSmartContract { event onReturnAll(uint256 returned); // Delete event onUnlockedTokens(uint256 returned); event onCashbackCode(address indexed hodler, address cashbackcode); event onStoreProfileHash(address indexed hodler, string profileHashed); event onAddContractAddress(address indexed contracthodler, bool contractstatus, uint256 _maxcontribution); event onHodlTokens(address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 endtime); event onClaimTokens(address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 endtime); event onAffiliateBonus(address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 endtime); // Variables address internal AXPRtoken; //ABCDtoken; // Delete address internal DefaultToken; // Struct Database struct Safe { uint256 id; // 01 -- > Registration Number uint256 amount; // 02 -- > Total amount of contribution to this transaction uint256 endtime; // 03 -- > The Expiration Of A Hold Platform Based On Unix Time address user; // 04 -- > The ETH address that you are using address tokenAddress; // 05 -- > The Token Contract Address That You Are Using string tokenSymbol; // 06 -- > The Token Symbol That You Are Using uint256 amountbalance; // 07 -- > 88% from Contribution / 72% Without Cashback uint256 cashbackbalance; // 08 -- > 16% from Contribution / 0% Without Cashback uint256 lasttime; // 09 -- > The Last Time You Withdraw Based On Unix Time uint256 percentage; // 10 -- > The percentage of tokens that are unlocked every month ( Default = 3% ) uint256 percentagereceive; // 11 -- > The Percentage You Have Received uint256 tokenreceive; // 12 -- > The Number Of Tokens You Have Received uint256 lastwithdraw; // 13 -- > The Last Amount You Withdraw address referrer; // 14 -- > Your ETH referrer address } // Uint256 uint256 public percent = 1200; // 01 -- > Monthly Unlock Percentage (Default 3%) uint256 private constant affiliate = 12; // 02 -- > Affiliate Bonus = 12% Of Total Contributions uint256 private constant cashback = 16; // 03 -- > Cashback Bonus = 16% Of Total Contributions uint256 private constant nocashback = 28; // 04 -- > Total % loss amount if you don't get cashback uint256 private constant totalreceive = 88; // 05 -- > The total amount you will receive uint256 private constant seconds30days = 2592000; // 06 -- > Number Of Seconds In One Month uint256 public hodlingTime; // 07 -- > Length of hold time in seconds uint256 private _currentIndex; // 08 -- > ID number ( Start from 500 ) //IDNumber uint256 public _countSafes; // 09 -- > Total Smart Contract User //TotalUser // Mapping mapping(address => bool) public contractaddress; // 01 -- > Contract Address mapping(address => address) public cashbackcode; // 02 -- > Cashback Code mapping(address => uint256) public _totalSaved; // 03 -- > Token Balance //TokenBalance mapping(address => uint256[]) public _userSafes; // 04 -- > Search ID by Address //IDAddress mapping(address => uint256) private EthereumVault; // 05 -- > Reserve Funds mapping(uint256 => Safe) private _safes; // 06 -- > Struct safe database mapping(address => uint256) public maxcontribution; // 07 -- > Maximum Contribution //N mapping(address => uint256) public AllContribution; // 08 -- > Deposit amount for all members //N mapping(address => uint256) public AllPayments; // 09 -- > Withdraw amount for all members //N mapping(address => string) public ContractSymbol; // 10 -- > Contract Address Symbol //N mapping(address => address[]) public afflist; // 11 -- > Affiliate List by ID //N // Double Mapping mapping (address => mapping (address => uint256)) public LifetimeContribution; // 01 -- > Total Deposit Amount Based On Address & Token //N mapping (address => mapping (address => uint256)) public LifetimePayments; // 02 -- > Total Withdraw Amount Based On Address & Token //N mapping (address => mapping (address => uint256)) public Affiliatevault; // 02 -- > Affiliate Balance That Hasn't Been Withdrawn //N mapping (address => mapping (address => uint256)) public Affiliateprofit; // 03 -- > The Amount Of Profit As An Affiliate //N address[] public _listedReserves; // Delete //Constructor constructor() public { AXPRtoken = 0xC39E626A04C5971D770e319760D7926502975e47; DefaultToken = 0xA15C7Ebe1f07CaF6bFF097D8a589fb8AC49Ae5B3; hodlingTime = 730 days; _currentIndex = 500; } ////////////////////////////////// Available For Everyone ////////////////////////////////// //// Function 01 - Fallback Function To Receive Donation In Eth function () public payable { require(msg.value > 0); EthereumVault[0x0] = add(EthereumVault[0x0], msg.value); } //// Function 02 - Contribute (Hodl Platform) function HodlTokens(address tokenAddress, uint256 amount) public { require(tokenAddress != 0x0); require(amount > 0 && amount <= maxcontribution[tokenAddress] ); if (contractaddress[tokenAddress] == false) { revert(); } else { ERC20Interface token = ERC20Interface(tokenAddress); require(token.transferFrom(msg.sender, address(this), amount)); uint256 affiliatecomission = div(mul(amount, affiliate), 100); uint256 no_cashback = div(mul(amount, nocashback), 100); if (cashbackcode[msg.sender] == 0 ) { uint256 data_amountbalance = div(mul(amount, 72), 100); uint256 data_cashbackbalance = 0; address data_referrer = EthereumNodes; cashbackcode[msg.sender] = EthereumNodes; emit onCashbackCode(msg.sender, EthereumNodes); EthereumVault[tokenAddress] = add(EthereumVault[tokenAddress], no_cashback); } else { data_amountbalance = sub(amount, affiliatecomission); data_cashbackbalance = div(mul(amount, cashback), 100); data_referrer = cashbackcode[msg.sender]; uint256 referrer_contribution = LifetimeContribution[data_referrer][tokenAddress]; if (referrer_contribution >= amount) { Affiliatevault[data_referrer][tokenAddress] = add(Affiliatevault[data_referrer][tokenAddress], affiliatecomission); Affiliateprofit[data_referrer][tokenAddress] = add(Affiliateprofit[data_referrer][tokenAddress], affiliatecomission); } else { uint256 Newbie = div(mul(referrer_contribution, affiliate), 100); Affiliatevault[data_referrer][tokenAddress] = add(Affiliatevault[data_referrer][tokenAddress], Newbie); Affiliateprofit[data_referrer][tokenAddress] = add(Affiliateprofit[data_referrer][tokenAddress], Newbie); uint256 data_unusedfunds = sub(affiliatecomission, Newbie); EthereumVault[tokenAddress] = add(EthereumVault[tokenAddress], data_unusedfunds); } } // Insert to Database afflist[data_referrer].push(msg.sender); _userSafes[msg.sender].push(_currentIndex); _safes[_currentIndex] = Safe( _currentIndex, amount, now + hodlingTime, msg.sender, tokenAddress, token.symbol(), data_amountbalance, data_cashbackbalance, now, percent, 0, 0, 0, data_referrer); LifetimeContribution[msg.sender][tokenAddress] = add(LifetimeContribution[msg.sender][tokenAddress], amount); // Update AllContribution, _totalSaved, _currentIndex, _countSafes AllContribution[tokenAddress] = add(AllContribution[tokenAddress], amount); _totalSaved[tokenAddress] = add(_totalSaved[tokenAddress], amount); _currentIndex++; _countSafes++; emit onHodlTokens(msg.sender, tokenAddress, token.symbol(), amount, now + hodlingTime); } } //// Function 03 - Claim Token That Has Been Unlocked function ClaimTokens(address tokenAddress, uint256 id) public { require(tokenAddress != 0x0); require(id != 0); Safe storage s = _safes[id]; require(s.user == msg.sender); if (s.amountbalance == 0) { revert(); } else { UnlockToken(tokenAddress, id); } } function UnlockToken(address tokenAddress, uint256 id) private { Safe storage s = _safes[id]; require(s.id != 0); require(s.tokenAddress == tokenAddress); uint256 eventAmount; address eventTokenAddress = s.tokenAddress; string memory eventTokenSymbol = s.tokenSymbol; if(s.endtime < now) // Hodl Complete { PayToken(s.user, s.tokenAddress, s.amountbalance); eventAmount = s.amountbalance; _totalSaved[s.tokenAddress] = sub(_totalSaved[s.tokenAddress], s.amountbalance); // * s.lastwithdraw = s.amountbalance; s.amountbalance = 0; s.lasttime = now; s.tokenreceive = div(mul(s.amount, totalreceive), 100) ; s.percentagereceive = mul(mul(88, 100), 100000000000000000000) ; emit onClaimTokens(msg.sender, eventTokenAddress, eventTokenSymbol, eventAmount, now); } else { UpdateUserData1(s.tokenAddress, s.id); } } function UpdateUserData1(address tokenAddress, uint256 id) private { Safe storage s = _safes[id]; require(s.id != 0); require(s.tokenAddress == tokenAddress); uint256 timeframe = sub(now, s.lasttime); uint256 CalculateWithdraw = div(mul(div(mul(s.amount, s.percentage), 100), timeframe), seconds30days); // uint256 CalculateWithdraw = s.amount * s.percentage / 100 * timeframe / seconds30days ; uint256 MaxWithdraw = div(s.amount, 10); // Maximum withdraw before unlocked, Max 10% Accumulation if (CalculateWithdraw > MaxWithdraw) { uint256 MaxAccumulation = MaxWithdraw; } else { MaxAccumulation = CalculateWithdraw; } // Maximum withdraw = User Amount Balance if (MaxAccumulation > s.amountbalance) { uint256 realAmount1 = s.amountbalance; } else { realAmount1 = MaxAccumulation; } // Including Cashback In The First Contribution uint256 amountbalance72 = div(mul(s.amount, 72), 100); if (s.amountbalance >= amountbalance72) { uint256 realAmount = add(realAmount1, s.cashbackbalance); } else { realAmount = realAmount1; } ////////// s.lastwithdraw = realAmount; uint256 newamountbalance = sub(s.amountbalance, realAmount); UpdateUserData2(tokenAddress, id, newamountbalance, realAmount); } function UpdateUserData2(address tokenAddress, uint256 id, uint256 newamountbalance, uint256 realAmount) private { Safe storage s = _safes[id]; require(s.id != 0); require(s.tokenAddress == tokenAddress); uint256 eventAmount; address eventTokenAddress = s.tokenAddress; string memory eventTokenSymbol = s.tokenSymbol; s.amountbalance = newamountbalance; s.lasttime = now; uint256 tokenaffiliate = div(mul(s.amount, affiliate), 100) ; uint256 maxcashback = div(mul(s.amount, cashback), 100) ; uint256 tokenreceived = sub(add(sub(sub(s.amount, tokenaffiliate), newamountbalance), s.cashbackbalance), maxcashback) ; // uint256 tokenreceived = s.amount - tokenaffiliate - newamountbalance + s.cashbackbalance - maxcashback ; // Cashback = 100 - 12 - 88 + 16 - 16 = 0 ----> No_Cashback = 100 - 12 - 72 + 0 - 16 = 1 uint256 percentagereceived = div(mul(tokenreceived, 100000000000000000000), s.amount) ; s.tokenreceive = tokenreceived; s.percentagereceive = percentagereceived; _totalSaved[s.tokenAddress] = sub(_totalSaved[s.tokenAddress], realAmount); PayToken(s.user, s.tokenAddress, realAmount); eventAmount = realAmount; emit onClaimTokens(msg.sender, eventTokenAddress, eventTokenSymbol, eventAmount, now); } function PayToken(address user, address tokenAddress, uint256 amount) private { AllPayments[tokenAddress] = add(AllPayments[tokenAddress], amount); LifetimePayments[msg.sender][tokenAddress] = add(LifetimePayments[user][tokenAddress], amount); ERC20Interface token = ERC20Interface(tokenAddress); require(token.balanceOf(address(this)) >= amount); token.transfer(user, amount); } //// Function 04 - Get How Many Contribute ? function GetUserSafesLength(address hodler) public view returns (uint256 length) { return _userSafes[hodler].length; } //// Function 05 - Get How Many Affiliate ? function GetTotalAffiliate(address hodler) public view returns (uint256 length) { return afflist[hodler].length; } //// Function 06 - Get complete data from each user function GetSafe(uint256 _id) public view returns (uint256 id, address user, address tokenAddress, uint256 amount, uint256 endtime, string tokenSymbol, uint256 amountbalance, uint256 lasttime, uint256 percentage, uint256 percentagereceive, uint256 tokenreceive, address referrer) { Safe storage s = _safes[_id]; return(s.id, s.user, s.tokenAddress, s.amount, s.endtime, s.tokenSymbol, s.amountbalance, s.lasttime, s.percentage, s.percentagereceive, s.tokenreceive, s.referrer); } //// Function 07 - Get Tokens Reserved For Ethereum Vault function GetTokenReserve(address tokenAddress) public view returns (uint256 amount) { return EthereumVault[tokenAddress]; } //// Function 08 - Get Ethereum Contract's Balance function GetContractBalance() public view returns(uint256) { return address(this).balance; } //// Function 09 - Cashback Code function CashbackCode(address _cashbackcode) public { require(_cashbackcode != msg.sender); if (cashbackcode[msg.sender] == 0) { cashbackcode[msg.sender] = _cashbackcode; emit onCashbackCode(msg.sender, _cashbackcode); } } //// Function 10 - Withdraw Affiliate Bonus function WithdrawAffiliate(address user, address tokenAddress) public { require(tokenAddress != 0x0); require(user == msg.sender); require(Affiliatevault[user][tokenAddress] > 0 ); uint256 amount = Affiliatevault[msg.sender][tokenAddress]; _totalSaved[tokenAddress] = sub(_totalSaved[tokenAddress], amount); AllPayments[tokenAddress] = add(AllPayments[tokenAddress], amount); uint256 eventAmount = amount; address eventTokenAddress = tokenAddress; string memory eventTokenSymbol = ContractSymbol[tokenAddress]; Affiliatevault[msg.sender][tokenAddress] = 0; ERC20Interface token = ERC20Interface(tokenAddress); require(token.balanceOf(address(this)) >= amount); token.transfer(user, amount); emit onClaimTokens(msg.sender, eventTokenAddress, eventTokenSymbol, eventAmount, now); } //// Function 11 - Get User's Any Token Balance function GetHodlTokensBalance(address tokenAddress) public view returns (uint256 balance) { require(tokenAddress != 0x0); for(uint256 i = 1; i < _currentIndex; i++) { Safe storage s = _safes[i]; if(s.user == msg.sender && s.tokenAddress == tokenAddress) balance += s.amount; } return balance; } ////////////////////////////////// restricted ////////////////////////////////// //// 01 Add Contract Address function AddContractAddress(address tokenAddress, bool contractstatus, uint256 _maxcontribution, string _ContractSymbol) public restricted { contractaddress[tokenAddress] = contractstatus; ContractSymbol[tokenAddress] = _ContractSymbol; maxcontribution[tokenAddress] = _maxcontribution; if (tokenAddress == DefaultToken && contractstatus == false) { contractaddress[tokenAddress] = true; } emit onAddContractAddress(tokenAddress, contractstatus, _maxcontribution); } //// 02 - Add Maximum Contribution function AddMaxContribution(address tokenAddress, uint256 _maxcontribution) public restricted { maxcontribution[tokenAddress] = _maxcontribution; } //// 03 - Unlock Tokens function UnlockTokens(address tokenAddress, uint256 id) public restricted { require(tokenAddress != 0x0); require(id != 0); UnlockToken(tokenAddress, id); } //// 04 Change Hodling Time function ChangeHodlingTime(uint256 newHodlingDays) restricted public { require(newHodlingDays >= 180); hodlingTime = newHodlingDays * 1 days; } //// 05 - Change Speed Distribution function ChangeSpeedDistribution(uint256 newSpeed) restricted public { require(newSpeed >= 3 && newSpeed <= 12); percent = newSpeed; } //// 06 - Withdraw Ethereum Received Through Fallback Function function WithdrawEth(uint256 amount) restricted public { require(amount > 0); require(address(this).balance >= amount); msg.sender.transfer(amount); } //// 07 Ethereum Nodes Fees function EthereumNodesFees(address tokenAddress) restricted public { require(EthereumVault[tokenAddress] > 0); uint256 amount = EthereumVault[tokenAddress]; _totalSaved[tokenAddress] = sub(_totalSaved[tokenAddress], amount); EthereumVault[tokenAddress] = 0; ERC20Interface token = ERC20Interface(tokenAddress); require(token.balanceOf(address(this)) >= amount); token.transfer(msg.sender, amount); } //// 08 - Return All Tokens To Their Respective Addresses function ReturnAllTokens(bool onlyAXPR) restricted public { uint256 returned; for(uint256 i = 1; i < _currentIndex; i++) { Safe storage s = _safes[i]; if (s.id != 0) { if ( (onlyAXPR && s.tokenAddress == AXPRtoken) || !onlyAXPR ) { PayToken(s.user, s.tokenAddress, s.amountbalance); s.lastwithdraw = s.amountbalance; s.amountbalance = 0; s.lasttime = now; s.percentagereceive = sub(add(totalreceive, s.cashbackbalance), 16); s.tokenreceive = div(mul(s.amount, s.percentagereceive ), 100); _totalSaved[s.tokenAddress] = 0; _countSafes--; returned++; } } } emit onReturnAll(returned); } //// 09 - Send All Tokens That Have Been Unlocked function SendUnlockedTokens(bool onlyDefault) restricted public { uint256 returned; for(uint256 i = 1; i < _currentIndex; i++) { Safe storage s = _safes[i]; if (s.id != 0) { if ( (onlyDefault && s.tokenAddress == AXPRtoken) || !onlyDefault ) { UpdateUserData1(s.tokenAddress, s.id); } } } emit onUnlockedTokens(returned); } // SAFE MATH FUNCTIONS // function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } contract ERC20Interface { uint256 public totalSupply; uint256 public decimals; function symbol() public view returns (string); function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
07 -- > Maximum Contribution N
mapping(address => uint256) public maxcontribution;
2,562,570
[ 1, 8642, 1493, 405, 18848, 735, 4027, 6862, 202, 50, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 6770, 12, 2867, 516, 2254, 5034, 13, 3196, 202, 482, 943, 591, 4027, 31, 3196, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; // import "@openzeppelin/contracts/utils/Counters.sol"; // import { Base64 } from "base64-sol/base64.sol"; import { RxStructs } from "./libraries/RxStructs.sol"; import { TokenURIDescriptor } from "./libraries/TokenURIDescriptor.sol"; /// @title A NFT Prescription creator /// @author Matias Parij (@7i7o) /// @notice You can use this contract only as a MVP for minting Prescriptions /// @dev Features such as workplaces for doctors or pharmacists are for future iterations contract Rx is ERC721, ERC721URIStorage, ERC721Burnable, AccessControl { /// @notice Role definition for Minter bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); /// @notice Role definition for Minter bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); /// @notice Role definition for Burner bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); /** Begin of State Variables & Events */ // uint8 internal constant MAX_KEY_LENGTH = 20; // uint8 internal constant MAX_VALUE_LENGTH = 62; uint8 internal constant RX_LINES = 12; // Has to be same value as in RxStructs !!! bool private selfGrantAdmin = false; /// @notice TokenId enumeration (start at '1'). uint256 private _tokenIdCounter; /// @notice this mapping holds all the subjects registered in the contract mapping ( address => RxStructs.Subject ) private subjects; /// @notice this mapping holds all the doctors registered in the contract mapping ( address => RxStructs.Doctor ) private doctors; /// @notice this mapping holds all the pharmacists registered in the contract mapping ( address => RxStructs.Pharmacist ) private pharmacists; /// @notice this mapping holds all the prescriptions minted in the contract mapping ( uint256 => RxStructs.RxData ) private rxs; /// @notice Event to signal when a new Rx has been minted /// @param sender address of the Doctor that minted the Rx /// @param receiver address of the Subject that received the Rx minted /// @param tokenId Id of the Token (Rx) that has been minted event minted(address indexed sender, address indexed receiver, uint256 indexed tokenId); /// @notice Event to signal when adding/replacing a Subject allowed to receive/hold NFT Prescriptions /// @param sender is the address of the admin that set the Subject's data /// @param _subjectId is the registered address of the subject (approved for holding NFT Prescriptions) /// @param _birthDate is the subjects' date of birth, in seconds, from UNIX Epoch (1970-01-01) /// @param _nameA is the subject's full name (uses 2 bytes32) /// @param _nameB is the subject's full name (uses 2 bytes32) /// @param _homeAddressA is the subject's legal home address (uses 2 bytes32) /// @param _homeAddressB is the subject's legal home address (uses 2 bytes32) event subjectDataSet(address indexed sender, address indexed _subjectId, uint256 _birthDate, bytes32 _nameA, bytes32 _nameB, bytes32 _homeAddressA, bytes32 _homeAddressB); /// @notice Event to signal when adding/replacing a Doctor allowed to mint NFT Prescriptions /// @param sender is the address of the admin that set the Doctor's data /// @param _subjectId is the ethereum address for the doctor (same Id as the subject that holds this doctor's personal details) /// @param _degree contains a string with the degree of the doctor /// @param _license contains a string with the legal license of the doctor event doctorDataSet(address indexed sender, address indexed _subjectId, bytes32 _degree, bytes32 _license); /// @notice Event to signal when adding/replacing a Pharmacist allowed to burn NFT Prescriptions /// @param sender is the address of the admin that set the Pharmacist's data /// @param _subjectId is the ethereum address for the pahrmacist (same Id as the subject that holds this pharmacist's personal details) /// @param _degree contains a string with the degree of the pharmacist /// @param _license contains a string with the legal license of the pharmacist event pharmacistDataSet(address indexed sender, address indexed _subjectId, bytes32 _degree, bytes32 _license); /// @notice Event to signal a removed Subject /// @param sender is the address of the admin that removed the Subject /// @param _subjectId is the registered address of the subject removed event subjectRemoved(address indexed sender, address indexed _subjectId); /// @notice Event to signal a removed Doctor /// @param sender is the address of the admin that removed the Doctor /// @param _subjectId is the registered address of the doctor removed event doctorRemoved(address indexed sender, address indexed _subjectId); /// @notice Event to signal a removed Pharmacist /// @param sender is the address of the admin that removed the Pharmacist /// @param _subjectId is the registered address of the pharmacist removed event pharmacistRemoved(address indexed sender, address indexed _subjectId); /** End of State Variables & Events */ /// @notice constructor for NFT Prescriptions contract /// @dev Using ERC721 default constructor with "Prescription" and "Rx" as Name and Symbol for the tokens /// @dev We set up the contract creator (msg.sender) with the ADMIN_ROLE to manage all the other Roles /// @dev We increment the counter in the constructor to start Ids in 1, keeping Id 0 (default for uints /// in solidity) to signal that someone doesn't have any NFTs constructor() ERC721("Rx", "Rx") { _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); grantRole(ADMIN_ROLE, msg.sender); _setRoleAdmin(MINTER_ROLE, ADMIN_ROLE); _setRoleAdmin(BURNER_ROLE, ADMIN_ROLE); _tokenIdCounter = 1; } /// @dev function override required by solidity function supportsInterface(bytes4 interfaceId) public view override(ERC721, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } /** Begin of implementation of functions for final project */ /// @dev Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner. function transferOwnership(address newOwner) public onlyRole(DEFAULT_ADMIN_ROLE) { grantRole(DEFAULT_ADMIN_ROLE, newOwner); renounceRole(DEFAULT_ADMIN_ROLE, msg.sender); } /// @dev Checks if _addr is a Subject function isSubject(address _addr) private view returns (bool) { return ( _addr != address(0) && subjects[_addr].subjectId == _addr ); } /// @dev Checks if _addr is a registered doctor function isDoctor(address _addr) private view returns (bool) { return ( _addr != address(0) && doctors[_addr].subjectId == _addr ); } /// @dev Checks if _addr is a registered pharmacist function isPharmacist(address _addr) private view returns (bool) { return ( _addr != address(0) && pharmacists[_addr].subjectId == _addr ); } /// @notice function override to prohibit token transfers function _transfer(address, address, uint256) internal view override(ERC721) { require(msg.sender == address(0), "RX: Rxs are untransferables"); } /// @notice Funtion to mint a Prescription. Should be called only by a Doctor (has MINTER_ROLE) /// @param to The id of the subject (patient) recipient of the prescription /// @param _keys Text lines with the 'title' of each content of the prescription (max 19 characters each) /// @param _values Text lines with the 'content' of the prescription (max 61 characters each) /// @dev Does NOT store a tokenURI. It stores Prescription data on contract (tokenURI is generated upon request) function mint(address to, bytes32[RX_LINES] memory _keys, bytes32[2*RX_LINES] memory _values) public onlyRole(MINTER_ROLE) { require( isSubject(to), 'RX: Not a Subject'); require( (msg.sender != to) , 'RX: Cannot self-prescribe'); uint256 tokenId = _tokenIdCounter++; super._safeMint(to, tokenId); // Store prescription data in contract, leaving tokenURI empty, for it is generated on request (Uniswap V3 style!) rxs[tokenId].date = block.timestamp; rxs[tokenId].patient = getSubject(to); // Patient Info rxs[tokenId].doctorSubject = getSubject(msg.sender); // Doctor (Subject) Info rxs[tokenId].doctor = getDoctor(msg.sender); // Doctor Info rxs[tokenId].keys = _keys; // Rx Keys rxs[tokenId].values = _values; // Rx values emit minted(msg.sender, to, tokenId); } /// @dev function override required by solidity /// @notice function override to store burner data in the rx before burning function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) onlyRole(BURNER_ROLE) { // delete rxs[tokenId]; // Keep Rx Data to be able to view past (dispensed) Prescriptions require( getApproved(tokenId) == msg.sender || isApprovedForAll(ownerOf(tokenId), msg.sender), "pharm not approved"); // We save the burner (pharmacist) data to the Rx rxs[tokenId].pharmacistSubject = getSubject(msg.sender); rxs[tokenId].pharmacist = getPharmacist(msg.sender); super._burn(tokenId); //TODO: Change prescription life cycle in 'Status' to keep prescription data without burning } /// @dev TokenURI generated on the fly from stored data (function override required by solidity) function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { // require(_exists(tokenId), "nonexistent token"); require(tokenId < _tokenIdCounter, "nonminted token"); // Also show TokenURI for 'dispensed' prescriptions return TokenURIDescriptor.constructTokenURI(tokenId, name(), symbol(), rxs[tokenId]); // TODO: Only show TokenURI to authorized people (patient, doctor, pharmacist) // TODO: Modify SVG when a prescription is 'dispensed' } /// @notice Function to get data for a specific tokenId. Only for Doctor, Patient or Pharmacist of the tokenId. /// @param tokenId uint256 representing an existing tokenId /// @return a RxData struct containing all the Rx Data function getRx(uint256 tokenId) public view returns (RxStructs.RxData memory) { return rxs[tokenId]; // TODO: Only show TokenURI to authorized people (patient, doctor, pharmacist) } /// @notice Function to set selfGrantAdmin (only deployer of contract is allowed) /// @param _selfAdmin bool to set state variable function setSelfGrantAdmin(bool _selfAdmin) public onlyRole(DEFAULT_ADMIN_ROLE) { selfGrantAdmin = _selfAdmin; } /// @notice Function to set selfGrantAdmin (only deployer of contract is allowed) /// @return bool with state variable function getSelfGrantAdmin() public view returns (bool) { return selfGrantAdmin; } /// @notice Function to add an admin account /// @param to Address of the account to grant admin role function addAdmin(address to) public { if (!selfGrantAdmin) { grantRole(ADMIN_ROLE, to); } else { // We skip role manager checks for the final project presentation _grantRole(ADMIN_ROLE, to); } } /// @notice Function to remove an admin account /// @param to Address of the account to remove admin role function removeAdmin(address to) public onlyRole(ADMIN_ROLE) { revokeRole(ADMIN_ROLE, to); } /// @notice Function to check if someone has admin role /// @param to address to check for admin role privilege /// @return true if @param to is an admin or false otherwise function isAdmin(address to) public view returns (bool) { return hasRole(ADMIN_ROLE, to); } /// @notice Function to retrieve a Subject /// @param _subjectId the registered address of the subject to retrieve /// @return an object with the Subject function getSubject(address _subjectId) public view returns (RxStructs.Subject memory) { return subjects[_subjectId]; } /// @notice Function to retrieve a Doctor /// @param _subjectId the registered address of the doctor to retrieve /// @return an object with the Doctor function getDoctor(address _subjectId) public view returns (RxStructs.Doctor memory) { return doctors[_subjectId]; } /// @notice Function to retrieve a Pharmacist /// @param _subjectId the registered address of the pharmacist to retrieve /// @return an object with the Pharmacist function getPharmacist(address _subjectId) public view returns (RxStructs.Pharmacist memory) { return pharmacists[_subjectId]; } /// @notice Function to add/replace a Subject allowed to receive/hold NFT Prescriptions /// @param _subjectId is the registered address of the subject (approved for holding NFT Prescriptions) /// @param _birthDate is the subjects' date of birth, in seconds, from UNIX Epoch (1970-01-01) /// @param _nameA is the subject's full name (uses 2 bytes32) /// @param _nameB is the subject's full name (uses 2 bytes32) /// @param _homeAddressA is the subject's legal home address (uses 2 bytes32) /// @param _homeAddressB is the subject's legal home address (uses 2 bytes32) /// @dev Only ADMIN_ROLE users are allowed to modify subjects function setSubjectData(address _subjectId, uint256 _birthDate, bytes32 _nameA, bytes32 _nameB, bytes32 _homeAddressA, bytes32 _homeAddressB) public onlyRole(ADMIN_ROLE) { require ( _subjectId != address(0), 'RX: Cannot register 0x0 address'); // subjects[_subjectId] = RxStructs.Subject(_subjectId, _birthDate, _nameA, _nameB, _homeAddressA, _homeAddressB); subjects[_subjectId].subjectId = _subjectId; subjects[_subjectId].birthDate = _birthDate; subjects[_subjectId].nameA = _nameA; subjects[_subjectId].nameB = _nameB; subjects[_subjectId].homeAddressA = _homeAddressA; subjects[_subjectId].homeAddressB = _homeAddressB; emit subjectDataSet(msg.sender, _subjectId, _birthDate, _nameA, _nameB, _homeAddressA, _homeAddressB); } /// @notice Function to add/replace a Doctor allowed to mint NFT Prescriptions /// @param _subjectId should be a valid ethereum address (same Id as the subject that holds this doctor's personal details) /// @param _degree should contain the degree of the doctor /// @param _license should contain the legal license of the doctor /// @dev @param _workplaces is a feature for future implementations function setDoctorData(address _subjectId, bytes32 _degree, bytes32 _license) //, address[] calldata _workplaces) public onlyRole(ADMIN_ROLE) { require( isSubject(_subjectId), 'RX: Not a Subject'); // Also checks address!=0x0 grantRole(MINTER_ROLE, _subjectId); // doctors[_subjectId] = RxStructs.Doctor(_subjectId, _degree, _license); doctors[_subjectId].subjectId = _subjectId; doctors[_subjectId].degree = _degree; doctors[_subjectId].license = _license; emit doctorDataSet(msg.sender, _subjectId, _degree, _license); } /// @notice Function to add/replace a Pharmacist allowed to burn NFT Prescriptions /// @param _subjectId should be a valid ethereum address (same Id as the subject that holds this pharmacist's personal details) /// @param _degree should contain the degree of the pharmacist /// @param _license should contain the legal license of the pharmacist /// @dev @param _workplaces is a feature for future implementations function setPharmacistData(address _subjectId, bytes32 _degree, bytes32 _license) //, address[] calldata _workplaces) public onlyRole(ADMIN_ROLE) { require( isSubject(_subjectId), 'RX: Not a Subject'); // Also checks address!=0x0 grantRole(BURNER_ROLE, _subjectId); // pharmacists[_subjectId] = RxStructs.Pharmacist(_subjectId, _degree, _license); pharmacists[_subjectId].subjectId = _subjectId; pharmacists[_subjectId].degree = _degree; pharmacists[_subjectId].license = _license; emit pharmacistDataSet(msg.sender, _subjectId, _degree, _license); } /// @notice Function to remove a registered Subject /// @param _subjectId is the registered address of the subject to remove /// @dev Only ADMIN_ROLE users are allowed to remove subjects function removeSubject(address _subjectId) public onlyRole(ADMIN_ROLE) { require( isSubject(_subjectId), 'RX: Not a Subject'); // Also checks address!=0x0 require( !isDoctor(_subjectId), 'RX: Still a Doctor'); require( !isPharmacist(_subjectId), 'RX: Still a Pharmacist'); delete subjects[_subjectId]; emit subjectRemoved(msg.sender, _subjectId); } /// @notice Function to remove a registered Doctor /// @param _subjectId is the registered address of the doctor to remove /// @dev Only ADMIN_ROLE users are allowed to remove doctors function removeDoctor(address _subjectId) public onlyRole(ADMIN_ROLE) { require( isDoctor(_subjectId), 'RX: Not a Doctor'); // Also checks address!=0x0 revokeRole(MINTER_ROLE, _subjectId); delete doctors[_subjectId]; emit doctorRemoved(msg.sender, _subjectId); } /// @notice Function to remove a registered Pharmacist /// @param _subjectId is the registered address of the pharmacist to remove /// @dev Only ADMIN_ROLE users are allowed to remove pharmacists function removePharmacist(address _subjectId) public onlyRole(ADMIN_ROLE) { require( isPharmacist(_subjectId), 'RX: Not a Pharmacist'); // Also checks address!=0x0 revokeRole(BURNER_ROLE, _subjectId); delete pharmacists[_subjectId]; emit pharmacistRemoved(msg.sender, _subjectId); } }
@dev TokenURI generated on the fly from stored data (function override required by solidity) require(_exists(tokenId), "nonexistent token"); TODO: Only show TokenURI to authorized people (patient, doctor, pharmacist) TODO: Modify SVG when a prescription is 'dispensed'
function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return TokenURIDescriptor.constructTokenURI(tokenId, name(), symbol(), rxs[tokenId]); }
13,112,966
[ 1, 1345, 3098, 4374, 603, 326, 21434, 628, 4041, 501, 261, 915, 3849, 1931, 635, 18035, 560, 13, 2583, 24899, 1808, 12, 2316, 548, 3631, 315, 5836, 19041, 1147, 8863, 2660, 30, 5098, 2405, 3155, 3098, 358, 10799, 16951, 261, 16330, 1979, 16, 741, 30206, 16, 1844, 4610, 1077, 376, 13, 2660, 30, 9518, 11281, 1347, 279, 4075, 24136, 353, 296, 2251, 1907, 730, 11, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 3849, 12, 654, 39, 27, 5340, 16, 4232, 39, 27, 5340, 3098, 3245, 13, 203, 3639, 1135, 261, 1080, 3778, 13, 203, 3639, 288, 203, 5411, 327, 3155, 1099, 734, 2263, 18, 10062, 1345, 3098, 12, 2316, 548, 16, 508, 9334, 3273, 9334, 8581, 87, 63, 2316, 548, 19226, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; library BWUtility { // -------- UTILITY FUNCTIONS ---------- // Return next higher even _multiple for _amount parameter (e.g used to round up to even finneys). function ceil(uint _amount, uint _multiple) pure public returns (uint) { return ((_amount + _multiple - 1) / _multiple) * _multiple; } // Checks if two coordinates are adjacent: // xxx // xox // xxx // All x (_x2, _xy2) are adjacent to o (_x1, _y1) in this ascii image. // Adjacency does not wrapp around map edges so if y2 = 255 and y1 = 0 then they are not ajacent function isAdjacent(uint8 _x1, uint8 _y1, uint8 _x2, uint8 _y2) pure public returns (bool) { return ((_x1 == _x2 && (_y2 - _y1 == 1 || _y1 - _y2 == 1))) || // Same column ((_y1 == _y2 && (_x2 - _x1 == 1 || _x1 - _x2 == 1))) || // Same row ((_x2 - _x1 == 1 && (_y2 - _y1 == 1 || _y1 - _y2 == 1))) || // Right upper or lower diagonal ((_x1 - _x2 == 1 && (_y2 - _y1 == 1 || _y1 - _y2 == 1))); // Left upper or lower diagonal } // Converts (x, y) to tileId xy function toTileId(uint8 _x, uint8 _y) pure public returns (uint16) { return uint16(_x) << 8 | uint16(_y); } // Converts _tileId to (x, y) function fromTileId(uint16 _tileId) pure public returns (uint8, uint8) { uint8 y = uint8(_tileId); uint8 x = uint8(_tileId >> 8); return (x, y); } function getBoostFromTile(address _claimer, address _attacker, address _defender, uint _blockValue) pure public returns (uint, uint) { if (_claimer == _attacker) { return (_blockValue, 0); } else if (_claimer == _defender) { return (0, _blockValue); } } } interface ERC20I { function transfer(address _recipient, uint256 _amount) external returns (bool); function balanceOf(address _holder) external view returns (uint256); } contract BWService { address private owner; address private bw; address private bwMarket; BWData private bwData; uint private seed = 42; uint private WITHDRAW_FEE = 20; //1/20 = 5% modifier isOwner { if (msg.sender != owner) { revert(); } _; } modifier isValidCaller { if (msg.sender != bw && msg.sender != bwMarket) { revert(); } _; } event TileClaimed(uint16 tileId, address newClaimer, uint priceInWei, uint creationTime); event TileFortified(uint16 tileId, address claimer, uint addedValueInWei, uint priceInWei, uint fortifyTime); // Sent when a user fortifies an existing claim by bumping its value. event TileAttackedSuccessfully(uint16 tileId, address attacker, uint attackAmount, uint totalAttackAmount, address defender, uint defendAmount, uint totalDefendAmount, uint attackRoll, uint attackTime); // Sent when a user successfully attacks a tile. event TileDefendedSuccessfully(uint16 tileId, address attacker, uint attackAmount, uint totalAttackAmount, address defender, uint defendAmount, uint totalDefendAmount, uint attackRoll, uint defendTime); // Sent when a user successfully defends a tile when attacked. event BlockValueMoved(uint16 sourceTileId, uint16 destTileId, address owner, uint movedBlockValue, uint postSourceValue, uint postDestValue, uint moveTime); // Sent when a user buys a tile from another user, by accepting a tile offer event UserBattleValueUpdated(address userAddress, uint battleValue, bool isWithdraw); // Constructor. constructor(address _bwData) public { bwData = BWData(_bwData); owner = msg.sender; } // Can't send funds straight to this contract. Avoid people sending by mistake. function () payable public { revert(); } // OWNER-ONLY FUNCTIONS function kill() public isOwner { selfdestruct(owner); } function setValidBwCaller(address _bw) public isOwner { bw = _bw; } function setValidBwMarketCaller(address _bwMarket) public isOwner { bwMarket = _bwMarket; } // TILE-RELATED FUNCTIONS // This function claims multiple previously unclaimed tiles in a single transaction. // The value assigned to each tile is the msg.value divided by the number of tiles claimed. // The msg.value is required to be an even multiple of the number of tiles claimed. function storeInitialClaim(address _msgSender, uint16[] _claimedTileIds, uint _claimAmount, bool _useBattleValue) public isValidCaller { uint tileCount = _claimedTileIds.length; require(tileCount > 0); require(_claimAmount >= 1 finney * tileCount); // ensure enough funds paid for all tiles require(_claimAmount % tileCount == 0); // ensure payment is an even multiple of number of tiles claimed uint valuePerBlockInWei = _claimAmount / tileCount; // Due to requires above this is guaranteed to be an even number if (_useBattleValue) { subUserBattleValue(_msgSender, _claimAmount, false); } addGlobalBlockValueBalance(_claimAmount); uint16 tileId; bool isNewTile; for (uint16 i = 0; i < tileCount; i++) { tileId = _claimedTileIds[i]; isNewTile = bwData.isNewTile(tileId); // Is length 0 if first time purchased require(isNewTile); // Can only claim previously unclaimed tiles. // Send claim event emit TileClaimed(tileId, _msgSender, valuePerBlockInWei, block.timestamp); // Update contract state with new tile ownership. bwData.storeClaim(tileId, _msgSender, valuePerBlockInWei); } } function fortifyClaims(address _msgSender, uint16[] _claimedTileIds, uint _fortifyAmount, bool _useBattleValue) public isValidCaller { uint tileCount = _claimedTileIds.length; require(tileCount > 0); uint balance = address(this).balance; require(balance + _fortifyAmount > balance); // prevent overflow require(_fortifyAmount % tileCount == 0); // ensure payment is an even multiple of number of tiles fortified uint addedValuePerTileInWei = _fortifyAmount / tileCount; // Due to requires above this is guaranteed to be an even number require(_fortifyAmount >= 1 finney * tileCount); // ensure enough funds paid for all tiles address claimer; uint blockValue; for (uint16 i = 0; i < tileCount; i++) { (claimer, blockValue) = bwData.getTileClaimerAndBlockValue(_claimedTileIds[i]); require(claimer != 0); // Can't do this on never-owned tiles require(claimer == _msgSender); // Only current claimer can fortify claim if (_useBattleValue) { subUserBattleValue(_msgSender, addedValuePerTileInWei, false); } fortifyClaim(_msgSender, _claimedTileIds[i], addedValuePerTileInWei); } } function fortifyClaim(address _msgSender, uint16 _claimedTileId, uint _fortifyAmount) private { uint blockValue; uint sellPrice; (blockValue, sellPrice) = bwData.getCurrentBlockValueAndSellPriceForTile(_claimedTileId); uint updatedBlockValue = blockValue + _fortifyAmount; // Send fortify event emit TileFortified(_claimedTileId, _msgSender, _fortifyAmount, updatedBlockValue, block.timestamp); // Update tile value. The tile has been fortified by bumping up its value. bwData.updateTileBlockValue(_claimedTileId, updatedBlockValue); // Track addition to global block value addGlobalBlockValueBalance(_fortifyAmount); } // Return a pseudo random number between lower and upper bounds // given the number of previous blocks it should hash. // Random function copied from https://github.com/axiomzen/eth-random/blob/master/contracts/Random.sol. // Changed sha3 to keccak256. // Changed random range from uint64 to uint (=uint256). function random(uint _upper) private returns (uint) { seed = uint(keccak256(keccak256(blockhash(block.number), seed), now)); return seed % _upper; } // A user tries to claim a tile that's already owned by another user. A battle ensues. // A random roll is done with % based on attacking vs defending amounts. function attackTile(address _msgSender, uint16 _tileId, uint _attackAmount, bool _useBattleValue, bool _autoFortify) public isValidCaller { require(_attackAmount >= 1 finney); // Don't allow attacking with less than one base tile price. require(_attackAmount % 1 finney == 0); address claimer; uint blockValue; (claimer, blockValue) = bwData.getTileClaimerAndBlockValue(_tileId); require(claimer != 0); // Can't do this on never-owned tiles require(claimer != _msgSender); // Can't attack one's own tiles require(claimer != owner); // Can't attack owner's tiles because it is used for raffle. // Calculate boosted amounts for attacker and defender // The base attack amount is sent in the by the user. // The base defend amount is the attacked tile's current blockValue. uint attackBoost; uint defendBoost; (attackBoost, defendBoost) = bwData.calculateBattleBoost(_tileId, _msgSender, claimer); uint totalAttackAmount = _attackAmount + attackBoost; uint totalDefendAmount = blockValue + defendBoost; require(totalAttackAmount >= _attackAmount); // prevent overflow require(totalDefendAmount >= blockValue); // prevent overflow require(totalAttackAmount + totalDefendAmount > totalAttackAmount && totalAttackAmount + totalDefendAmount > totalDefendAmount); // Prevent overflow // Verify that attack odds are within allowed range. require(totalAttackAmount / 10 <= blockValue); // Disallow attacks with more than 1000% of defendAmount require(totalAttackAmount >= blockValue / 10); // Disallow attacks with less than 10% of defendAmount // The battle considers boosts. uint attackRoll = random(totalAttackAmount + totalDefendAmount); // This is where the excitement happens! if (attackRoll > totalDefendAmount) { // Send update event emit TileAttackedSuccessfully(_tileId, _msgSender, _attackAmount, totalAttackAmount, claimer, blockValue, totalDefendAmount, attackRoll, block.timestamp); // Change block owner but keep same block value (attacker got battlevalue instead) bwData.setClaimerForTile(_tileId, _msgSender); // Tile successfully attacked! if (_useBattleValue) { if (_autoFortify) { // Fortify the won tile using battle value fortifyClaim(_msgSender, _tileId, _attackAmount); subUserBattleValue(_msgSender, _attackAmount, false); } else { // No reason to withdraw followed by deposit of same amount } } else { if (_autoFortify) { // Fortify the won tile using attack amount fortifyClaim(_msgSender, _tileId, _attackAmount); } else { addUserBattleValue(_msgSender, _attackAmount); // Don't include boost here! } } } else { // Tile successfully defended! if (_useBattleValue) { subUserBattleValue(_msgSender, _attackAmount, false); // Don't include boost here! } addUserBattleValue(claimer, _attackAmount); // Don't include boost here! // Send update event emit TileDefendedSuccessfully(_tileId, _msgSender, _attackAmount, totalAttackAmount, claimer, blockValue, totalDefendAmount, attackRoll, block.timestamp); // Update the timestamp for the defended block. bwData.updateTileTimeStamp(_tileId); } } function moveBlockValue(address _msgSender, uint8 _xSource, uint8 _ySource, uint8 _xDest, uint8 _yDest, uint _moveAmount) public isValidCaller { uint16 sourceTileId = BWUtility.toTileId(_xSource, _ySource); uint16 destTileId = BWUtility.toTileId(_xDest, _yDest); address sourceTileClaimer; address destTileClaimer; uint sourceTileBlockValue; uint destTileBlockValue; (sourceTileClaimer, sourceTileBlockValue) = bwData.getTileClaimerAndBlockValue(sourceTileId); (destTileClaimer, destTileBlockValue) = bwData.getTileClaimerAndBlockValue(destTileId); require(sourceTileClaimer == _msgSender); require(destTileClaimer == _msgSender); require(_moveAmount >= 1 finney); // Can't be less require(_moveAmount % 1 finney == 0); // Move amount must be in multiples of 1 finney // require(sourceTile.blockValue - _moveAmount >= BASE_TILE_PRICE_WEI); // Must always leave some at source require(sourceTileBlockValue - _moveAmount < sourceTileBlockValue); // Prevent overflow require(destTileBlockValue + _moveAmount > destTileBlockValue); // Prevent overflow require(BWUtility.isAdjacent(_xSource, _ySource, _xDest, _yDest)); sourceTileBlockValue -= _moveAmount; destTileBlockValue += _moveAmount; // If ALL block value was moved away from the source tile, we lose our claim to it. It becomes ownerless. if (sourceTileBlockValue == 0) { bwData.deleteTile(sourceTileId); } else { bwData.updateTileBlockValue(sourceTileId, sourceTileBlockValue); bwData.deleteOffer(sourceTileId); // Offer invalid since block value has changed } bwData.updateTileBlockValue(destTileId, destTileBlockValue); bwData.deleteOffer(destTileId); // Offer invalid since block value has changed emit BlockValueMoved(sourceTileId, destTileId, _msgSender, _moveAmount, sourceTileBlockValue, destTileBlockValue, block.timestamp); } // BATTLE VALUE FUNCTIONS function withdrawBattleValue(address msgSender, uint _battleValueInWei) public isValidCaller returns (uint) { require(bwData.hasUser(msgSender)); require(_battleValueInWei % 1 finney == 0); // Must be divisible by 1 finney uint fee = _battleValueInWei / WITHDRAW_FEE; // Since we divide by 20 we can never create infinite fractions, so we'll always count in whole wei amounts. require(_battleValueInWei - fee < _battleValueInWei); // prevent underflow uint amountToWithdraw = _battleValueInWei - fee; uint feeBalance = bwData.getFeeBalance(); require(feeBalance + fee >= feeBalance); // prevent overflow feeBalance += fee; bwData.setFeeBalance(feeBalance); subUserBattleValue(msgSender, _battleValueInWei, true); return amountToWithdraw; } function addUserBattleValue(address _userId, uint _amount) public isValidCaller { uint userBattleValue = bwData.getUserBattleValue(_userId); require(userBattleValue + _amount > userBattleValue); // prevent overflow uint newBattleValue = userBattleValue + _amount; bwData.setUserBattleValue(_userId, newBattleValue); // Don't include boost here! emit UserBattleValueUpdated(_userId, newBattleValue, false); } function subUserBattleValue(address _userId, uint _amount, bool _isWithdraw) public isValidCaller { uint userBattleValue = bwData.getUserBattleValue(_userId); require(_amount <= userBattleValue); // Must be less than user's battle value - also implicitly checks that underflow isn't possible uint newBattleValue = userBattleValue - _amount; bwData.setUserBattleValue(_userId, newBattleValue); // Don't include boost here! emit UserBattleValueUpdated(_userId, newBattleValue, _isWithdraw); } function addGlobalBlockValueBalance(uint _amount) public isValidCaller { // Track addition to global block value. uint blockValueBalance = bwData.getBlockValueBalance(); require(blockValueBalance + _amount > blockValueBalance); // Prevent overflow bwData.setBlockValueBalance(blockValueBalance + _amount); } // Allow us to transfer out airdropped tokens if we ever receive any function transferTokens(address _tokenAddress, address _recipient) public isOwner { ERC20I token = ERC20I(_tokenAddress); require(token.transfer(_recipient, token.balanceOf(this))); } } contract BWData { address public owner; address private bwService; address private bw; address private bwMarket; uint private blockValueBalance = 0; uint private feeBalance = 0; uint private BASE_TILE_PRICE_WEI = 1 finney; // 1 milli-ETH. mapping (address => User) private users; // user address -> user information mapping (uint16 => Tile) private tiles; // tileId -> list of TileClaims for that particular tile // Info about the users = those who have purchased tiles. struct User { uint creationTime; bool censored; uint battleValue; } // Info about a tile ownership struct Tile { address claimer; uint blockValue; uint creationTime; uint sellPrice; // If 0 -> not on marketplace. If > 0 -> on marketplace. } struct Boost { uint8 numAttackBoosts; uint8 numDefendBoosts; uint attackBoost; uint defendBoost; } constructor() public { owner = msg.sender; } // Can't send funds straight to this contract. Avoid people sending by mistake. function () payable public { revert(); } function kill() public isOwner { selfdestruct(owner); } modifier isValidCaller { if (msg.sender != bwService && msg.sender != bw && msg.sender != bwMarket) { revert(); } _; } modifier isOwner { if (msg.sender != owner) { revert(); } _; } function setBwServiceValidCaller(address _bwService) public isOwner { bwService = _bwService; } function setBwValidCaller(address _bw) public isOwner { bw = _bw; } function setBwMarketValidCaller(address _bwMarket) public isOwner { bwMarket = _bwMarket; } // ----------USER-RELATED GETTER FUNCTIONS------------ //function getUser(address _user) view public returns (bytes32) { //BWUtility.User memory user = users[_user]; //require(user.creationTime != 0); //return (user.creationTime, user.imageUrl, user.tag, user.email, user.homeUrl, user.creationTime, user.censored, user.battleValue); //} function addUser(address _msgSender) public isValidCaller { User storage user = users[_msgSender]; require(user.creationTime == 0); user.creationTime = block.timestamp; } function hasUser(address _user) view public isValidCaller returns (bool) { return users[_user].creationTime != 0; } // ----------TILE-RELATED GETTER FUNCTIONS------------ function getTile(uint16 _tileId) view public isValidCaller returns (address, uint, uint, uint) { Tile storage currentTile = tiles[_tileId]; return (currentTile.claimer, currentTile.blockValue, currentTile.creationTime, currentTile.sellPrice); } function getTileClaimerAndBlockValue(uint16 _tileId) view public isValidCaller returns (address, uint) { Tile storage currentTile = tiles[_tileId]; return (currentTile.claimer, currentTile.blockValue); } function isNewTile(uint16 _tileId) view public isValidCaller returns (bool) { Tile storage currentTile = tiles[_tileId]; return currentTile.creationTime == 0; } function storeClaim(uint16 _tileId, address _claimer, uint _blockValue) public isValidCaller { tiles[_tileId] = Tile(_claimer, _blockValue, block.timestamp, 0); } function updateTileBlockValue(uint16 _tileId, uint _blockValue) public isValidCaller { tiles[_tileId].blockValue = _blockValue; } function setClaimerForTile(uint16 _tileId, address _claimer) public isValidCaller { tiles[_tileId].claimer = _claimer; } function updateTileTimeStamp(uint16 _tileId) public isValidCaller { tiles[_tileId].creationTime = block.timestamp; } function getCurrentClaimerForTile(uint16 _tileId) view public isValidCaller returns (address) { Tile storage currentTile = tiles[_tileId]; if (currentTile.creationTime == 0) { return 0; } return currentTile.claimer; } function getCurrentBlockValueAndSellPriceForTile(uint16 _tileId) view public isValidCaller returns (uint, uint) { Tile storage currentTile = tiles[_tileId]; if (currentTile.creationTime == 0) { return (0, 0); } return (currentTile.blockValue, currentTile.sellPrice); } function getBlockValueBalance() view public isValidCaller returns (uint){ return blockValueBalance; } function setBlockValueBalance(uint _blockValueBalance) public isValidCaller { blockValueBalance = _blockValueBalance; } function getFeeBalance() view public isValidCaller returns (uint) { return feeBalance; } function setFeeBalance(uint _feeBalance) public isValidCaller { feeBalance = _feeBalance; } function getUserBattleValue(address _userId) view public isValidCaller returns (uint) { return users[_userId].battleValue; } function setUserBattleValue(address _userId, uint _battleValue) public isValidCaller { users[_userId].battleValue = _battleValue; } function verifyAmount(address _msgSender, uint _msgValue, uint _amount, bool _useBattleValue) view public isValidCaller { User storage user = users[_msgSender]; require(user.creationTime != 0); if (_useBattleValue) { require(_msgValue == 0); require(user.battleValue >= _amount); } else { require(_amount == _msgValue); } } function addBoostFromTile(Tile _tile, address _attacker, address _defender, Boost memory _boost) pure private { if (_tile.claimer == _attacker) { require(_boost.attackBoost + _tile.blockValue >= _tile.blockValue); // prevent overflow _boost.attackBoost += _tile.blockValue; _boost.numAttackBoosts += 1; } else if (_tile.claimer == _defender) { require(_boost.defendBoost + _tile.blockValue >= _tile.blockValue); // prevent overflow _boost.defendBoost += _tile.blockValue; _boost.numDefendBoosts += 1; } } function calculateBattleBoost(uint16 _tileId, address _attacker, address _defender) view public isValidCaller returns (uint, uint) { uint8 x; uint8 y; (x, y) = BWUtility.fromTileId(_tileId); Boost memory boost = Boost(0, 0, 0, 0); // We overflow x, y on purpose here if x or y is 0 or 255 - the map overflows and so should adjacency. // Go through all adjacent tiles to (x, y). if (y != 255) { if (x != 255) { addBoostFromTile(tiles[BWUtility.toTileId(x+1, y+1)], _attacker, _defender, boost); } addBoostFromTile(tiles[BWUtility.toTileId(x, y+1)], _attacker, _defender, boost); if (x != 0) { addBoostFromTile(tiles[BWUtility.toTileId(x-1, y+1)], _attacker, _defender, boost); } } if (x != 255) { addBoostFromTile(tiles[BWUtility.toTileId(x+1, y)], _attacker, _defender, boost); } if (x != 0) { addBoostFromTile(tiles[BWUtility.toTileId(x-1, y)], _attacker, _defender, boost); } if (y != 0) { if(x != 255) { addBoostFromTile(tiles[BWUtility.toTileId(x+1, y-1)], _attacker, _defender, boost); } addBoostFromTile(tiles[BWUtility.toTileId(x, y-1)], _attacker, _defender, boost); if(x != 0) { addBoostFromTile(tiles[BWUtility.toTileId(x-1, y-1)], _attacker, _defender, boost); } } // The benefit of boosts is multiplicative (quadratic): // - More boost tiles gives a higher total blockValue (the sum of the adjacent tiles) // - More boost tiles give a higher multiple of that total blockValue that can be used (10% per adjacent tie) // Example: // A) I boost attack with 1 single tile worth 10 finney // -> Total boost is 10 * 1 / 10 = 1 finney // B) I boost attack with 3 tiles worth 1 finney each // -> Total boost is (1+1+1) * 3 / 10 = 0.9 finney // C) I boost attack with 8 tiles worth 2 finney each // -> Total boost is (2+2+2+2+2+2+2+2) * 8 / 10 = 14.4 finney // D) I boost attack with 3 tiles of 1, 5 and 10 finney respectively // -> Total boost is (ss1+5+10) * 3 / 10 = 4.8 finney // This division by 10 can't create fractions since our uint is wei, and we can't have overflow from the multiplication // We do allow fractions of finney here since the boosted values aren't stored anywhere, only used for attack rolls and sent in events boost.attackBoost = (boost.attackBoost / 10 * boost.numAttackBoosts); boost.defendBoost = (boost.defendBoost / 10 * boost.numDefendBoosts); return (boost.attackBoost, boost.defendBoost); } function censorUser(address _userAddress, bool _censored) public isValidCaller { User storage user = users[_userAddress]; require(user.creationTime != 0); user.censored = _censored; } function deleteTile(uint16 _tileId) public isValidCaller { delete tiles[_tileId]; } function setSellPrice(uint16 _tileId, uint _sellPrice) public isValidCaller { tiles[_tileId].sellPrice = _sellPrice; //testrpc cannot estimate gas when delete is used. } function deleteOffer(uint16 _tileId) public isValidCaller { tiles[_tileId].sellPrice = 0; //testrpc cannot estimate gas when delete is used. } } /** * Copyright 2018 Block Wars Team * */ contract BW { address public owner; BWService private bwService; BWData private bwData; bool public paused = false; modifier isOwner { if (msg.sender != owner) { revert(); } _; } // Checks if entire game (except battle value withdraw) is paused or not. modifier isNotPaused { if (paused) { revert(); } _; } // Only allow wallets to call this function, not contracts. modifier isNotContractCaller { require(msg.sender == tx.origin); _; } // All contract event types. event UserCreated(address userAddress, bytes32 name, bytes imageUrl, bytes32 tag, bytes32 homeUrl, uint creationTime, address invitedBy); event UserCensored(address userAddress, bool isCensored); event TransferTileFromOwner(uint16 tileId, address seller, address buyer, uint acceptTime); // Sent when a user buys a tile from another user, by accepting a tile offer event UserUpdated(address userAddress, bytes32 name, bytes imageUrl, bytes32 tag, bytes32 homeUrl, uint updateTime); // BASIC CONTRACT FUNCTIONS // Constructor. constructor(address _bwService, address _bwData) public { bwService = BWService(_bwService); bwData = BWData(_bwData); owner = msg.sender; } // Can't send funds straight to this contract. Avoid people sending by mistake. function () payable public { revert(); } // Allow a new user to claim one or more previously unclaimed tiles by paying Ether. function claimTilesForNewUser(bytes32 _name, bytes _imageUrl, bytes32 _tag, bytes32 _homeUrl, uint16[] _claimedTileIds, address _invitedBy) payable public isNotPaused isNotContractCaller { bwData.addUser(msg.sender); emit UserCreated(msg.sender, _name, _imageUrl, _tag, _homeUrl, block.timestamp, _invitedBy); bwService.storeInitialClaim(msg.sender, _claimedTileIds, msg.value, false); } // Allow an existing user to claim one or more previously unclaimed tiles by paying Ether. function claimTilesForExistingUser(uint16[] _claimedTileIds, uint _claimAmount, bool _useBattleValue) payable public isNotPaused isNotContractCaller { bwData.verifyAmount(msg.sender, msg.value, _claimAmount, _useBattleValue); bwService.storeInitialClaim(msg.sender, _claimedTileIds, _claimAmount, _useBattleValue); } // Allow users to change name, image URL, tag and home URL. Not censored status or battle value though. function updateUser(bytes32 _name, bytes _imageUrl, bytes32 _tag, bytes32 _homeUrl) public isNotPaused isNotContractCaller { require(bwData.hasUser(msg.sender)); // All the updated values are stored in events only so there's no state to update on the contract here. emit UserUpdated(msg.sender, _name, _imageUrl, _tag, _homeUrl, block.timestamp); } // This function fortifies multiple previously claimed tiles in a single transaction. // The value assigned to each tile is the msg.value divided by the number of tiles fortified. // The msg.value is required to be an even multiple of the number of tiles fortified. // Only tiles owned by msg.sender can be fortified. function fortifyClaims(uint16[] _claimedTileIds, uint _fortifyAmount, bool _useBattleValue) payable public isNotPaused isNotContractCaller { bwData.verifyAmount(msg.sender, msg.value, _fortifyAmount, _useBattleValue); bwService.fortifyClaims(msg.sender, _claimedTileIds, _fortifyAmount, _useBattleValue); } // A new user attacks a tile claimed by someone else, trying to make it theirs through battle. function attackTileForNewUser(uint16 _tileId, bytes32 _name, bytes _imageUrl, bytes32 _tag, bytes32 _homeUrl, address _invitedBy) payable public isNotPaused isNotContractCaller { bwData.addUser(msg.sender); emit UserCreated(msg.sender, _name, _imageUrl, _tag, _homeUrl, block.timestamp, _invitedBy); bwService.attackTile(msg.sender, _tileId, msg.value, false, false); } // An existing user attacks a tile claimed by someone else, trying to make it theirs through battle. function attackTileForExistingUser(uint16 _tileId, uint _attackAmount, bool _useBattleValue, bool _autoFortify) payable public isNotPaused isNotContractCaller { bwData.verifyAmount(msg.sender, msg.value, _attackAmount, _useBattleValue); bwService.attackTile(msg.sender, _tileId, _attackAmount, _useBattleValue, _autoFortify); } // Move "army" = block value from one block to an adjacent block. Moving ALL value equates giving up ownership of the source tile. function moveBlockValue(uint8 _xSource, uint8 _ySource, uint8 _xDest, uint8 _yDest, uint _moveAmount) public isNotPaused isNotContractCaller { bwService.moveBlockValue(msg.sender, _xSource, _ySource, _xDest, _yDest, _moveAmount); } // Allow users to withdraw battle value in Ether. function withdrawBattleValue(uint _battleValueInWei) public isNotContractCaller { uint amountToWithdraw = bwService.withdrawBattleValue(msg.sender, _battleValueInWei); msg.sender.transfer(amountToWithdraw); } // -------- OWNER-ONLY FUNCTIONS ---------- // Only used by owner for raffle. Owner need name, address and picture from user. // These users can then be given tiles by owner using transferTileFromOwner. function createNewUser(bytes32 _name, bytes _imageUrl, address _user) public isOwner { bwData.addUser(_user); emit UserCreated(msg.sender, _name, _imageUrl, 0x0, 0x0, block.timestamp, 0x0); } // Allow updating censored status. Owner only. In case someone uploads offensive content. // The contract owners reserve the right to apply censorship. This will mean that the // name, tag or URL images might not be displayed for a censored user. function censorUser(address _userAddress, bool _censored) public isOwner { bwData.censorUser(_userAddress, _censored); emit UserCensored(_userAddress, _censored); } // Pause the entire game, but let users keep withdrawing battle value function setPaused(bool _paused) public isOwner { paused = _paused; } function kill() public isOwner { selfdestruct(owner); } function withdrawValue(bool _isFee) public isOwner { uint balance = address(this).balance; uint amountToWithdraw; if (_isFee) { amountToWithdraw = bwData.getFeeBalance(); if (balance < amountToWithdraw) { // Should never happen, but paranoia amountToWithdraw = balance; } bwData.setFeeBalance(0); } else { amountToWithdraw = bwData.getBlockValueBalance(); if (balance < amountToWithdraw) { // Should never happen, but paranoia amountToWithdraw = balance; } bwData.setBlockValueBalance(0); } owner.transfer(amountToWithdraw); } function depositBattleValue(address _user) payable public isOwner { require(bwData.hasUser(_user)); require(msg.value % 1 finney == 0); // Must be divisible by 1 finney bwService.addUserBattleValue(_user, msg.value); } // The owner can transfer ownership of own tiles to other users, as prizes in competitions. function transferTileFromOwner(uint16 _tileId, address _newOwner) public payable isOwner { address claimer = bwData.getCurrentClaimerForTile(_tileId); require(claimer == owner); require(bwData.hasUser(_newOwner)); require(msg.value % 1 finney == 0); // Must be divisible by 1 finney uint balance = address(this).balance; require(balance + msg.value >= balance); // prevent overflow bwData.setClaimerForTile(_tileId, _newOwner); bwService.addUserBattleValue(_newOwner, msg.value); emit TransferTileFromOwner(_tileId, _newOwner, msg.sender, block.timestamp); } // Allow us to transfer out airdropped tokens if we ever receive any function transferTokens(address _tokenAddress, address _recipient) public isOwner { ERC20I token = ERC20I(_tokenAddress); require(token.transfer(_recipient, token.balanceOf(this))); } }
ensure enough funds paid for all tiles
require(_fortifyAmount >= 1 finney * tileCount);
6,618
[ 1, 15735, 7304, 284, 19156, 30591, 364, 777, 12568, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 24899, 18850, 1164, 6275, 1545, 404, 574, 82, 402, 380, 4769, 1380, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // File: contracts/thirdparty/loopring-wallet/ILoopringWalletV2.sol // Taken from: https://github.com/Loopring/protocols/tree/master/packages/hebao_v2/contracts/iface/ILoopringWalletV2.sol // Copyright 2017 Loopring Technology Limited. /// @title Loopring SmartWallet V2 interface /// @author Brecht Devos - <[email protected]> abstract contract ILoopringWalletV2 { /// @dev Initializes the smart wallet. /// @param owner The wallet owner address. /// @param guardians The initial wallet guardians. /// @param quota The initial wallet quota. /// @param inheritor The inheritor of the wallet. /// @param feeRecipient The address receiving the fee for creating the wallet. /// @param feeToken The token to use for the fee payment. /// @param feeAmount The amount of tokens paid to the fee recipient. function initialize( address owner, address[] calldata guardians, uint quota, address inheritor, address feeRecipient, address feeToken, uint feeAmount ) external virtual; /// @dev Returns the timestamp the wallet was created. /// @return The timestamp the wallet was created. function getCreationTimestamp() public view virtual returns (uint64); /// @dev Returns the current wallet owner. /// @return The current wallet owner. function getOwner() public view virtual returns (address); } // File: contracts/thirdparty/Create2.sol // Taken from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/970f687f04d20e01138a3e8ccf9278b1d4b3997b/contracts/utils/Create2.sol /** * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer. * `CREATE2` can be used to compute in advance the address where a smart * contract will be deployed, which allows for interesting new mechanisms known * as 'counterfactual interactions'. * * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more * information. */ library Create2 { /** * @dev Deploys a contract using `CREATE2`. The address where the contract * will be deployed can be known in advance via {computeAddress}. Note that * a contract cannot be deployed twice using the same salt. */ function deploy(bytes32 salt, bytes memory bytecode) internal returns (address payable) { address payable addr; // solhint-disable-next-line no-inline-assembly assembly { addr := create2(0, add(bytecode, 0x20), mload(bytecode), salt) } require(addr != address(0), "CREATE2_FAILED"); return addr; } /** * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the `bytecode` * or `salt` will result in a new destination address. */ function computeAddress(bytes32 salt, bytes memory bytecode) internal view returns (address) { return computeAddress(salt, bytecode, address(this)); } /** * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}. */ function computeAddress(bytes32 salt, bytes memory bytecodeHash, address deployer) internal pure returns (address) { bytes32 bytecodeHashHash = keccak256(bytecodeHash); bytes32 _data = keccak256( abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHashHash) ); return address(bytes20(_data << 96)); } } // File: contracts/thirdparty/proxies/WalletProxy.sol // Taken from: https://github.com/gnosis/safe-contracts/blob/development/contracts/proxies/GnosisSafeProxy.sol /// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain /// @author Richard Meissner - <[email protected]> interface IProxy { function masterCopy() external view returns (address); } /// @title WalletProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract. /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract WalletProxy { // masterCopy always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated. // To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt` address internal masterCopy; /// @dev Constructor function sets address of master copy contract. /// @param _masterCopy Master copy address. constructor(address _masterCopy) { require(_masterCopy != address(0), "Invalid master copy address provided"); masterCopy = _masterCopy; } /// @dev Fallback function forwards all transactions and returns all received return data. fallback() payable external { // solium-disable-next-line security/no-inline-assembly assembly { let _masterCopy := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff) // 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) { mstore(0, _masterCopy) return(0, 0x20) } calldatacopy(0, 0, calldatasize()) let success := delegatecall(gas(), _masterCopy, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) if eq(success, 0) { revert(0, returndatasize()) } return(0, returndatasize()) } } } // File: contracts/thirdparty/loopring-wallet/WalletDeploymentLib.sol // Taken from: https://github.com/Loopring/protocols/tree/master/packages/hebao_v2/contracts/base/WalletDeploymentLib.sol // Copyright 2017 Loopring Technology Limited. /// @title WalletDeploymentLib /// @dev Functionality to compute wallet addresses and to deploy wallets /// @author Brecht Devos - <[email protected]> contract WalletDeploymentLib { address public immutable walletImplementation; string public constant WALLET_CREATION = "WALLET_CREATION"; constructor( address _walletImplementation ) { walletImplementation = _walletImplementation; } function getWalletCode() public view returns (bytes memory) { return hex"608060405234801561001057600080fd5b5060405161016f38038061016f8339818101604052602081101561003357600080fd5b50516001600160a01b03811661007a5760405162461bcd60e51b815260040180806020018281038252602481526020018061014b6024913960400191505060405180910390fd5b600080546001600160a01b039092166001600160a01b031990921691909117905560a2806100a96000396000f3fe6080604052600073ffffffffffffffffffffffffffffffffffffffff8154167fa619486e0000000000000000000000000000000000000000000000000000000082351415604e57808252602082f35b3682833781823684845af490503d82833e806067573d82fd5b503d81f3fea2646970667358221220676404d5a2e50e328cc18fc786619f9629ae43d7ff695286c941717f0a1541e564736f6c63430007060033496e76616c6964206d617374657220636f707920616464726573732070726f76696465640000000000000000000000004b16684de50ebcc60fd54b0a5fd1ccfdc940bb27"; } function computeWalletSalt( address owner, uint salt ) public pure returns (bytes32) { return keccak256( abi.encodePacked( WALLET_CREATION, owner, salt ) ); } function _deploy( address owner, uint salt ) internal returns (address payable wallet) { wallet = Create2.deploy( computeWalletSalt(owner, salt), getWalletCode() ); } function _computeWalletAddress( address owner, uint salt, address deployer ) internal view returns (address) { return Create2.computeAddress( computeWalletSalt(owner, salt), getWalletCode(), deployer ); } } // File: contracts/lib/AddressUtil.sol // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for addresses /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library AddressUtil { using AddressUtil for *; function isContract( address addr ) 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; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(addr) } return (codehash != 0x0 && codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470); } function toPayable( address addr ) internal pure returns (address payable) { return payable(addr); } // Works like address.send but with a customizable gas limit // Make sure your code is safe for reentrancy when using this function! function sendETH( address to, uint amount, uint gasLimit ) internal returns (bool success) { if (amount == 0) { return true; } address payable recipient = to.toPayable(); /* solium-disable-next-line */ (success, ) = recipient.call{value: amount, gas: gasLimit}(""); } // Works like address.transfer but with a customizable gas limit // Make sure your code is safe for reentrancy when using this function! function sendETHAndVerify( address to, uint amount, uint gasLimit ) internal returns (bool success) { success = to.sendETH(amount, gasLimit); require(success, "TRANSFER_FAILURE"); } // Works like call but is slightly more efficient when data // needs to be copied from memory to do the call. function fastCall( address to, uint gasLimit, uint value, bytes memory data ) internal returns (bool success, bytes memory returnData) { if (to != address(0)) { assembly { // Do the call success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0) // Copy the return data let size := returndatasize() returnData := mload(0x40) mstore(returnData, size) returndatacopy(add(returnData, 32), 0, size) // Update free memory pointer mstore(0x40, add(returnData, add(32, size))) } } } // Like fastCall, but throws when the call is unsuccessful. function fastCallAndVerify( address to, uint gasLimit, uint value, bytes memory data ) internal returns (bytes memory returnData) { bool success; (success, returnData) = fastCall(to, gasLimit, value, data); if (!success) { assembly { revert(add(returnData, 32), mload(returnData)) } } } } // File: contracts/thirdparty/BytesUtil.sol //Mainly taken from https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol library BytesUtil { function concat( bytes memory _preBytes, bytes memory _postBytes ) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function slice( bytes memory _bytes, uint _start, uint _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length)); 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) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { require(_bytes.length >= (_start + 20)); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) { require(_bytes.length >= (_start + 1)); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) { require(_bytes.length >= (_start + 2)); uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint24(bytes memory _bytes, uint _start) internal pure returns (uint24) { require(_bytes.length >= (_start + 3)); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) { require(_bytes.length >= (_start + 4)); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) { require(_bytes.length >= (_start + 8)); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) { require(_bytes.length >= (_start + 12)); uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) { require(_bytes.length >= (_start + 16)); uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) { require(_bytes.length >= (_start + 32)); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes4(bytes memory _bytes, uint _start) internal pure returns (bytes4) { require(_bytes.length >= (_start + 4)); bytes4 tempBytes4; assembly { tempBytes4 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes4; } function toBytes20(bytes memory _bytes, uint _start) internal pure returns (bytes20) { require(_bytes.length >= (_start + 20)); bytes20 tempBytes20; assembly { tempBytes20 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes20; } function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) { require(_bytes.length >= (_start + 32)); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function toAddressUnsafe(bytes memory _bytes, uint _start) internal pure returns (address) { address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint8) { uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint16) { uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint24Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint24) { uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint32Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint32) { uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint64) { uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint96) { uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint128) { uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUintUnsafe(bytes memory _bytes, uint _start) internal pure returns (uint256) { uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes4Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes4) { bytes4 tempBytes4; assembly { tempBytes4 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes4; } function toBytes20Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes20) { bytes20 tempBytes20; assembly { tempBytes20 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes20; } function toBytes32Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes32) { bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function fastSHA256( bytes memory data ) internal view returns (bytes32) { bytes32[] memory result = new bytes32[](1); bool success; assembly { let ptr := add(data, 32) success := staticcall(sub(gas(), 2000), 2, ptr, mload(data), add(result, 32), 32) } require(success, "SHA256_FAILED"); return result[0]; } } // File: contracts/lib/MathUint.sol // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for uint /// @author Daniel Wang - <[email protected]> library MathUint { using MathUint for uint; function mul( uint a, uint b ) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b, "MUL_OVERFLOW"); } function sub( uint a, uint b ) internal pure returns (uint) { require(b <= a, "SUB_UNDERFLOW"); return a - b; } function add( uint a, uint b ) internal pure returns (uint c) { c = a + b; require(c >= a, "ADD_OVERFLOW"); } function add64( uint64 a, uint64 b ) internal pure returns (uint64 c) { c = a + b; require(c >= a, "ADD_OVERFLOW"); } } // File: contracts/lib/ERC1271.sol // Copyright 2017 Loopring Technology Limited. abstract contract ERC1271 { // bytes4(keccak256("isValidSignature(bytes32,bytes)") bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e; function isValidSignature( bytes32 _hash, bytes memory _signature) public view virtual returns (bytes4 magicValueB32); } // File: contracts/lib/SignatureUtil.sol // Copyright 2017 Loopring Technology Limited. /// @title SignatureUtil /// @author Daniel Wang - <[email protected]> /// @dev This method supports multihash standard. Each signature's last byte indicates /// the signature's type. library SignatureUtil { using BytesUtil for bytes; using MathUint for uint; using AddressUtil for address; enum SignatureType { ILLEGAL, INVALID, EIP_712, ETH_SIGN, WALLET // deprecated } bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e; function verifySignatures( bytes32 signHash, address[] memory signers, bytes[] memory signatures ) internal view returns (bool) { require(signers.length == signatures.length, "BAD_SIGNATURE_DATA"); address lastSigner; for (uint i = 0; i < signers.length; i++) { require(signers[i] > lastSigner, "INVALID_SIGNERS_ORDER"); lastSigner = signers[i]; if (!verifySignature(signHash, signers[i], signatures[i])) { return false; } } return true; } function verifySignature( bytes32 signHash, address signer, bytes memory signature ) internal view returns (bool) { if (signer == address(0)) { return false; } return signer.isContract()? verifyERC1271Signature(signHash, signer, signature): verifyEOASignature(signHash, signer, signature); } function recoverECDSASigner( bytes32 signHash, bytes memory signature ) internal pure returns (address) { if (signature.length != 65) { return address(0); } bytes32 r; bytes32 s; uint8 v; // we jump 32 (0x20) as the first slot of bytes contains the length // we jump 65 (0x41) per signature // for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := and(mload(add(signature, 0x41)), 0xff) } // See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v == 27 || v == 28) { return ecrecover(signHash, v, r, s); } else { return address(0); } } function verifyEOASignature( bytes32 signHash, address signer, bytes memory signature ) private pure returns (bool success) { if (signer == address(0)) { return false; } uint signatureTypeOffset = signature.length.sub(1); SignatureType signatureType = SignatureType(signature.toUint8(signatureTypeOffset)); // Strip off the last byte of the signature by updating the length assembly { mstore(signature, signatureTypeOffset) } if (signatureType == SignatureType.EIP_712) { success = (signer == recoverECDSASigner(signHash, signature)); } else if (signatureType == SignatureType.ETH_SIGN) { bytes32 hash = keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", signHash) ); success = (signer == recoverECDSASigner(hash, signature)); } else { success = false; } // Restore the signature length assembly { mstore(signature, add(signatureTypeOffset, 1)) } return success; } function verifyERC1271Signature( bytes32 signHash, address signer, bytes memory signature ) private view returns (bool) { bytes memory callData = abi.encodeWithSelector( ERC1271.isValidSignature.selector, signHash, signature ); (bool success, bytes memory result) = signer.staticcall(callData); return ( success && result.length == 32 && result.toBytes4(0) == ERC1271_MAGICVALUE ); } } // File: contracts/core/iface/IAgentRegistry.sol // Copyright 2017 Loopring Technology Limited. interface IAgent{} abstract contract IAgentRegistry { /// @dev Returns whether an agent address is an agent of an account owner /// @param owner The account owner. /// @param agent The agent address /// @return True if the agent address is an agent for the account owner, else false function isAgent( address owner, address agent ) external virtual view returns (bool); /// @dev Returns whether an agent address is an agent of all account owners /// @param owners The account owners. /// @param agent The agent address /// @return True if the agent address is an agent for the account owner, else false function isAgent( address[] calldata owners, address agent ) external virtual view returns (bool); /// @dev Returns whether an agent address is a universal agent. /// @param agent The agent address /// @return True if the agent address is a universal agent, else false function isUniversalAgent(address agent) public virtual view returns (bool); } // File: contracts/lib/Ownable.sol // Copyright 2017 Loopring Technology Limited. /// @title Ownable /// @author Brecht Devos - <[email protected]> /// @dev The Ownable contract has an owner address, and provides basic /// authorization control functions, this simplifies the implementation of /// "user permissions". contract Ownable { address public owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /// @dev The Ownable constructor sets the original `owner` of the contract /// to the sender. constructor() { owner = msg.sender; } /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner, "UNAUTHORIZED"); _; } /// @dev Allows the current owner to transfer control of the contract to a /// new owner. /// @param newOwner The address to transfer ownership to. function transferOwnership( address newOwner ) public virtual onlyOwner { require(newOwner != address(0), "ZERO_ADDRESS"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } } // File: contracts/lib/Claimable.sol // Copyright 2017 Loopring Technology Limited. /// @title Claimable /// @author Brecht Devos - <[email protected]> /// @dev Extension for the Ownable contract, where the ownership needs /// to be claimed. This allows the new owner to accept the transfer. contract Claimable is Ownable { address public pendingOwner; /// @dev Modifier throws if called by any account other than the pendingOwner. modifier onlyPendingOwner() { require(msg.sender == pendingOwner, "UNAUTHORIZED"); _; } /// @dev Allows the current owner to set the pendingOwner address. /// @param newOwner The address to transfer ownership to. function transferOwnership( address newOwner ) public override onlyOwner { require(newOwner != address(0) && newOwner != owner, "INVALID_ADDRESS"); pendingOwner = newOwner; } /// @dev Allows the pendingOwner address to finalize the transfer. function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/core/iface/IBlockVerifier.sol // Copyright 2017 Loopring Technology Limited. /// @title IBlockVerifier /// @author Brecht Devos - <[email protected]> abstract contract IBlockVerifier is Claimable { // -- Events -- event CircuitRegistered( uint8 indexed blockType, uint16 blockSize, uint8 blockVersion ); event CircuitDisabled( uint8 indexed blockType, uint16 blockSize, uint8 blockVersion ); // -- Public functions -- /// @dev Sets the verifying key for the specified circuit. /// Every block permutation needs its own circuit and thus its own set of /// verification keys. Only a limited number of block sizes per block /// type are supported. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @param vk The verification key function registerCircuit( uint8 blockType, uint16 blockSize, uint8 blockVersion, uint[18] calldata vk ) external virtual; /// @dev Disables the use of the specified circuit. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) function disableCircuit( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual; /// @dev Verifies blocks with the given public data and proofs. /// Verifying a block makes sure all requests handled in the block /// are correctly handled by the operator. /// @param blockType The type of block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @param publicInputs The hash of all the public data of the blocks /// @param proofs The ZK proofs proving that the blocks are correct /// @return True if the block is valid, false otherwise function verifyProofs( uint8 blockType, uint16 blockSize, uint8 blockVersion, uint[] calldata publicInputs, uint[] calldata proofs ) external virtual view returns (bool); /// @dev Checks if a circuit with the specified parameters is registered. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @return True if the circuit is registered, false otherwise function isCircuitRegistered( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual view returns (bool); /// @dev Checks if a circuit can still be used to commit new blocks. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @return True if the circuit is enabled, false otherwise function isCircuitEnabled( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual view returns (bool); } // File: contracts/core/iface/IDepositContract.sol // Copyright 2017 Loopring Technology Limited. /// @title IDepositContract. /// @dev Contract storing and transferring funds for an exchange. /// /// ERC1155 tokens can be supported by registering pseudo token addresses calculated /// as `address(keccak256(real_token_address, token_params))`. Then the custom /// deposit contract can look up the real token address and paramsters with the /// pseudo token address before doing the transfers. /// @author Brecht Devos - <[email protected]> interface IDepositContract { /// @dev Returns if a token is suppoprted by this contract. function isTokenSupported(address token) external view returns (bool); /// @dev Transfers tokens from a user to the exchange. This function will /// be called when a user deposits funds to the exchange. /// In a simple implementation the funds are simply stored inside the /// deposit contract directly. More advanced implementations may store the funds /// in some DeFi application to earn interest, so this function could directly /// call the necessary functions to store the funds there. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address of the account that sends the tokens. /// @param token The address of the token to transfer (`0x0` for ETH). /// @param amount The amount of tokens to transfer. /// @param extraData Opaque data that can be used by the contract to handle the deposit /// @return amountReceived The amount to deposit to the user's account in the Merkle tree function deposit( address from, address token, uint96 amount, bytes calldata extraData ) external payable returns (uint96 amountReceived); /// @dev Transfers tokens from the exchange to a user. This function will /// be called when a withdrawal is done for a user on the exchange. /// In the simplest implementation the funds are simply stored inside the /// deposit contract directly so this simply transfers the requested tokens back /// to the user. More advanced implementations may store the funds /// in some DeFi application to earn interest so the function would /// need to get those tokens back from the DeFi application first before they /// can be transferred to the user. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address from which 'amount' tokens are transferred. /// @param to The address to which 'amount' tokens are transferred. /// @param token The address of the token to transfer (`0x0` for ETH). /// @param amount The amount of tokens transferred. /// @param extraData Opaque data that can be used by the contract to handle the withdrawal function withdraw( address from, address to, address token, uint amount, bytes calldata extraData ) external payable; /// @dev Transfers tokens (ETH not supported) for a user using the allowance set /// for the exchange. This way the approval can be used for all functionality (and /// extended functionality) of the exchange. /// Should NOT be used to deposit/withdraw user funds, `deposit`/`withdraw` /// should be used for that as they will contain specialised logic for those operations. /// This function can be called by the exchange to transfer onchain funds of users /// necessary for Agent functionality. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address of the account that sends the tokens. /// @param to The address to which 'amount' tokens are transferred. /// @param token The address of the token to transfer (ETH is and cannot be suppported). /// @param amount The amount of tokens transferred. function transfer( address from, address to, address token, uint amount ) external payable; /// @dev Checks if the given address is used for depositing ETH or not. /// Is used while depositing to send the correct ETH amount to the deposit contract. /// /// Note that 0x0 is always registered for deposting ETH when the exchange is created! /// This function allows additional addresses to be used for depositing ETH, the deposit /// contract can implement different behaviour based on the address value. /// /// @param addr The address to check /// @return True if the address is used for depositing ETH, else false. function isETH(address addr) external view returns (bool); } // File: contracts/core/iface/ILoopringV3.sol // Copyright 2017 Loopring Technology Limited. /// @title ILoopringV3 /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> abstract contract ILoopringV3 is Claimable { // == Events == event ExchangeStakeDeposited(address exchangeAddr, uint amount); event ExchangeStakeWithdrawn(address exchangeAddr, uint amount); event ExchangeStakeBurned(address exchangeAddr, uint amount); event SettingsUpdated(uint time); // == Public Variables == mapping (address => uint) internal exchangeStake; uint public totalStake; address public blockVerifierAddress; uint public forcedWithdrawalFee; uint public tokenRegistrationFeeLRCBase; uint public tokenRegistrationFeeLRCDelta; uint8 public protocolTakerFeeBips; uint8 public protocolMakerFeeBips; address payable public protocolFeeVault; // == Public Functions == /// @dev Returns the LRC token address /// @return the LRC token address function lrcAddress() external view virtual returns (address); /// @dev Updates the global exchange settings. /// This function can only be called by the owner of this contract. /// /// Warning: these new values will be used by existing and /// new Loopring exchanges. function updateSettings( address payable _protocolFeeVault, // address(0) not allowed address _blockVerifierAddress, // address(0) not allowed uint _forcedWithdrawalFee ) external virtual; /// @dev Updates the global protocol fee settings. /// This function can only be called by the owner of this contract. /// /// Warning: these new values will be used by existing and /// new Loopring exchanges. function updateProtocolFeeSettings( uint8 _protocolTakerFeeBips, uint8 _protocolMakerFeeBips ) external virtual; /// @dev Gets the amount of staked LRC for an exchange. /// @param exchangeAddr The address of the exchange /// @return stakedLRC The amount of LRC function getExchangeStake( address exchangeAddr ) public virtual view returns (uint stakedLRC); /// @dev Burns a certain amount of staked LRC for a specific exchange. /// This function is meant to be called only from exchange contracts. /// @return burnedLRC The amount of LRC burned. If the amount is greater than /// the staked amount, all staked LRC will be burned. function burnExchangeStake( uint amount ) external virtual returns (uint burnedLRC); /// @dev Stakes more LRC for an exchange. /// @param exchangeAddr The address of the exchange /// @param amountLRC The amount of LRC to stake /// @return stakedLRC The total amount of LRC staked for the exchange function depositExchangeStake( address exchangeAddr, uint amountLRC ) external virtual returns (uint stakedLRC); /// @dev Withdraws a certain amount of staked LRC for an exchange to the given address. /// This function is meant to be called only from within exchange contracts. /// @param recipient The address to receive LRC /// @param requestedAmount The amount of LRC to withdraw /// @return amountLRC The amount of LRC withdrawn function withdrawExchangeStake( address recipient, uint requestedAmount ) external virtual returns (uint amountLRC); /// @dev Gets the protocol fee values for an exchange. /// @return takerFeeBips The protocol taker fee /// @return makerFeeBips The protocol maker fee function getProtocolFeeValues( ) public virtual view returns ( uint8 takerFeeBips, uint8 makerFeeBips ); } // File: contracts/core/iface/ExchangeData.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeData /// @dev All methods in this lib are internal, therefore, there is no need /// to deploy this library independently. /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library ExchangeData { // -- Enums -- enum TransactionType { NOOP, DEPOSIT, WITHDRAWAL, TRANSFER, SPOT_TRADE, ACCOUNT_UPDATE, AMM_UPDATE, SIGNATURE_VERIFICATION, NFT_MINT, // L2 NFT mint or L1-to-L2 NFT deposit NFT_DATA } enum NftType { ERC1155, ERC721 } // -- Structs -- struct Token { address token; } struct ProtocolFeeData { uint32 syncedAt; // only valid before 2105 (85 years to go) uint8 takerFeeBips; uint8 makerFeeBips; uint8 previousTakerFeeBips; uint8 previousMakerFeeBips; } // General auxiliary data for each conditional transaction struct AuxiliaryData { uint txIndex; bool approved; bytes data; } // This is the (virtual) block the owner needs to submit onchain to maintain the // per-exchange (virtual) blockchain. struct Block { uint8 blockType; uint16 blockSize; uint8 blockVersion; bytes data; uint256[8] proof; // Whether we should store the @BlockInfo for this block on-chain. bool storeBlockInfoOnchain; // Block specific data that is only used to help process the block on-chain. // It is not used as input for the circuits and it is not necessary for data-availability. // This bytes array contains the abi encoded AuxiliaryData[] data. bytes auxiliaryData; // Arbitrary data, mainly for off-chain data-availability, i.e., // the multihash of the IPFS file that contains the block data. bytes offchainData; } struct BlockInfo { // The time the block was submitted on-chain. uint32 timestamp; // The public data hash of the block (the 28 most significant bytes). bytes28 blockDataHash; } // Represents an onchain deposit request. struct Deposit { uint96 amount; uint64 timestamp; } // A forced withdrawal request. // If the actual owner of the account initiated the request (we don't know who the owner is // at the time the request is being made) the full balance will be withdrawn. struct ForcedWithdrawal { address owner; uint64 timestamp; } struct Constants { uint SNARK_SCALAR_FIELD; uint MAX_OPEN_FORCED_REQUESTS; uint MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE; uint TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS; uint MAX_NUM_ACCOUNTS; uint MAX_NUM_TOKENS; uint MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED; uint MIN_TIME_IN_SHUTDOWN; uint TX_DATA_AVAILABILITY_SIZE; uint MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND; } // This is the prime number that is used for the alt_bn128 elliptic curve, see EIP-196. uint public constant SNARK_SCALAR_FIELD = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint public constant MAX_OPEN_FORCED_REQUESTS = 4096; uint public constant MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE = 15 days; uint public constant TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS = 7 days; uint public constant MAX_NUM_ACCOUNTS = 2 ** 32; uint public constant MAX_NUM_TOKENS = 2 ** 16; uint public constant MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED = 7 days; uint public constant MIN_TIME_IN_SHUTDOWN = 30 days; // The amount of bytes each rollup transaction uses in the block data for data-availability. // This is the maximum amount of bytes of all different transaction types. uint32 public constant MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND = 15 days; uint32 public constant ACCOUNTID_PROTOCOLFEE = 0; uint public constant TX_DATA_AVAILABILITY_SIZE = 68; uint public constant TX_DATA_AVAILABILITY_SIZE_PART_1 = 29; uint public constant TX_DATA_AVAILABILITY_SIZE_PART_2 = 39; uint public constant NFT_TOKEN_ID_START = 2 ** 15; struct AccountLeaf { uint32 accountID; address owner; uint pubKeyX; uint pubKeyY; uint32 nonce; uint feeBipsAMM; } struct BalanceLeaf { uint16 tokenID; uint96 balance; uint weightAMM; uint storageRoot; } struct Nft { address minter; // Minter address for a L2 mint or // the NFT's contract address in the case of a L1-to-L2 NFT deposit. NftType nftType; address token; uint256 nftID; uint8 creatorFeeBips; } struct MerkleProof { ExchangeData.AccountLeaf accountLeaf; ExchangeData.BalanceLeaf balanceLeaf; ExchangeData.Nft nft; uint[48] accountMerkleProof; uint[24] balanceMerkleProof; } struct BlockContext { bytes32 DOMAIN_SEPARATOR; uint32 timestamp; Block block; uint txIndex; } // Represents the entire exchange state except the owner of the exchange. struct State { uint32 maxAgeDepositUntilWithdrawable; bytes32 DOMAIN_SEPARATOR; ILoopringV3 loopring; IBlockVerifier blockVerifier; IAgentRegistry agentRegistry; IDepositContract depositContract; // The merkle root of the offchain data stored in a Merkle tree. The Merkle tree // stores balances for users using an account model. bytes32 merkleRoot; // List of all blocks mapping(uint => BlockInfo) blocks; uint numBlocks; // List of all tokens Token[] tokens; // A map from a token to its tokenID + 1 mapping (address => uint16) tokenToTokenId; // A map from an accountID to a tokenID to if the balance is withdrawn mapping (uint32 => mapping (uint16 => bool)) withdrawnInWithdrawMode; // A map from an account to a token to the amount withdrawable for that account. // This is only used when the automatic distribution of the withdrawal failed. mapping (address => mapping (uint16 => uint)) amountWithdrawable; // A map from an account to a token to the forced withdrawal (always full balance) // The `uint16' represents ERC20 token ID (if < NFT_TOKEN_ID_START) or // NFT balance slot (if >= NFT_TOKEN_ID_START) mapping (uint32 => mapping (uint16 => ForcedWithdrawal)) pendingForcedWithdrawals; // A map from an address to a token to a deposit mapping (address => mapping (uint16 => Deposit)) pendingDeposits; // A map from an account owner to an approved transaction hash to if the transaction is approved or not mapping (address => mapping (bytes32 => bool)) approvedTx; // A map from an account owner to a destination address to a tokenID to an amount to a storageID to a new recipient address mapping (address => mapping (address => mapping (uint16 => mapping (uint => mapping (uint32 => address))))) withdrawalRecipient; // Counter to keep track of how many of forced requests are open so we can limit the work that needs to be done by the owner uint32 numPendingForcedTransactions; // Cached data for the protocol fee ProtocolFeeData protocolFeeData; // Time when the exchange was shutdown uint shutdownModeStartTime; // Time when the exchange has entered withdrawal mode uint withdrawalModeStartTime; // Last time the protocol fee was withdrawn for a specific token mapping (address => uint) protocolFeeLastWithdrawnTime; // Duplicated loopring address address loopringAddr; // AMM fee bips uint8 ammFeeBips; // Enable/Disable `onchainTransferFrom` bool allowOnchainTransferFrom; // owner => NFT type => token address => nftID => Deposit mapping (address => mapping (NftType => mapping (address => mapping(uint256 => Deposit)))) pendingNFTDeposits; // owner => minter => NFT type => token address => nftID => amount withdrawable // This is only used when the automatic distribution of the withdrawal failed. mapping (address => mapping (address => mapping (NftType => mapping (address => mapping(uint256 => uint))))) amountWithdrawableNFT; } } // File: contracts/core/iface/IExchangeV3.sol // Copyright 2017 Loopring Technology Limited. /// @title IExchangeV3 /// @dev Note that Claimable and RentrancyGuard are inherited here to /// ensure all data members are declared on IExchangeV3 to make it /// easy to support upgradability through proxies. /// /// Subclasses of this contract must NOT define constructor to /// initialize data. /// /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> abstract contract IExchangeV3 is Claimable { // -- Events -- event ExchangeCloned( address exchangeAddress, address owner, bytes32 genesisMerkleRoot ); event TokenRegistered( address token, uint16 tokenId ); event Shutdown( uint timestamp ); event WithdrawalModeActivated( uint timestamp ); event BlockSubmitted( uint indexed blockIdx, bytes32 merkleRoot, bytes32 publicDataHash ); event DepositRequested( address from, address to, address token, uint16 tokenId, uint96 amount ); event NFTDepositRequested( address from, address to, uint8 nftType, address token, uint256 nftID, uint96 amount ); event ForcedWithdrawalRequested( address owner, uint16 tokenID, uint32 accountID ); event WithdrawalCompleted( uint8 category, address from, address to, address token, uint amount ); event WithdrawalFailed( uint8 category, address from, address to, address token, uint amount ); event NftWithdrawalCompleted( uint8 category, address from, address to, uint16 tokenID, address token, uint256 nftID, uint amount ); event NftWithdrawalFailed( uint8 category, address from, address to, uint16 tokenID, address token, uint256 nftID, uint amount ); event ProtocolFeesUpdated( uint8 takerFeeBips, uint8 makerFeeBips, uint8 previousTakerFeeBips, uint8 previousMakerFeeBips ); event TransactionApproved( address owner, bytes32 transactionHash ); // -- Initialization -- /// @dev Initializes this exchange. This method can only be called once. /// @param loopring The LoopringV3 contract address. /// @param owner The owner of this exchange. /// @param genesisMerkleRoot The initial Merkle tree state. function initialize( address loopring, address owner, bytes32 genesisMerkleRoot ) virtual external; /// @dev Initialized the agent registry contract used by the exchange. /// Can only be called by the exchange owner once. /// @param agentRegistry The agent registry contract to be used function setAgentRegistry(address agentRegistry) external virtual; /// @dev Gets the agent registry contract used by the exchange. /// @return the agent registry contract function getAgentRegistry() external virtual view returns (IAgentRegistry); /// Can only be called by the exchange owner once. /// @param depositContract The deposit contract to be used function setDepositContract(address depositContract) external virtual; /// @dev refresh the blockVerifier contract which maybe changed in loopringV3 contract. function refreshBlockVerifier() external virtual; /// @dev Gets the deposit contract used by the exchange. /// @return the deposit contract function getDepositContract() external virtual view returns (IDepositContract); // @dev Exchange owner withdraws fees from the exchange. // @param token Fee token address // @param feeRecipient Fee recipient address function withdrawExchangeFees( address token, address feeRecipient ) external virtual; // -- Constants -- /// @dev Returns a list of constants used by the exchange. /// @return constants The list of constants. function getConstants() external virtual pure returns(ExchangeData.Constants memory); // -- Mode -- /// @dev Returns hether the exchange is in withdrawal mode. /// @return Returns true if the exchange is in withdrawal mode, else false. function isInWithdrawalMode() external virtual view returns (bool); /// @dev Returns whether the exchange is shutdown. /// @return Returns true if the exchange is shutdown, else false. function isShutdown() external virtual view returns (bool); // -- Tokens -- /// @dev Registers an ERC20 token for a token id. Note that different exchanges may have /// different ids for the same ERC20 token. /// /// Please note that 1 is reserved for Ether (ETH), 2 is reserved for Wrapped Ether (ETH), /// and 3 is reserved for Loopring Token (LRC). /// /// This function is only callable by the exchange owner. /// /// @param tokenAddress The token's address /// @return tokenID The token's ID in this exchanges. function registerToken( address tokenAddress ) external virtual returns (uint16 tokenID); /// @dev Returns the id of a registered token. /// @param tokenAddress The token's address /// @return tokenID The token's ID in this exchanges. function getTokenID( address tokenAddress ) external virtual view returns (uint16 tokenID); /// @dev Returns the address of a registered token. /// @param tokenID The token's ID in this exchanges. /// @return tokenAddress The token's address function getTokenAddress( uint16 tokenID ) external virtual view returns (address tokenAddress); // -- Stakes -- /// @dev Gets the amount of LRC the owner has staked onchain for this exchange. /// The stake will be burned if the exchange does not fulfill its duty by /// processing user requests in time. Please note that order matching may potentially /// performed by another party and is not part of the exchange's duty. /// /// @return The amount of LRC staked function getExchangeStake() external virtual view returns (uint); /// @dev Withdraws the amount staked for this exchange. /// This can only be done if the exchange has been correctly shutdown: /// - The exchange owner has shutdown the exchange /// - All deposit requests are processed /// - All funds are returned to the users (merkle root is reset to initial state) /// /// Can only be called by the exchange owner. /// /// @return amountLRC The amount of LRC withdrawn function withdrawExchangeStake( address recipient ) external virtual returns (uint amountLRC); /// @dev Can by called by anyone to burn the stake of the exchange when certain /// conditions are fulfilled. /// /// Currently this will only burn the stake of the exchange if /// the exchange is in withdrawal mode. function burnExchangeStake() external virtual; // -- Blocks -- /// @dev Gets the current Merkle root of this exchange's virtual blockchain. /// @return The current Merkle root. function getMerkleRoot() external virtual view returns (bytes32); /// @dev Gets the height of this exchange's virtual blockchain. The block height for a /// new exchange is 1. /// @return The virtual blockchain height which is the index of the last block. function getBlockHeight() external virtual view returns (uint); /// @dev Gets some minimal info of a previously submitted block that's kept onchain. /// A DEX can use this function to implement a payment receipt verification /// contract with a challange-response scheme. /// @param blockIdx The block index. function getBlockInfo(uint blockIdx) external virtual view returns (ExchangeData.BlockInfo memory); /// @dev Sumbits new blocks to the rollup blockchain. /// /// This function can only be called by the exchange operator. /// /// @param blocks The blocks being submitted /// - blockType: The type of the new block /// - blockSize: The number of onchain or offchain requests/settlements /// that have been processed in this block /// - blockVersion: The circuit version to use for verifying the block /// - storeBlockInfoOnchain: If the block info for this block needs to be stored on-chain /// - data: The data for this block /// - offchainData: Arbitrary data, mainly for off-chain data-availability, i.e., /// the multihash of the IPFS file that contains the block data. function submitBlocks(ExchangeData.Block[] calldata blocks) external virtual; /// @dev Gets the number of available forced request slots. /// @return The number of available slots. function getNumAvailableForcedSlots() external virtual view returns (uint); // -- Deposits -- /// @dev Deposits Ether or ERC20 tokens to the specified account. /// /// This function is only callable by an agent of 'from'. /// /// The operator is not forced to do the deposit. /// /// @param from The address that deposits the funds to the exchange /// @param to The account owner's address receiving the funds /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @param amount The amount of tokens to deposit /// @param extraData Optional extra data used by the deposit contract function deposit( address from, address to, address tokenAddress, uint96 amount, bytes calldata extraData ) external virtual payable; /// @dev Deposits an NFT to the specified account. /// /// This function is only callable by an agent of 'from'. /// /// The operator is not forced to do the deposit. /// /// @param from The address that deposits the funds to the exchange /// @param to The account owner's address receiving the funds /// @param nftType The type of NFT contract address (ERC721/ERC1155/...) /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @param nftID The token type 'id`. /// @param amount The amount of tokens to deposit. /// @param extraData Optional extra data used by the deposit contract. function depositNFT( address from, address to, ExchangeData.NftType nftType, address tokenAddress, uint256 nftID, uint96 amount, bytes calldata extraData ) external virtual; /// @dev Gets the amount of tokens that may be added to the owner's account. /// @param owner The destination address for the amount deposited. /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @return The amount of tokens pending. function getPendingDepositAmount( address owner, address tokenAddress ) public virtual view returns (uint96); /// @dev Gets the amount of tokens that may be added to the owner's account. /// @param owner The destination address for the amount deposited. /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @param nftType The type of NFT contract address (ERC721/ERC1155/...) /// @param nftID The token type 'id`. /// @return The amount of tokens pending. function getPendingNFTDepositAmount( address owner, address tokenAddress, ExchangeData.NftType nftType, uint256 nftID ) public virtual view returns (uint96); // -- Withdrawals -- /// @dev Submits an onchain request to force withdraw Ether, ERC20 and NFT tokens. /// This request always withdraws the full balance. /// /// This function is only callable by an agent of the account. /// /// The total fee in ETH that the user needs to pay is 'withdrawalFee'. /// If the user sends too much ETH the surplus is sent back immediately. /// /// Note that after such an operation, it will take the owner some /// time (no more than MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE) to process the request /// and create the deposit to the offchain account. /// /// @param owner The expected owner of the account /// @param tokenID The tokenID to withdraw from /// @param accountID The address the account in the Merkle tree. function forceWithdrawByTokenID( address owner, uint16 tokenID, uint32 accountID ) external virtual payable; /// @dev Submits an onchain request to force withdraw Ether or ERC20 tokens. /// This request always withdraws the full balance. /// /// This function is only callable by an agent of the account. /// /// The total fee in ETH that the user needs to pay is 'withdrawalFee'. /// If the user sends too much ETH the surplus is sent back immediately. /// /// Note that after such an operation, it will take the owner some /// time (no more than MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE) to process the request /// and create the deposit to the offchain account. /// /// @param owner The expected owner of the account /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @param accountID The address the account in the Merkle tree. function forceWithdraw( address owner, address tokenAddress, uint32 accountID ) external virtual payable; /// @dev Checks if a forced withdrawal is pending for an account balance. /// @param accountID The accountID of the account to check. /// @param token The token address /// @return True if a request is pending, false otherwise function isForcedWithdrawalPending( uint32 accountID, address token ) external virtual view returns (bool); /// @dev Submits an onchain request to withdraw Ether or ERC20 tokens from the /// protocol fees account. The complete balance is always withdrawn. /// /// Anyone can request a withdrawal of the protocol fees. /// /// Note that after such an operation, it will take the owner some /// time (no more than MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE) to process the request /// and create the deposit to the offchain account. /// /// @param tokenAddress The address of the token, use `0x0` for Ether. function withdrawProtocolFees( address tokenAddress ) external virtual payable; /// @dev Gets the time the protocol fee for a token was last withdrawn. /// @param tokenAddress The address of the token, use `0x0` for Ether. /// @return The time the protocol fee was last withdrawn. function getProtocolFeeLastWithdrawnTime( address tokenAddress ) external virtual view returns (uint); /// @dev Allows anyone to withdraw funds for a specified user using the balances stored /// in the Merkle tree. The funds will be sent to the owner of the acount. /// /// Can only be used in withdrawal mode (i.e. when the owner has stopped /// committing blocks and is not able to commit any more blocks). /// /// This will NOT modify the onchain merkle root! The merkle root stored /// onchain will remain the same after the withdrawal. We store if the user /// has withdrawn the balance in State.withdrawnInWithdrawMode. /// /// @param merkleProof The Merkle inclusion proof function withdrawFromMerkleTree( ExchangeData.MerkleProof calldata merkleProof ) external virtual; /// @dev Checks if the balance for the account was withdrawn with `withdrawFromMerkleTree`. /// @param accountID The accountID of the balance to check. /// @param token The token address /// @return True if it was already withdrawn, false otherwise function isWithdrawnInWithdrawalMode( uint32 accountID, address token ) external virtual view returns (bool); /// @dev Allows withdrawing funds deposited to the contract in a deposit request when /// it was never processed by the owner within the maximum time allowed. /// /// Can be called by anyone. The deposited tokens will be sent back to /// the owner of the account they were deposited in. /// /// @param owner The address of the account the withdrawal was done for. /// @param token The token address function withdrawFromDepositRequest( address owner, address token ) external virtual; /// @dev Allows withdrawing funds deposited to the contract in a deposit request when /// it was never processed by the owner within the maximum time allowed. /// /// Can be called by anyone. The deposited tokens will be sent back to /// the owner of the account they were deposited in. /// /// @param owner The address of the account the withdrawal was done for. /// @param token The token address /// @param nftType The type of NFT contract address (ERC721/ERC1155/...) /// @param nftID The token type 'id`. function withdrawFromNFTDepositRequest( address owner, address token, ExchangeData.NftType nftType, uint256 nftID ) external virtual; /// @dev Allows withdrawing funds after a withdrawal request (either onchain /// or offchain) was submitted in a block by the operator. /// /// Can be called by anyone. The withdrawn tokens will be sent to /// the owner of the account they were withdrawn out. /// /// Normally it is should not be needed for users to call this manually. /// Funds from withdrawal requests will be sent to the account owner /// immediately by the owner when the block is submitted. /// The user will however need to call this manually if the transfer failed. /// /// Tokens and owners must have the same size. /// /// @param owners The addresses of the account the withdrawal was done for. /// @param tokens The token addresses function withdrawFromApprovedWithdrawals( address[] calldata owners, address[] calldata tokens ) external virtual; /// @dev Allows withdrawing funds after an NFT withdrawal request (either onchain /// or offchain) was submitted in a block by the operator. /// /// Can be called by anyone. The withdrawn tokens will be sent to /// the owner of the account they were withdrawn out. /// /// Normally it is should not be needed for users to call this manually. /// Funds from withdrawal requests will be sent to the account owner /// immediately by the owner when the block is submitted. /// The user will however need to call this manually if the transfer failed. /// /// All input arrays must have the same size. /// /// @param owners The addresses of the accounts the withdrawal was done for. /// @param minters The addresses of the minters. /// @param nftTypes The NFT token addresses types /// @param tokens The token addresses /// @param nftIDs The token ids function withdrawFromApprovedWithdrawalsNFT( address[] memory owners, address[] memory minters, ExchangeData.NftType[] memory nftTypes, address[] memory tokens, uint256[] memory nftIDs ) external virtual; /// @dev Gets the amount that can be withdrawn immediately with `withdrawFromApprovedWithdrawals`. /// @param owner The address of the account the withdrawal was done for. /// @param token The token address /// @return The amount withdrawable function getAmountWithdrawable( address owner, address token ) external virtual view returns (uint); /// @dev Gets the amount that can be withdrawn immediately with `withdrawFromApprovedWithdrawalsNFT`. /// @param owner The address of the account the withdrawal was done for. /// @param token The token address /// @param nftType The NFT token address types /// @param nftID The token id /// @param minter The NFT minter /// @return The amount withdrawable function getAmountWithdrawableNFT( address owner, address token, ExchangeData.NftType nftType, uint256 nftID, address minter ) external virtual view returns (uint); /// @dev Notifies the exchange that the owner did not process a forced request. /// If this is indeed the case, the exchange will enter withdrawal mode. /// /// Can be called by anyone. /// /// @param accountID The accountID the forced request was made for /// @param tokenID The tokenID of the the forced request function notifyForcedRequestTooOld( uint32 accountID, uint16 tokenID ) external virtual; /// @dev Allows a withdrawal to be done to an adddresss that is different /// than initialy specified in the withdrawal request. This can be used to /// implement functionality like fast withdrawals. /// /// This function can only be called by an agent. /// /// @param from The address of the account that does the withdrawal. /// @param to The address to which 'amount' tokens were going to be withdrawn. /// @param token The address of the token that is withdrawn ('0x0' for ETH). /// @param amount The amount of tokens that are going to be withdrawn. /// @param storageID The storageID of the withdrawal request. /// @param newRecipient The new recipient address of the withdrawal. function setWithdrawalRecipient( address from, address to, address token, uint96 amount, uint32 storageID, address newRecipient ) external virtual; /// @dev Gets the withdrawal recipient. /// /// @param from The address of the account that does the withdrawal. /// @param to The address to which 'amount' tokens were going to be withdrawn. /// @param token The address of the token that is withdrawn ('0x0' for ETH). /// @param amount The amount of tokens that are going to be withdrawn. /// @param storageID The storageID of the withdrawal request. function getWithdrawalRecipient( address from, address to, address token, uint96 amount, uint32 storageID ) external virtual view returns (address); /// @dev Allows an agent to transfer ERC-20 tokens for a user using the allowance /// the user has set for the exchange. This way the user only needs to approve a single exchange contract /// for all exchange/agent features, which allows for a more seamless user experience. /// /// This function can only be called by an agent. /// /// @param from The address of the account that sends the tokens. /// @param to The address to which 'amount' tokens are transferred. /// @param token The address of the token to transfer (ETH is and cannot be suppported). /// @param amount The amount of tokens transferred. function onchainTransferFrom( address from, address to, address token, uint amount ) external virtual; /// @dev Allows an agent to approve a rollup tx. /// /// This function can only be called by an agent. /// /// @param owner The owner of the account /// @param txHash The hash of the transaction function approveTransaction( address owner, bytes32 txHash ) external virtual; /// @dev Allows an agent to approve multiple rollup txs. /// /// This function can only be called by an agent. /// /// @param owners The account owners /// @param txHashes The hashes of the transactions function approveTransactions( address[] calldata owners, bytes32[] calldata txHashes ) external virtual; /// @dev Checks if a rollup tx is approved using the tx's hash. /// /// @param owner The owner of the account that needs to authorize the tx /// @param txHash The hash of the transaction /// @return True if the tx is approved, else false function isTransactionApproved( address owner, bytes32 txHash ) external virtual view returns (bool); // -- Admins -- /// @dev Sets the max time deposits have to wait before becoming withdrawable. /// @param newValue The new value. /// @return The old value. function setMaxAgeDepositUntilWithdrawable( uint32 newValue ) external virtual returns (uint32); /// @dev Returns the max time deposits have to wait before becoming withdrawable. /// @return The value. function getMaxAgeDepositUntilWithdrawable() external virtual view returns (uint32); /// @dev Shuts down the exchange. /// Once the exchange is shutdown all onchain requests are permanently disabled. /// When all requirements are fulfilled the exchange owner can withdraw /// the exchange stake with withdrawStake. /// /// Note that the exchange can still enter the withdrawal mode after this function /// has been invoked successfully. To prevent entering the withdrawal mode before the /// the echange stake can be withdrawn, all withdrawal requests still need to be handled /// for at least MIN_TIME_IN_SHUTDOWN seconds. /// /// Can only be called by the exchange owner. /// /// @return success True if the exchange is shutdown, else False function shutdown() external virtual returns (bool success); /// @dev Gets the protocol fees for this exchange. /// @return syncedAt The timestamp the protocol fees were last updated /// @return takerFeeBips The protocol taker fee /// @return makerFeeBips The protocol maker fee /// @return previousTakerFeeBips The previous protocol taker fee /// @return previousMakerFeeBips The previous protocol maker fee function getProtocolFeeValues() external virtual view returns ( uint32 syncedAt, uint8 takerFeeBips, uint8 makerFeeBips, uint8 previousTakerFeeBips, uint8 previousMakerFeeBips ); /// @dev Gets the domain separator used in this exchange. function getDomainSeparator() external virtual view returns (bytes32); /// @dev set amm pool feeBips value. function setAmmFeeBips(uint8 _feeBips) external virtual; /// @dev get amm pool feeBips value. function getAmmFeeBips() external virtual view returns (uint8); } // File: contracts/amm/libamm/IAmmSharedConfig.sol // Copyright 2017 Loopring Technology Limited. interface IAmmSharedConfig { function maxForcedExitAge() external view returns (uint); function maxForcedExitCount() external view returns (uint); function forcedExitFee() external view returns (uint); } // File: contracts/amm/libamm/AmmData.sol // Copyright 2017 Loopring Technology Limited. /// @title AmmData library AmmData { uint public constant POOL_TOKEN_BASE = 100 * (10 ** 8); uint public constant POOL_TOKEN_MINTED_SUPPLY = uint96(-1); enum PoolTxType { NOOP, JOIN, EXIT } struct PoolConfig { address sharedConfig; address exchange; string poolName; uint32 accountID; address[] tokens; uint96[] weights; uint8 feeBips; string tokenSymbol; } struct PoolJoin { address owner; uint96[] joinAmounts; uint32[] joinStorageIDs; uint96 mintMinAmount; uint96 fee; uint32 validUntil; } struct PoolExit { address owner; uint96 burnAmount; uint32 burnStorageID; // for pool token withdrawal from user to the pool uint96[] exitMinAmounts; // the amount to receive BEFORE paying the fee. uint96 fee; uint32 validUntil; } struct PoolTx { PoolTxType txType; bytes data; bytes signature; } struct Token { address addr; uint96 weight; uint16 tokenID; } struct Context { // functional parameters uint txIdx; // AMM pool state variables bytes32 domainSeparator; uint32 accountID; uint16 poolTokenID; uint8 feeBips; uint totalSupply; Token[] tokens; uint96[] tokenBalancesL2; } struct State { // Pool token state variables string poolName; string symbol; uint _totalSupply; mapping(address => uint) balanceOf; mapping(address => mapping(address => uint)) allowance; mapping(address => uint) nonces; // AMM pool state variables IAmmSharedConfig sharedConfig; Token[] tokens; // The order of the following variables important to minimize loads bytes32 exchangeDomainSeparator; bytes32 domainSeparator; IExchangeV3 exchange; uint32 accountID; uint16 poolTokenID; uint8 feeBips; address exchangeOwner; uint64 shutdownTimestamp; uint16 forcedExitCount; // A map from a user to the forced exit. mapping (address => PoolExit) forcedExit; mapping (bytes32 => bool) approvedTx; } } // File: contracts/aux/access/IBlockReceiver.sol // Copyright 2017 Loopring Technology Limited. /// @title IBlockReceiver /// @author Brecht Devos - <[email protected]> abstract contract IBlockReceiver { function beforeBlockSubmission( bytes calldata txsData, bytes calldata callbackData ) external virtual; } // File: contracts/lib/EIP712.sol // Copyright 2017 Loopring Technology Limited. library EIP712 { struct Domain { string name; string version; address verifyingContract; } bytes32 constant internal EIP712_DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); string constant internal EIP191_HEADER = "\x19\x01"; function hash(Domain memory domain) internal pure returns (bytes32) { uint _chainid; assembly { _chainid := chainid() } return keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(domain.name)), keccak256(bytes(domain.version)), _chainid, domain.verifyingContract ) ); } function hashPacked( bytes32 domainSeparator, bytes32 dataHash ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( EIP191_HEADER, domainSeparator, dataHash ) ); } } // File: contracts/thirdparty/SafeCast.sol // Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/SafeCast.sol /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint40 from uint256, reverting on * overflow (when the input is greater than largest uint40). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 40 bits */ function toUint40(uint256 value) internal pure returns (uint40) { require(value < 2**40, "SafeCast: value doesn\'t fit in 40 bits"); return uint40(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // File: contracts/lib/FloatUtil.sol // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for floats /// @author Brecht Devos - <[email protected]> library FloatUtil { using MathUint for uint; using SafeCast for uint; // Decodes a decimal float value that is encoded like `exponent | mantissa`. // Both exponent and mantissa are in base 10. // Decoding to an integer is as simple as `mantissa * (10 ** exponent)` // Will throw when the decoded value overflows an uint96 /// @param f The float value with 5 bits for the exponent /// @param numBits The total number of bits (numBitsMantissa := numBits - numBitsExponent) /// @return value The decoded integer value. function decodeFloat( uint f, uint numBits ) internal pure returns (uint96 value) { if (f == 0) { return 0; } uint numBitsMantissa = numBits.sub(5); uint exponent = f >> numBitsMantissa; // log2(10**77) = 255.79 < 256 require(exponent <= 77, "EXPONENT_TOO_LARGE"); uint mantissa = f & ((1 << numBitsMantissa) - 1); value = mantissa.mul(10 ** exponent).toUint96(); } // Decodes a decimal float value that is encoded like `exponent | mantissa`. // Both exponent and mantissa are in base 10. // Decoding to an integer is as simple as `mantissa * (10 ** exponent)` // Will throw when the decoded value overflows an uint96 /// @param f The float value with 5 bits exponent, 11 bits mantissa /// @return value The decoded integer value. function decodeFloat16( uint16 f ) internal pure returns (uint96) { uint value = ((uint(f) & 2047) * (10 ** (uint(f) >> 11))); require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits"); return uint96(value); } // Decodes a decimal float value that is encoded like `exponent | mantissa`. // Both exponent and mantissa are in base 10. // Decoding to an integer is as simple as `mantissa * (10 ** exponent)` // Will throw when the decoded value overflows an uint96 /// @param f The float value with 5 bits exponent, 19 bits mantissa /// @return value The decoded integer value. function decodeFloat24( uint24 f ) internal pure returns (uint96) { uint value = ((uint(f) & 524287) * (10 ** (uint(f) >> 19))); require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits"); return uint96(value); } } // File: contracts/core/impl/libexchange/ExchangeSignatures.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeSignatures. /// @dev All methods in this lib are internal, therefore, there is no need /// to deploy this library independently. /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> library ExchangeSignatures { using SignatureUtil for bytes32; function requireAuthorizedTx( ExchangeData.State storage S, address signer, bytes memory signature, bytes32 txHash ) internal // inline call { require(signer != address(0), "INVALID_SIGNER"); // Verify the signature if one is provided, otherwise fall back to an approved tx if (signature.length > 0) { require(txHash.verifySignature(signer, signature), "INVALID_SIGNATURE"); } else { require(S.approvedTx[signer][txHash], "TX_NOT_APPROVED"); delete S.approvedTx[signer][txHash]; } } } // File: contracts/core/impl/libtransactions/AccountUpdateTransaction.sol // Copyright 2017 Loopring Technology Limited. /// @title AccountUpdateTransaction /// @author Brecht Devos - <[email protected]> library AccountUpdateTransaction { using BytesUtil for bytes; using FloatUtil for uint16; using ExchangeSignatures for ExchangeData.State; bytes32 constant public ACCOUNTUPDATE_TYPEHASH = keccak256( "AccountUpdate(address owner,uint32 accountID,uint16 feeTokenID,uint96 maxFee,uint256 publicKey,uint32 validUntil,uint32 nonce)" ); struct AccountUpdate { address owner; uint32 accountID; uint16 feeTokenID; uint96 maxFee; uint96 fee; uint publicKey; uint32 validUntil; uint32 nonce; } // Auxiliary data for each account update struct AccountUpdateAuxiliaryData { bytes signature; uint96 maxFee; uint32 validUntil; } function process( ExchangeData.State storage S, ExchangeData.BlockContext memory ctx, bytes memory data, uint offset, bytes memory auxiliaryData ) internal { // Read the account update AccountUpdate memory accountUpdate; readTx(data, offset, accountUpdate); AccountUpdateAuxiliaryData memory auxData = abi.decode(auxiliaryData, (AccountUpdateAuxiliaryData)); // Fill in withdrawal data missing from DA accountUpdate.validUntil = auxData.validUntil; accountUpdate.maxFee = auxData.maxFee == 0 ? accountUpdate.fee : auxData.maxFee; // Validate require(ctx.timestamp < accountUpdate.validUntil, "ACCOUNT_UPDATE_EXPIRED"); require(accountUpdate.fee <= accountUpdate.maxFee, "ACCOUNT_UPDATE_FEE_TOO_HIGH"); // Calculate the tx hash bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, accountUpdate); // Check onchain authorization S.requireAuthorizedTx(accountUpdate.owner, auxData.signature, txHash); } function readTx( bytes memory data, uint offset, AccountUpdate memory accountUpdate ) internal pure { uint _offset = offset; require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.ACCOUNT_UPDATE), "INVALID_TX_TYPE"); _offset += 1; // Check that this is a conditional offset require(data.toUint8Unsafe(_offset) == 1, "INVALID_AUXILIARYDATA_DATA"); _offset += 1; // Extract the data from the tx data // We don't use abi.decode for this because of the large amount of zero-padding // bytes the circuit would also have to hash. accountUpdate.owner = data.toAddressUnsafe(_offset); _offset += 20; accountUpdate.accountID = data.toUint32Unsafe(_offset); _offset += 4; accountUpdate.feeTokenID = data.toUint16Unsafe(_offset); _offset += 2; accountUpdate.fee = data.toUint16Unsafe(_offset).decodeFloat16(); _offset += 2; accountUpdate.publicKey = data.toUintUnsafe(_offset); _offset += 32; accountUpdate.nonce = data.toUint32Unsafe(_offset); _offset += 4; } function hashTx( bytes32 DOMAIN_SEPARATOR, AccountUpdate memory accountUpdate ) internal pure returns (bytes32) { return EIP712.hashPacked( DOMAIN_SEPARATOR, keccak256( abi.encode( ACCOUNTUPDATE_TYPEHASH, accountUpdate.owner, accountUpdate.accountID, accountUpdate.feeTokenID, accountUpdate.maxFee, accountUpdate.publicKey, accountUpdate.validUntil, accountUpdate.nonce ) ) ); } } // File: contracts/aux/agents/LoopringWalletAgent.sol // Copyright 2017 Loopring Technology Limited. /// @title LoopringWalletAgent /// @dev Agent to allow authorizing L2 transactions using an undeployed Loopring Smart Wallet /// @author Brecht Devos - <[email protected]> contract LoopringWalletAgent is WalletDeploymentLib, IBlockReceiver { using AddressUtil for address; using SignatureUtil for bytes32; // Maximum amount of time this agent can still authorize transactions // approved by the initial wallet owner after the wallet has been deployed. uint public constant MAX_TIME_VALID_AFTER_CREATION = 7 days; address public immutable deployer; IExchangeV3 public immutable exchange; bytes32 public immutable EXCHANGE_DOMAIN_SEPARATOR; struct WalletSignatureData { bytes signature; uint96 maxFee; uint32 validUntil; address walletOwner; uint salt; } constructor( address _walletImplementation, address _deployer, IExchangeV3 _exchange ) WalletDeploymentLib(_walletImplementation) { deployer = _deployer; exchange = _exchange; EXCHANGE_DOMAIN_SEPARATOR = _exchange.getDomainSeparator(); } // Allows authorizing transactions in an independent transaction function approveTransactionsFor( address[] calldata wallets, bytes32[] calldata txHashes, bytes[] calldata signatures ) external virtual { require(txHashes.length == wallets.length, "INVALID_DATA"); require(signatures.length == wallets.length, "INVALID_DATA"); // Verify the signatures for (uint i = 0; i < wallets.length; i++) { WalletSignatureData memory data = abi.decode(signatures[i], (WalletSignatureData)); require( _canInitialOwnerAuthorizeTransactions(wallets[i], msg.sender, data.salt) || _isUsableSignatureForWallet( wallets[i], txHashes[i], data ), "INVALID_SIGNATURE" ); } // Approve the transactions on the exchange exchange.approveTransactions(wallets, txHashes); } // Allow transactions to be authorized while submitting a block function beforeBlockSubmission( bytes calldata txsData, bytes calldata callbackData ) external override virtual { _beforeBlockSubmission(txsData, callbackData); } // Returns true if the signature can be used for authorizing the transaction function isUsableSignatureForWallet( address wallet, bytes32 hash, bytes memory signature ) public view returns (bool) { WalletSignatureData memory data = abi.decode(signature, (WalletSignatureData)); return _isUsableSignatureForWallet(wallet, hash, data); } // Returns true if just the signature is valid (but it may have expired) function isValidSignatureForWallet( address wallet, bytes32 hash, bytes memory signature ) public view returns (bool) { WalletSignatureData memory data = abi.decode(signature, (WalletSignatureData)); return _isValidSignatureForWallet(wallet, hash, data); } // Returns the timestamp up until the signature can be used function getSignatureExpiry( address wallet, bytes32 hash, bytes memory signature ) public view returns (uint) { WalletSignatureData memory data = abi.decode(signature, (WalletSignatureData)); if (!_isValidSignatureForWallet(wallet, hash, data)) { return 0; } else { return getInitialOwnerExpiry(wallet); } } // Returns the timestamp up until the initial owner can authorize transactions function getInitialOwnerExpiry( address walletAddress ) public view returns (uint) { // Always allowed when the smart wallet hasn't been deployed yet if (!walletAddress.isContract()) { return type(uint).max; } ILoopringWalletV2 wallet = ILoopringWalletV2(walletAddress); // Allow the initial wallet owner to sign transactions after deployment for some limited time return wallet.getCreationTimestamp() + MAX_TIME_VALID_AFTER_CREATION; } // == Internal Functions == function _beforeBlockSubmission( bytes calldata txsData, bytes calldata callbackData ) internal view returns (AccountUpdateTransaction.AccountUpdate memory accountUpdate) { WalletSignatureData memory data = abi.decode(callbackData, (WalletSignatureData)); // Read the AccountUpdate transaction AccountUpdateTransaction.readTx(txsData, 0, accountUpdate); // Fill in withdrawal data missing from DA accountUpdate.validUntil = data.validUntil; accountUpdate.maxFee = data.maxFee == 0 ? accountUpdate.fee : data.maxFee; // Validate require(block.timestamp < accountUpdate.validUntil, "ACCOUNT_UPDATE_EXPIRED"); require(accountUpdate.fee <= accountUpdate.maxFee, "ACCOUNT_UPDATE_FEE_TOO_HIGH"); // Calculate the transaction hash bytes32 txHash = AccountUpdateTransaction.hashTx(EXCHANGE_DOMAIN_SEPARATOR, accountUpdate); // Verify the signature require( _isUsableSignatureForWallet( accountUpdate.owner, txHash, data ), "INVALID_SIGNATURE" ); // Make sure we have consumed exactly the expected number of transactions require(txsData.length == ExchangeData.TX_DATA_AVAILABILITY_SIZE, "INVALID_NUM_TXS"); } function _isUsableSignatureForWallet( address wallet, bytes32 hash, WalletSignatureData memory data ) internal view returns (bool) { // Verify that the signature is valid and the initial owner is still allowed // to authorize transactions for the wallet. return _isValidSignatureForWallet(wallet, hash, data) && _isInitialOwnerUsable(wallet); } function _isValidSignatureForWallet( address wallet, bytes32 hash, WalletSignatureData memory data ) internal view returns (bool) { // Verify that the account owner is the initial owner of the smart wallet // and that the signature is a valid signature from the initial owner. return _isInitialOwner(wallet, data.walletOwner, data.salt) && hash.verifySignature(data.walletOwner, data.signature); } function _canInitialOwnerAuthorizeTransactions( address wallet, address walletOwner, uint salt ) internal view returns (bool) { // Verify that the initial owner is the owner of the wallet // and can still be used to authorize transactions return _isInitialOwner(wallet, walletOwner, salt) && _isInitialOwnerUsable(wallet); } function _isInitialOwnerUsable( address wallet ) internal view virtual returns (bool) { return block.timestamp <= getInitialOwnerExpiry(wallet); } function _isInitialOwner( address wallet, address walletOwner, uint salt ) internal view returns (bool) { return _computeWalletAddress(walletOwner, salt, deployer) == wallet; } } // File: contracts/aux/agents/DestroyableWalletAgent.sol // Copyright 2017 Loopring Technology Limited. /// @title DestroyableWalletAgent /// @dev Agent that allows setting up accounts that can easily be rendered unusable /// @author Brecht Devos - <[email protected]> contract DestroyableWalletAgent is LoopringWalletAgent { struct WalletData { uint32 accountID; bool destroyed; } mapping(address => WalletData) public walletData; constructor( address _walletImplementation, address _deployer, IExchangeV3 exchange ) LoopringWalletAgent(_walletImplementation, _deployer, exchange) {} function beforeBlockSubmission( bytes calldata txsData, bytes calldata callbackData ) external override { AccountUpdateTransaction.AccountUpdate memory accountUpdate; accountUpdate = LoopringWalletAgent._beforeBlockSubmission(txsData, callbackData); WalletData storage wallet = walletData[accountUpdate.owner]; if (wallet.accountID == 0) { // First use of this wallet, store the accountID wallet.accountID = accountUpdate.accountID; } else { // Only allow a single account on L2 to ever sign L2 transactions // for this wallet address require( wallet.accountID == accountUpdate.accountID, "ACCOUNT_ALREADY_EXISTS_FOR_WALLET" ); } // Destroy the wallet if the EdDSA public key is set to 0 if (accountUpdate.publicKey == 0) { wallet.destroyed = true; } } /// @dev Computes the destructable wallet address /// @param owner The owner. /// @param salt A salt. /// @return The wallet address function computeWalletAddress( address owner, uint salt ) public view returns (address) { return _computeWalletAddress( owner, salt, deployer ); } /// @dev Checks if the wallet can still be used /// @param wallet The wallet address. /// @return Returns true if destroyed, else false function isDestroyed( address wallet ) public view returns (bool) { return walletData[wallet].destroyed; } // Disable `approveTransactionsFor` function approveTransactionsFor( address[] calldata /*wallets*/, bytes32[] calldata /*txHashes*/, bytes[] calldata /*signatures*/ ) external override pure { revert("UNSUPPORTED"); } // == Internal Functions == function _isInitialOwnerUsable( address wallet ) internal view override returns (bool) { // Also disallow the owner to use the wallet when destroyed return LoopringWalletAgent._isInitialOwnerUsable(wallet) && !isDestroyed(wallet); } }
Disable `approveTransactionsFor`
function approveTransactionsFor( address[] calldata /*wallets*/, bytes32[] calldata /*txHashes*/, bytes[] calldata /*signatures*/ ) external override pure { revert("UNSUPPORTED"); }
1,427,413
[ 1, 11879, 1375, 12908, 537, 14186, 1290, 68, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6617, 537, 14186, 1290, 12, 203, 3639, 1758, 8526, 745, 892, 1748, 8019, 2413, 5549, 16, 203, 3639, 1731, 1578, 8526, 745, 892, 1748, 978, 14455, 5549, 16, 203, 3639, 1731, 8526, 282, 745, 892, 1748, 30730, 5549, 203, 3639, 262, 203, 3639, 3903, 203, 3639, 3849, 203, 3639, 16618, 203, 565, 288, 203, 3639, 15226, 2932, 2124, 21134, 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 ]
./full_match/3/0x25a5F12a707Bc30b2081f750976E489b62F567aE/sources/localhost/deployments/Option.full.sol
* @title Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function symbol() external view returns (string memory); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function totalSupply() external view returns (uint256); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); pragma solidity ^0.7.3; }
8,097,047
[ 1, 1358, 434, 326, 4232, 39, 3462, 4529, 487, 2553, 316, 326, 512, 2579, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 654, 39, 3462, 288, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 203, 565, 445, 3273, 1435, 3903, 1476, 1135, 261, 1080, 3778, 1769, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 565, 445, 7412, 1265, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 10929, 7009, 1359, 12, 2867, 17571, 264, 16, 2254, 5034, 3096, 620, 13, 3903, 1135, 261, 6430, 1769, 203, 565, 445, 20467, 7009, 1359, 12, 2867, 17571, 264, 16, 2254, 5034, 10418, 329, 620, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 27, 18, 23, 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 ]
// SPDX-License-Identifier: Unlicense pragma solidity >=0.7.6; import 'src/tsm/contracts/NutBerryTokenBridge.sol'; import 'src/v1/contracts/NutBerryFlavorV1.sol'; import './V1TestOneChallenge.sol'; contract V1TestOne is NutBerryFlavorV1, V1TestOneChallenge { function submitCustomBlock (uint256, uint256) external { _createBlockMessage(); } // ERC-20 function _BALANCES_KEY (address token, address account) internal returns (uint256 ret) { assembly { mstore(0, token) mstore(32, account) ret := keccak256(0, 64) } } // ERC-721 function _OWNERS_KEY (address token, uint256 tokenId) internal returns (uint256 ret) { assembly { mstore(0, token) mstore(32, tokenId) ret := keccak256(0, 64) } } function _NONCE_KEY (address a) internal returns (uint256 ret) { assembly { mstore(0, 0xacacac) mstore(32, a) ret := keccak256(0, 64) } } function _increment (uint256 k, uint256 v) internal { _sstore(k, _sload(k) + v); } function _incrementNonce (address a) internal { _increment(_NONCE_KEY(a), 1); NutBerryCore._setStorageL1(bytes32(uint256(a)), 1); } function owners (address token, uint256 tokenId) public returns (address) { return address(_sload(_OWNERS_KEY(token, tokenId))); } function balances (address token, address account) public returns (uint256) { return _sload(_BALANCES_KEY(token, account)); } function nonces (address account) public returns (uint256) { return _sload(_NONCE_KEY(account)); } /// @dev State transition when a user deposits a token. function onDeposit (address owner, address token, uint256 value, uint256 tokenType) external { // all power the core protocol require(msg.sender == address(this)); if (NutBerryTokenBridge._getTokenType(token) == 0) { NutBerryTokenBridge._setTokenType(token, tokenType); } if (tokenType == 1) { _increment(_BALANCES_KEY(token, owner), value); } else { _sstore(_OWNERS_KEY(token, value), uint(owner)); } } event Message(bytes data); function onCustomBlockBeacon (bytes memory data) external { require(msg.sender == address(this)); _storeCallDataHash(); _sstore(uint256(keccak256(data)), _getTime()); emit Message(data); } function _storeCallDataHash () internal { uint ptr; uint hash; assembly { let size := calldatasize() // that becomes more work on L1 (challenge) if origin() { // < usual calldata... > // < 32 bytes timestamp > // < read witnesses... - each 32 bytes > // < # of witness elements - 32 bytes> // < write witnesses - each 32 bytes > // < # of witness elements - 32 bytes > size := sub(calldatasize(), 32) // load the length of nElements and sub size := sub(size, mul(32, calldataload(size))) // points to the start of `write witnesses` size := sub(size, 32) // points at `# read witnesses` and subtracts size := sub(size, mul(32, calldataload(size))) // sub again (block timestamp) size := sub(size, 32) } ptr := mload(64) calldatacopy(ptr, 0, size) hash := keccak256(ptr, size) log1(0, 0, hash) } _sstore(hash, ptr); } function onExit (address msgSender, address token, uint256 value) external { // all power the core protocol require(msg.sender == address(this)); _storeCallDataHash(); _incrementNonce(msgSender); if (NutBerryTokenBridge._getTokenType(token) == 1) { _incrementExit(token, msgSender, value); } else { _setERC721Exit(token, msgSender, value); } assembly { let ptr := 0 let size := 32 mstore(ptr, token) log0(ptr, size) ptr := add(ptr, size) mstore(ptr, value) log0(ptr, size) } } function onTransfer (address msgSender, address to, address token, uint256 value) external { // all power the core protocol require(msg.sender == address(this)); _storeCallDataHash(); _incrementNonce(msgSender); assembly { let ptr := 0 let size := 32 mstore(ptr, to) log0(ptr, size) ptr := add(ptr, size) mstore(ptr, token) log0(ptr, size) ptr := add(ptr, size) mstore(ptr, value) log0(ptr, size) } } function onOne (address msgSender, bytes memory one, uint256 nonce, bytes memory two) external { // all power the core protocol require(msg.sender == address(this)); _storeCallDataHash(); _incrementNonce(msgSender); assembly { let ptr := mload(64) let size := 32 size := mload(one) log0(add(one, 32), size) size := 32 mstore(ptr, nonce) log0(ptr, size) size := mload(two) log0(add(two, 32), size) } } function onTwo (address msgSender, bytes24 foo) external { require(msg.sender == address(this)); _storeCallDataHash(); _incrementNonce(msgSender); uint tmp; assembly { let ptr := mload(64) let size := 32 mstore(ptr, foo) log0(ptr, size) tmp := keccak256(0, 32) } for (uint i = 0; i < 3000; i++) { _sstore(0x4411, tmp); } } function onThree (address msgSender, int128) external { require(msg.sender == address(this)); _storeCallDataHash(); _incrementNonce(msgSender); uint tmp = 0; for (uint i = 0; i < 0xff; i++) { uint _now = _getTime(); if (_now < 1623777000 || _now > 2623777000) { revert(); } tmp += _now; } _sstore(0x9241, tmp); assembly { mstore(0, calldataload(36)) log0(0, 32) } } function onShouldRevert (address, uint256 shouldRevertWithString) external { require(msg.sender == address(this)); if (shouldRevertWithString == 0) { revert(); } revert('hello world'); } function signalUpgradeTo (address newImplementation) external { emit NutBerryEvents.RollupUpgrade(newImplementation); } }
all power the core protocol
function onOne (address msgSender, bytes memory one, uint256 nonce, bytes memory two) external { require(msg.sender == address(this)); _storeCallDataHash(); _incrementNonce(msgSender); assembly { let ptr := mload(64) let size := 32 size := mload(one) log0(add(one, 32), size) size := 32 mstore(ptr, nonce) log0(ptr, size) size := mload(two) log0(add(two, 32), size) } }
12,770,373
[ 1, 454, 7212, 326, 2922, 1771, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 603, 3335, 261, 2867, 1234, 12021, 16, 1731, 3778, 1245, 16, 2254, 5034, 7448, 16, 1731, 3778, 2795, 13, 3903, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 1758, 12, 2211, 10019, 203, 565, 389, 2233, 1477, 751, 2310, 5621, 203, 565, 389, 15016, 13611, 12, 3576, 12021, 1769, 203, 203, 565, 19931, 288, 203, 1377, 2231, 6571, 519, 312, 945, 12, 1105, 13, 203, 1377, 2231, 963, 519, 3847, 203, 203, 1377, 963, 519, 312, 945, 12, 476, 13, 203, 1377, 613, 20, 12, 1289, 12, 476, 16, 3847, 3631, 963, 13, 203, 203, 1377, 963, 519, 3847, 203, 1377, 312, 2233, 12, 6723, 16, 7448, 13, 203, 1377, 613, 20, 12, 6723, 16, 963, 13, 203, 203, 1377, 963, 519, 312, 945, 12, 15415, 13, 203, 1377, 613, 20, 12, 1289, 12, 15415, 16, 3847, 3631, 963, 13, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1313161554/0xFE878CdC89e9d7Cd643339197704E40DF851b8a8/sources/_contracts/ReaperStrategyCompoundLeverage.sol
* @dev This strategy will deposit and leverage a token on Compound to maximize yield by farming reward tokens/
contract ReaperStrategyCompoundLeverage is ReaperBaseStrategyv2 { using SafeERC20Upgradeable for IERC20Upgradeable; address public constant nativeToken = address(0xC42C30aC6Cc15faC9bD938618BcaA1a1FaE8501d); address public constant feesToken = address(0xB12BFcA5A55806AaF64E99521918A4bf0fC40802); address public constant rewardToken = address(0x9f1F933C660a1DC856F0E0Fe058435879c5CCEf0); address public dualRewardToken; address public want; CErc20I public cWant; address public constant UNI_ROUTER = address(0x2CB45Edb4517d5947aFdE3BEAbF95A582506858B); address public constant REWARD_DISTRIBUTOR = address(0x98E8d4b4F53FA2a2d1b9C651AF919Fc839eE4c1a); IComptroller public comptroller; address[] public rewardToNativeRoute; address[] public dualRewardToNativeRoute; address[] public nativeToFeesRoute; address[] public nativeToWantRoute; address[] public markets; uint256 public constant MANTISSA = 1e18; uint256 public constant MAX_BORROW_DEPTH = 15; uint256 public ltvSafetyZone; uint256 public targetLTV; uint256 public allowedLTVDrift; uint256 public balanceOfPool; uint256 public borrowDepth; uint256 public minWantToLeverage; uint256 public minRewardToSell; uint256 public withdrawSlippageTolerance; bool public isDualRewardActive; uint8 public dualRewardIndex; function initialize( address _vault, address[] memory _feeRemitters, address[] memory _strategists, address[] memory _multisigRoles, address _cWant ) public initializer { __ReaperBaseStrategy_init(_vault, _feeRemitters, _strategists, _multisigRoles); cWant = CErc20I(_cWant); want = cWant.underlying(); comptroller = IComptroller(cWant.comptroller()); markets = [_cWant]; rewardToNativeRoute = [rewardToken, nativeToken]; nativeToFeesRoute = [nativeToken, feesToken]; nativeToWantRoute = [nativeToken, want]; ltvSafetyZone = 0.70 ether; allowedLTVDrift = 0.01 ether; setTargetLtv(type(uint256).max); balanceOfPool = 0; borrowDepth = 2; minWantToLeverage = 1000; minRewardToSell = 1000; withdrawSlippageTolerance = 50; dualRewardToken = address(0xC42C30aC6Cc15faC9bD938618BcaA1a1FaE8501d); isDualRewardActive = true; dualRewardIndex = 1; _giveAllowances(); comptroller.enterMarkets(markets); } function _deposit() internal override doUpdateBalance { CErc20I(cWant).mint(balanceOfWant()); uint256 _ltv = _calculateLTVAfterWithdraw(0); if (_shouldLeverage(_ltv)) { _leverMax(); _deleverage(0); } } function _deposit() internal override doUpdateBalance { CErc20I(cWant).mint(balanceOfWant()); uint256 _ltv = _calculateLTVAfterWithdraw(0); if (_shouldLeverage(_ltv)) { _leverMax(); _deleverage(0); } } } else if (_shouldDeleverage(_ltv)) { function _withdraw(uint256 _withdrawAmount) internal override doUpdateBalance { uint256 _ltv = _calculateLTVAfterWithdraw(_withdrawAmount); if (_shouldLeverage(_ltv)) { _withdrawUnderlyingToVault(_withdrawAmount); _leverMax(); _deleverage(_withdrawAmount); _withdrawUnderlyingToVault(_withdrawAmount); _withdrawUnderlyingToVault(_withdrawAmount); } } function _withdraw(uint256 _withdrawAmount) internal override doUpdateBalance { uint256 _ltv = _calculateLTVAfterWithdraw(_withdrawAmount); if (_shouldLeverage(_ltv)) { _withdrawUnderlyingToVault(_withdrawAmount); _leverMax(); _deleverage(_withdrawAmount); _withdrawUnderlyingToVault(_withdrawAmount); _withdrawUnderlyingToVault(_withdrawAmount); } } } else if (_shouldDeleverage(_ltv)) { } else { function _harvestCore() internal override { _claimRewards(); _swapRewardsToNative(); _chargeFees(); _swapToWant(); } function _claimRewards() internal { IRewardDistributor(REWARD_DISTRIBUTOR).claimReward(0, payable(address(this)), markets); if (isDualRewardActive) { IRewardDistributor(REWARD_DISTRIBUTOR).claimReward(dualRewardIndex, payable(address(this)), markets); } } function _claimRewards() internal { IRewardDistributor(REWARD_DISTRIBUTOR).claimReward(0, payable(address(this)), markets); if (isDualRewardActive) { IRewardDistributor(REWARD_DISTRIBUTOR).claimReward(dualRewardIndex, payable(address(this)), markets); } } function _swapRewardsToNative() internal { uint256 rewardBalance = IERC20Upgradeable(rewardToken).balanceOf(address(this)); if (rewardBalance >= minRewardToSell) { _swap(rewardBalance, rewardToNativeRoute); } uint256 dualRewardBalance = IERC20Upgradeable(dualRewardToken).balanceOf(address(this)); if (dualRewardBalance >= minRewardToSell && nativeToken != dualRewardToken) { _swap(dualRewardBalance, dualRewardToNativeRoute); } } function _swapRewardsToNative() internal { uint256 rewardBalance = IERC20Upgradeable(rewardToken).balanceOf(address(this)); if (rewardBalance >= minRewardToSell) { _swap(rewardBalance, rewardToNativeRoute); } uint256 dualRewardBalance = IERC20Upgradeable(dualRewardToken).balanceOf(address(this)); if (dualRewardBalance >= minRewardToSell && nativeToken != dualRewardToken) { _swap(dualRewardBalance, dualRewardToNativeRoute); } } function _swapRewardsToNative() internal { uint256 rewardBalance = IERC20Upgradeable(rewardToken).balanceOf(address(this)); if (rewardBalance >= minRewardToSell) { _swap(rewardBalance, rewardToNativeRoute); } uint256 dualRewardBalance = IERC20Upgradeable(dualRewardToken).balanceOf(address(this)); if (dualRewardBalance >= minRewardToSell && nativeToken != dualRewardToken) { _swap(dualRewardBalance, dualRewardToNativeRoute); } } function _swap(uint256 _amount, address[] memory _path) internal { IERC20Upgradeable(_path[0]).safeIncreaseAllowance(UNI_ROUTER, _amount); IUniswapRouter(UNI_ROUTER).swapExactTokensForTokensSupportingFeeOnTransferTokens( _amount, 0, _path, address(this), block.timestamp ); } function _chargeFees() internal { uint256 nativeFee = (IERC20Upgradeable(nativeToken).balanceOf(address(this)) * totalFee) / PERCENT_DIVISOR; uint256 beforeSwapBal = IERC20Upgradeable(feesToken).balanceOf(address(this)); _swap(nativeFee, nativeToFeesRoute); uint256 fees = IERC20Upgradeable(feesToken).balanceOf(address(this)) - beforeSwapBal; if (fees != 0) { uint256 callFeeToUser = (fees * callFee) / PERCENT_DIVISOR; uint256 treasuryFeeToVault = (fees * treasuryFee) / PERCENT_DIVISOR; uint256 feeToStrategist = (treasuryFeeToVault * strategistFee) / PERCENT_DIVISOR; treasuryFeeToVault -= feeToStrategist; IERC20Upgradeable(feesToken).safeTransfer(msg.sender, callFeeToUser); IERC20Upgradeable(feesToken).safeTransfer(treasury, treasuryFeeToVault); IERC20Upgradeable(feesToken).safeTransfer(strategistRemitter, feeToStrategist); } } function _chargeFees() internal { uint256 nativeFee = (IERC20Upgradeable(nativeToken).balanceOf(address(this)) * totalFee) / PERCENT_DIVISOR; uint256 beforeSwapBal = IERC20Upgradeable(feesToken).balanceOf(address(this)); _swap(nativeFee, nativeToFeesRoute); uint256 fees = IERC20Upgradeable(feesToken).balanceOf(address(this)) - beforeSwapBal; if (fees != 0) { uint256 callFeeToUser = (fees * callFee) / PERCENT_DIVISOR; uint256 treasuryFeeToVault = (fees * treasuryFee) / PERCENT_DIVISOR; uint256 feeToStrategist = (treasuryFeeToVault * strategistFee) / PERCENT_DIVISOR; treasuryFeeToVault -= feeToStrategist; IERC20Upgradeable(feesToken).safeTransfer(msg.sender, callFeeToUser); IERC20Upgradeable(feesToken).safeTransfer(treasury, treasuryFeeToVault); IERC20Upgradeable(feesToken).safeTransfer(strategistRemitter, feeToStrategist); } } function _swapToWant() internal { if (want == nativeToken) { return; } uint256 nativeBalance = IERC20Upgradeable(nativeToken).balanceOf(address(this)); if (nativeBalance != 0) { _swap(nativeBalance, nativeToWantRoute); } } function _swapToWant() internal { if (want == nativeToken) { return; } uint256 nativeBalance = IERC20Upgradeable(nativeToken).balanceOf(address(this)); if (nativeBalance != 0) { _swap(nativeBalance, nativeToWantRoute); } } function _swapToWant() internal { if (want == nativeToken) { return; } uint256 nativeBalance = IERC20Upgradeable(nativeToken).balanceOf(address(this)); if (nativeBalance != 0) { _swap(nativeBalance, nativeToWantRoute); } } function balanceOf() public view override returns (uint256) { return balanceOfWant() + balanceOfPool; } function balanceOfWant() public view returns (uint256) { return IERC20Upgradeable(want).balanceOf(address(this)); } function estimateHarvest() external view override returns (uint256 profit, uint256 callFeeToUser) { uint256 rewards = IRewardDistributor(REWARD_DISTRIBUTOR).rewardAccrued(0, address(this)); if (!isDualRewardActive && rewards == 0) { return (0, 0); } profit += IUniswapRouter(UNI_ROUTER).getAmountsOut(rewards, rewardToNativeRoute)[1]; if (isDualRewardActive) { rewards = IRewardDistributor(REWARD_DISTRIBUTOR).rewardAccrued(dualRewardIndex, address(this)); if (rewards != 0) { profit += IUniswapRouter(UNI_ROUTER).getAmountsOut(rewards, dualRewardToNativeRoute)[1]; } } uint256 nativeFee = (profit * totalFee) / PERCENT_DIVISOR; callFeeToUser = (nativeFee * callFee) / PERCENT_DIVISOR; profit -= nativeFee; } function estimateHarvest() external view override returns (uint256 profit, uint256 callFeeToUser) { uint256 rewards = IRewardDistributor(REWARD_DISTRIBUTOR).rewardAccrued(0, address(this)); if (!isDualRewardActive && rewards == 0) { return (0, 0); } profit += IUniswapRouter(UNI_ROUTER).getAmountsOut(rewards, rewardToNativeRoute)[1]; if (isDualRewardActive) { rewards = IRewardDistributor(REWARD_DISTRIBUTOR).rewardAccrued(dualRewardIndex, address(this)); if (rewards != 0) { profit += IUniswapRouter(UNI_ROUTER).getAmountsOut(rewards, dualRewardToNativeRoute)[1]; } } uint256 nativeFee = (profit * totalFee) / PERCENT_DIVISOR; callFeeToUser = (nativeFee * callFee) / PERCENT_DIVISOR; profit -= nativeFee; } function estimateHarvest() external view override returns (uint256 profit, uint256 callFeeToUser) { uint256 rewards = IRewardDistributor(REWARD_DISTRIBUTOR).rewardAccrued(0, address(this)); if (!isDualRewardActive && rewards == 0) { return (0, 0); } profit += IUniswapRouter(UNI_ROUTER).getAmountsOut(rewards, rewardToNativeRoute)[1]; if (isDualRewardActive) { rewards = IRewardDistributor(REWARD_DISTRIBUTOR).rewardAccrued(dualRewardIndex, address(this)); if (rewards != 0) { profit += IUniswapRouter(UNI_ROUTER).getAmountsOut(rewards, dualRewardToNativeRoute)[1]; } } uint256 nativeFee = (profit * totalFee) / PERCENT_DIVISOR; callFeeToUser = (nativeFee * callFee) / PERCENT_DIVISOR; profit -= nativeFee; } function estimateHarvest() external view override returns (uint256 profit, uint256 callFeeToUser) { uint256 rewards = IRewardDistributor(REWARD_DISTRIBUTOR).rewardAccrued(0, address(this)); if (!isDualRewardActive && rewards == 0) { return (0, 0); } profit += IUniswapRouter(UNI_ROUTER).getAmountsOut(rewards, rewardToNativeRoute)[1]; if (isDualRewardActive) { rewards = IRewardDistributor(REWARD_DISTRIBUTOR).rewardAccrued(dualRewardIndex, address(this)); if (rewards != 0) { profit += IUniswapRouter(UNI_ROUTER).getAmountsOut(rewards, dualRewardToNativeRoute)[1]; } } uint256 nativeFee = (profit * totalFee) / PERCENT_DIVISOR; callFeeToUser = (nativeFee * callFee) / PERCENT_DIVISOR; profit -= nativeFee; } function calculateLTV() external view returns (uint256 ltv) { (, uint256 cWantBalance, uint256 borrowed, uint256 exchangeRate) = cWant.getAccountSnapshot(address(this)); uint256 supplied = (cWantBalance * exchangeRate) / MANTISSA; if (supplied == 0 || borrowed == 0) { return 0; } ltv = (MANTISSA * borrowed) / supplied; } function calculateLTV() external view returns (uint256 ltv) { (, uint256 cWantBalance, uint256 borrowed, uint256 exchangeRate) = cWant.getAccountSnapshot(address(this)); uint256 supplied = (cWantBalance * exchangeRate) / MANTISSA; if (supplied == 0 || borrowed == 0) { return 0; } ltv = (MANTISSA * borrowed) / supplied; } function manualDeleverage(uint256 amount) external doUpdateBalance { _atLeastRole(STRATEGIST); require(cWant.redeemUnderlying(amount) == 0); require(cWant.repayBorrow(amount) == 0); } function manualReleaseWant(uint256 amount) external doUpdateBalance { _atLeastRole(STRATEGIST); require(cWant.redeemUnderlying(amount) == 0); } function setTargetLtv(uint256 _ltv) public { _atLeastRole(KEEPER); (, uint256 collateralFactorMantissa, ) = comptroller.markets(address(cWant)); uint256 maxSafeLTV = (collateralFactorMantissa * ltvSafetyZone) / MANTISSA; if (_ltv > maxSafeLTV) { _ltv = maxSafeLTV; } require(collateralFactorMantissa > _ltv + allowedLTVDrift); targetLTV = _ltv; } function setTargetLtv(uint256 _ltv) public { _atLeastRole(KEEPER); (, uint256 collateralFactorMantissa, ) = comptroller.markets(address(cWant)); uint256 maxSafeLTV = (collateralFactorMantissa * ltvSafetyZone) / MANTISSA; if (_ltv > maxSafeLTV) { _ltv = maxSafeLTV; } require(collateralFactorMantissa > _ltv + allowedLTVDrift); targetLTV = _ltv; } function setLtvSafetyZone(uint256 _newLtvSafetyZone) external { _atLeastRole(STRATEGIST); require(_newLtvSafetyZone < 0.97 ether); ltvSafetyZone = _newLtvSafetyZone; } function setAllowedLtvDrift(uint256 _drift) external { _atLeastRole(STRATEGIST); (, uint256 collateralFactorMantissa, ) = comptroller.markets(address(cWant)); require(collateralFactorMantissa > targetLTV + _drift); allowedLTVDrift = _drift; } function setBorrowDepth(uint256 _borrowDepth) external { _atLeastRole(STRATEGIST); require(_borrowDepth <= MAX_BORROW_DEPTH); borrowDepth = _borrowDepth; } function setMinRewardToSell(uint256 _minRewardToSell) external { _atLeastRole(STRATEGIST); minRewardToSell = _minRewardToSell; } function setMinWantToLeverage(uint256 _minWantToLeverage) external { _atLeastRole(STRATEGIST); minWantToLeverage = _minWantToLeverage; } function setWithdrawSlippageTolerance(uint256 _withdrawSlippageTolerance) external { _atLeastRole(STRATEGIST); withdrawSlippageTolerance = _withdrawSlippageTolerance; } function configureDualReward( bool _isDualRewardActive, address _dualRewardToken, uint8 _dualRewardIndex, address[] calldata _newDualRewardToNativeRoute ) external { _atLeastRole(STRATEGIST); require(_newDualRewardToNativeRoute[0] == _dualRewardToken); require(_newDualRewardToNativeRoute[_newDualRewardToNativeRoute.length - 1] == nativeToken); isDualRewardActive = _isDualRewardActive; dualRewardToken = _dualRewardToken; dualRewardIndex = _dualRewardIndex; delete dualRewardToNativeRoute; dualRewardToNativeRoute = _newDualRewardToNativeRoute; } function _retireStrat() internal override doUpdateBalance { _claimRewards(); _swapRewardsToNative(); _swapToWant(); _deleverage(type(uint256).max); _withdrawUnderlyingToVault(balanceOfPool); } function _reclaimWant() internal override doUpdateBalance { _deleverage(type(uint256).max); } function getCurrentPosition() public view returns (uint256 supplied, uint256 borrowed) { (, uint256 cWantBalance, uint256 borrowBalance, uint256 exchangeRate) = cWant.getAccountSnapshot(address(this)); borrowed = borrowBalance; supplied = (cWantBalance * exchangeRate) / MANTISSA; } function updateBalance() public { uint256 supplyBalance = CErc20I(cWant).balanceOfUnderlying(address(this)); uint256 borrowBalance = CErc20I(cWant).borrowBalanceCurrent(address(this)); balanceOfPool = supplyBalance - borrowBalance; } function _leverMax() internal { uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); uint256 realSupply = supplied - borrowed; uint256 newBorrow = _getMaxBorrowFromSupplied(realSupply, targetLTV); uint256 totalAmountToBorrow = newBorrow - borrowed; for (uint256 i = 0; i < borrowDepth && totalAmountToBorrow > minWantToLeverage; i++) { totalAmountToBorrow -= _leverUpStep(totalAmountToBorrow); } } function _leverMax() internal { uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); uint256 realSupply = supplied - borrowed; uint256 newBorrow = _getMaxBorrowFromSupplied(realSupply, targetLTV); uint256 totalAmountToBorrow = newBorrow - borrowed; for (uint256 i = 0; i < borrowDepth && totalAmountToBorrow > minWantToLeverage; i++) { totalAmountToBorrow -= _leverUpStep(totalAmountToBorrow); } } function _leverUpStep(uint256 _borrowAmount) internal returns (uint256) { if (_borrowAmount == 0) { return 0; } uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); (, uint256 collateralFactorMantissa, ) = comptroller.markets(address(cWant)); uint256 canBorrow = (supplied * collateralFactorMantissa) / MANTISSA; canBorrow -= borrowed; if (canBorrow < _borrowAmount) { _borrowAmount = canBorrow; } if (_borrowAmount > 10) { CErc20I(cWant).borrow(_borrowAmount); CErc20I(cWant).mint(balanceOfWant()); } return _borrowAmount; } function _leverUpStep(uint256 _borrowAmount) internal returns (uint256) { if (_borrowAmount == 0) { return 0; } uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); (, uint256 collateralFactorMantissa, ) = comptroller.markets(address(cWant)); uint256 canBorrow = (supplied * collateralFactorMantissa) / MANTISSA; canBorrow -= borrowed; if (canBorrow < _borrowAmount) { _borrowAmount = canBorrow; } if (_borrowAmount > 10) { CErc20I(cWant).borrow(_borrowAmount); CErc20I(cWant).mint(balanceOfWant()); } return _borrowAmount; } function _leverUpStep(uint256 _borrowAmount) internal returns (uint256) { if (_borrowAmount == 0) { return 0; } uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); (, uint256 collateralFactorMantissa, ) = comptroller.markets(address(cWant)); uint256 canBorrow = (supplied * collateralFactorMantissa) / MANTISSA; canBorrow -= borrowed; if (canBorrow < _borrowAmount) { _borrowAmount = canBorrow; } if (_borrowAmount > 10) { CErc20I(cWant).borrow(_borrowAmount); CErc20I(cWant).mint(balanceOfWant()); } return _borrowAmount; } function _leverUpStep(uint256 _borrowAmount) internal returns (uint256) { if (_borrowAmount == 0) { return 0; } uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); (, uint256 collateralFactorMantissa, ) = comptroller.markets(address(cWant)); uint256 canBorrow = (supplied * collateralFactorMantissa) / MANTISSA; canBorrow -= borrowed; if (canBorrow < _borrowAmount) { _borrowAmount = canBorrow; } if (_borrowAmount > 10) { CErc20I(cWant).borrow(_borrowAmount); CErc20I(cWant).mint(balanceOfWant()); } return _borrowAmount; } function _getMaxBorrowFromSupplied(uint256 wantSupplied, uint256 collateralFactor) internal pure returns (uint256) { return ((wantSupplied * collateralFactor) / (MANTISSA - collateralFactor)); } function _shouldLeverage(uint256 _ltv) internal view returns (bool) { return (targetLTV >= allowedLTVDrift && _ltv < targetLTV - allowedLTVDrift); } function _shouldDeleverage(uint256 _ltv) internal view returns (bool) { return (_ltv > targetLTV + allowedLTVDrift); } function _calculateLTVAfterWithdraw(uint256 _withdrawAmount) internal returns (uint256 ltv) { uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); supplied = supplied - _withdrawAmount; if (supplied == 0 || borrowed == 0) { return 0; } ltv = (MANTISSA * borrowed) / supplied; } function _calculateLTVAfterWithdraw(uint256 _withdrawAmount) internal returns (uint256 ltv) { uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); supplied = supplied - _withdrawAmount; if (supplied == 0 || borrowed == 0) { return 0; } ltv = (MANTISSA * borrowed) / supplied; } function _withdrawUnderlyingToVault(uint256 _withdrawAmount) internal { uint256 initialWithdrawAmount = _withdrawAmount; uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); uint256 realSupplied = supplied - borrowed; if (realSupplied == 0) { return; } if (_withdrawAmount > realSupplied) { _withdrawAmount = realSupplied; } uint256 tempColla = targetLTV + allowedLTVDrift; if (tempColla == 0) { } uint256 reservedAmount = (borrowed * MANTISSA) / tempColla; if (supplied >= reservedAmount) { uint256 redeemable = supplied - reservedAmount; uint256 balance = cWant.balanceOf(address(this)); if (balance > 1) { if (redeemable < _withdrawAmount) { _withdrawAmount = redeemable; } } } uint256 withdrawAmount = _withdrawAmount - 1; if (withdrawAmount < initialWithdrawAmount) { require( withdrawAmount >= (initialWithdrawAmount * (PERCENT_DIVISOR - withdrawSlippageTolerance)) / PERCENT_DIVISOR ); } CErc20I(cWant).redeemUnderlying(withdrawAmount); IERC20Upgradeable(want).safeTransfer(vault, withdrawAmount); } function _withdrawUnderlyingToVault(uint256 _withdrawAmount) internal { uint256 initialWithdrawAmount = _withdrawAmount; uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); uint256 realSupplied = supplied - borrowed; if (realSupplied == 0) { return; } if (_withdrawAmount > realSupplied) { _withdrawAmount = realSupplied; } uint256 tempColla = targetLTV + allowedLTVDrift; if (tempColla == 0) { } uint256 reservedAmount = (borrowed * MANTISSA) / tempColla; if (supplied >= reservedAmount) { uint256 redeemable = supplied - reservedAmount; uint256 balance = cWant.balanceOf(address(this)); if (balance > 1) { if (redeemable < _withdrawAmount) { _withdrawAmount = redeemable; } } } uint256 withdrawAmount = _withdrawAmount - 1; if (withdrawAmount < initialWithdrawAmount) { require( withdrawAmount >= (initialWithdrawAmount * (PERCENT_DIVISOR - withdrawSlippageTolerance)) / PERCENT_DIVISOR ); } CErc20I(cWant).redeemUnderlying(withdrawAmount); IERC20Upgradeable(want).safeTransfer(vault, withdrawAmount); } function _withdrawUnderlyingToVault(uint256 _withdrawAmount) internal { uint256 initialWithdrawAmount = _withdrawAmount; uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); uint256 realSupplied = supplied - borrowed; if (realSupplied == 0) { return; } if (_withdrawAmount > realSupplied) { _withdrawAmount = realSupplied; } uint256 tempColla = targetLTV + allowedLTVDrift; if (tempColla == 0) { } uint256 reservedAmount = (borrowed * MANTISSA) / tempColla; if (supplied >= reservedAmount) { uint256 redeemable = supplied - reservedAmount; uint256 balance = cWant.balanceOf(address(this)); if (balance > 1) { if (redeemable < _withdrawAmount) { _withdrawAmount = redeemable; } } } uint256 withdrawAmount = _withdrawAmount - 1; if (withdrawAmount < initialWithdrawAmount) { require( withdrawAmount >= (initialWithdrawAmount * (PERCENT_DIVISOR - withdrawSlippageTolerance)) / PERCENT_DIVISOR ); } CErc20I(cWant).redeemUnderlying(withdrawAmount); IERC20Upgradeable(want).safeTransfer(vault, withdrawAmount); } function _withdrawUnderlyingToVault(uint256 _withdrawAmount) internal { uint256 initialWithdrawAmount = _withdrawAmount; uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); uint256 realSupplied = supplied - borrowed; if (realSupplied == 0) { return; } if (_withdrawAmount > realSupplied) { _withdrawAmount = realSupplied; } uint256 tempColla = targetLTV + allowedLTVDrift; if (tempColla == 0) { } uint256 reservedAmount = (borrowed * MANTISSA) / tempColla; if (supplied >= reservedAmount) { uint256 redeemable = supplied - reservedAmount; uint256 balance = cWant.balanceOf(address(this)); if (balance > 1) { if (redeemable < _withdrawAmount) { _withdrawAmount = redeemable; } } } uint256 withdrawAmount = _withdrawAmount - 1; if (withdrawAmount < initialWithdrawAmount) { require( withdrawAmount >= (initialWithdrawAmount * (PERCENT_DIVISOR - withdrawSlippageTolerance)) / PERCENT_DIVISOR ); } CErc20I(cWant).redeemUnderlying(withdrawAmount); IERC20Upgradeable(want).safeTransfer(vault, withdrawAmount); } function _withdrawUnderlyingToVault(uint256 _withdrawAmount) internal { uint256 initialWithdrawAmount = _withdrawAmount; uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); uint256 realSupplied = supplied - borrowed; if (realSupplied == 0) { return; } if (_withdrawAmount > realSupplied) { _withdrawAmount = realSupplied; } uint256 tempColla = targetLTV + allowedLTVDrift; if (tempColla == 0) { } uint256 reservedAmount = (borrowed * MANTISSA) / tempColla; if (supplied >= reservedAmount) { uint256 redeemable = supplied - reservedAmount; uint256 balance = cWant.balanceOf(address(this)); if (balance > 1) { if (redeemable < _withdrawAmount) { _withdrawAmount = redeemable; } } } uint256 withdrawAmount = _withdrawAmount - 1; if (withdrawAmount < initialWithdrawAmount) { require( withdrawAmount >= (initialWithdrawAmount * (PERCENT_DIVISOR - withdrawSlippageTolerance)) / PERCENT_DIVISOR ); } CErc20I(cWant).redeemUnderlying(withdrawAmount); IERC20Upgradeable(want).safeTransfer(vault, withdrawAmount); } function _withdrawUnderlyingToVault(uint256 _withdrawAmount) internal { uint256 initialWithdrawAmount = _withdrawAmount; uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); uint256 realSupplied = supplied - borrowed; if (realSupplied == 0) { return; } if (_withdrawAmount > realSupplied) { _withdrawAmount = realSupplied; } uint256 tempColla = targetLTV + allowedLTVDrift; if (tempColla == 0) { } uint256 reservedAmount = (borrowed * MANTISSA) / tempColla; if (supplied >= reservedAmount) { uint256 redeemable = supplied - reservedAmount; uint256 balance = cWant.balanceOf(address(this)); if (balance > 1) { if (redeemable < _withdrawAmount) { _withdrawAmount = redeemable; } } } uint256 withdrawAmount = _withdrawAmount - 1; if (withdrawAmount < initialWithdrawAmount) { require( withdrawAmount >= (initialWithdrawAmount * (PERCENT_DIVISOR - withdrawSlippageTolerance)) / PERCENT_DIVISOR ); } CErc20I(cWant).redeemUnderlying(withdrawAmount); IERC20Upgradeable(want).safeTransfer(vault, withdrawAmount); } function _withdrawUnderlyingToVault(uint256 _withdrawAmount) internal { uint256 initialWithdrawAmount = _withdrawAmount; uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); uint256 realSupplied = supplied - borrowed; if (realSupplied == 0) { return; } if (_withdrawAmount > realSupplied) { _withdrawAmount = realSupplied; } uint256 tempColla = targetLTV + allowedLTVDrift; if (tempColla == 0) { } uint256 reservedAmount = (borrowed * MANTISSA) / tempColla; if (supplied >= reservedAmount) { uint256 redeemable = supplied - reservedAmount; uint256 balance = cWant.balanceOf(address(this)); if (balance > 1) { if (redeemable < _withdrawAmount) { _withdrawAmount = redeemable; } } } uint256 withdrawAmount = _withdrawAmount - 1; if (withdrawAmount < initialWithdrawAmount) { require( withdrawAmount >= (initialWithdrawAmount * (PERCENT_DIVISOR - withdrawSlippageTolerance)) / PERCENT_DIVISOR ); } CErc20I(cWant).redeemUnderlying(withdrawAmount); IERC20Upgradeable(want).safeTransfer(vault, withdrawAmount); } function _withdrawUnderlyingToVault(uint256 _withdrawAmount) internal { uint256 initialWithdrawAmount = _withdrawAmount; uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); uint256 realSupplied = supplied - borrowed; if (realSupplied == 0) { return; } if (_withdrawAmount > realSupplied) { _withdrawAmount = realSupplied; } uint256 tempColla = targetLTV + allowedLTVDrift; if (tempColla == 0) { } uint256 reservedAmount = (borrowed * MANTISSA) / tempColla; if (supplied >= reservedAmount) { uint256 redeemable = supplied - reservedAmount; uint256 balance = cWant.balanceOf(address(this)); if (balance > 1) { if (redeemable < _withdrawAmount) { _withdrawAmount = redeemable; } } } uint256 withdrawAmount = _withdrawAmount - 1; if (withdrawAmount < initialWithdrawAmount) { require( withdrawAmount >= (initialWithdrawAmount * (PERCENT_DIVISOR - withdrawSlippageTolerance)) / PERCENT_DIVISOR ); } CErc20I(cWant).redeemUnderlying(withdrawAmount); IERC20Upgradeable(want).safeTransfer(vault, withdrawAmount); } function _getBorrowDifference(uint256 _withdrawAmount) internal returns (uint256 difference) { uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); uint256 realSupply = supplied - borrowed; if (_withdrawAmount > realSupply) { _withdrawAmount = realSupply; } uint256 desiredSupply = realSupply - _withdrawAmount; if (desiredBorrow > 1e5) { desiredBorrow = desiredBorrow - 1e5; } difference = borrowed - desiredBorrow; } function _getBorrowDifference(uint256 _withdrawAmount) internal returns (uint256 difference) { uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); uint256 realSupply = supplied - borrowed; if (_withdrawAmount > realSupply) { _withdrawAmount = realSupply; } uint256 desiredSupply = realSupply - _withdrawAmount; if (desiredBorrow > 1e5) { desiredBorrow = desiredBorrow - 1e5; } difference = borrowed - desiredBorrow; } uint256 desiredBorrow = (desiredSupply * targetLTV) / (MANTISSA - targetLTV); function _getBorrowDifference(uint256 _withdrawAmount) internal returns (uint256 difference) { uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); uint256 realSupply = supplied - borrowed; if (_withdrawAmount > realSupply) { _withdrawAmount = realSupply; } uint256 desiredSupply = realSupply - _withdrawAmount; if (desiredBorrow > 1e5) { desiredBorrow = desiredBorrow - 1e5; } difference = borrowed - desiredBorrow; } function _deleverage(uint256 _withdrawAmount) internal { uint256 borrowDifference = _getBorrowDifference(_withdrawAmount); for (uint256 i = 0; i < borrowDepth && borrowDifference > minWantToLeverage; i++) { borrowDifference -= _leverDownStep(borrowDifference); } } function _deleverage(uint256 _withdrawAmount) internal { uint256 borrowDifference = _getBorrowDifference(_withdrawAmount); for (uint256 i = 0; i < borrowDepth && borrowDifference > minWantToLeverage; i++) { borrowDifference -= _leverDownStep(borrowDifference); } } function _leverDownStep(uint256 _releaseAmount) internal returns (uint256 deleveragedAmount) { uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); (, uint256 collateralFactorMantissa, ) = comptroller.markets(address(cWant)); uint256 minAllowedSupply = (borrowed * MANTISSA) / collateralFactorMantissa; uint256 maxAllowedDeleverageAmount = supplied - minAllowedSupply; deleveragedAmount = maxAllowedDeleverageAmount; if (deleveragedAmount > borrowed) { deleveragedAmount = borrowed; } if (deleveragedAmount > _releaseAmount) { deleveragedAmount = _releaseAmount; } uint256 exchangeRateStored = cWant.exchangeRateStored(); if (deleveragedAmount * MANTISSA >= exchangeRateStored && deleveragedAmount > 10) { cWant.redeemUnderlying(deleveragedAmount); cWant.repayBorrow(deleveragedAmount); } } function _leverDownStep(uint256 _releaseAmount) internal returns (uint256 deleveragedAmount) { uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); (, uint256 collateralFactorMantissa, ) = comptroller.markets(address(cWant)); uint256 minAllowedSupply = (borrowed * MANTISSA) / collateralFactorMantissa; uint256 maxAllowedDeleverageAmount = supplied - minAllowedSupply; deleveragedAmount = maxAllowedDeleverageAmount; if (deleveragedAmount > borrowed) { deleveragedAmount = borrowed; } if (deleveragedAmount > _releaseAmount) { deleveragedAmount = _releaseAmount; } uint256 exchangeRateStored = cWant.exchangeRateStored(); if (deleveragedAmount * MANTISSA >= exchangeRateStored && deleveragedAmount > 10) { cWant.redeemUnderlying(deleveragedAmount); cWant.repayBorrow(deleveragedAmount); } } function _leverDownStep(uint256 _releaseAmount) internal returns (uint256 deleveragedAmount) { uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); (, uint256 collateralFactorMantissa, ) = comptroller.markets(address(cWant)); uint256 minAllowedSupply = (borrowed * MANTISSA) / collateralFactorMantissa; uint256 maxAllowedDeleverageAmount = supplied - minAllowedSupply; deleveragedAmount = maxAllowedDeleverageAmount; if (deleveragedAmount > borrowed) { deleveragedAmount = borrowed; } if (deleveragedAmount > _releaseAmount) { deleveragedAmount = _releaseAmount; } uint256 exchangeRateStored = cWant.exchangeRateStored(); if (deleveragedAmount * MANTISSA >= exchangeRateStored && deleveragedAmount > 10) { cWant.redeemUnderlying(deleveragedAmount); cWant.repayBorrow(deleveragedAmount); } } function _leverDownStep(uint256 _releaseAmount) internal returns (uint256 deleveragedAmount) { uint256 supplied = cWant.balanceOfUnderlying(address(this)); uint256 borrowed = cWant.borrowBalanceStored(address(this)); (, uint256 collateralFactorMantissa, ) = comptroller.markets(address(cWant)); uint256 minAllowedSupply = (borrowed * MANTISSA) / collateralFactorMantissa; uint256 maxAllowedDeleverageAmount = supplied - minAllowedSupply; deleveragedAmount = maxAllowedDeleverageAmount; if (deleveragedAmount > borrowed) { deleveragedAmount = borrowed; } if (deleveragedAmount > _releaseAmount) { deleveragedAmount = _releaseAmount; } uint256 exchangeRateStored = cWant.exchangeRateStored(); if (deleveragedAmount * MANTISSA >= exchangeRateStored && deleveragedAmount > 10) { cWant.redeemUnderlying(deleveragedAmount); cWant.repayBorrow(deleveragedAmount); } } function _giveAllowances() internal override { IERC20Upgradeable(want).safeApprove(address(cWant), 0); IERC20Upgradeable(want).safeApprove(address(cWant), type(uint256).max); } function _removeAllowances() internal override { IERC20Upgradeable(want).safeApprove(address(cWant), 0); } modifier doUpdateBalance() { _; updateBalance(); } }
16,945,890
[ 1, 2503, 6252, 903, 443, 1724, 471, 884, 5682, 279, 1147, 603, 21327, 358, 943, 10153, 2824, 635, 284, 4610, 310, 19890, 2430, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 868, 7294, 4525, 16835, 1682, 5682, 353, 868, 7294, 2171, 4525, 90, 22, 288, 203, 565, 1450, 14060, 654, 39, 3462, 10784, 429, 364, 467, 654, 39, 3462, 10784, 429, 31, 203, 203, 565, 1758, 1071, 5381, 6448, 1345, 273, 1758, 12, 20, 14626, 9452, 39, 5082, 69, 39, 26, 39, 71, 3600, 507, 39, 29, 70, 40, 11180, 5292, 2643, 38, 5353, 37, 21, 69, 21, 29634, 41, 7140, 1611, 72, 1769, 203, 565, 1758, 1071, 5381, 1656, 281, 1345, 273, 1758, 12, 20, 20029, 2138, 15259, 71, 37, 25, 37, 2539, 3672, 26, 37, 69, 42, 1105, 41, 2733, 9401, 3657, 2643, 37, 24, 17156, 20, 74, 39, 24, 6840, 3103, 1769, 203, 565, 1758, 1071, 5381, 19890, 1345, 273, 1758, 12, 20, 92, 29, 74, 21, 42, 29, 3707, 39, 26, 4848, 69, 21, 5528, 28, 4313, 42, 20, 41, 20, 2954, 6260, 5193, 4763, 28, 7235, 71, 25, 39, 1441, 74, 20, 1769, 203, 565, 1758, 1071, 24557, 17631, 1060, 1345, 31, 203, 565, 1758, 1071, 2545, 31, 203, 565, 29538, 1310, 3462, 45, 1071, 276, 59, 970, 31, 203, 203, 565, 1758, 1071, 5381, 19462, 67, 1457, 1693, 654, 273, 1758, 12, 20, 92, 22, 8876, 7950, 41, 1966, 7950, 4033, 72, 6162, 9462, 69, 27263, 41, 23, 5948, 5895, 42, 8778, 37, 8204, 2947, 7677, 7140, 28, 38, 1769, 203, 565, 1758, 1071, 5381, 2438, 21343, 67, 2565, 27424, 1693, 916, 273, 1758, 12, 20, 92, 10689, 41, 28, 72, 24, 70, 24, 42, 8643, 2046, 22, 2 ]
./full_match/97/0x52EC3FD654EF2756601acF7Ae64b939b608441e8/sources/contracts/AULP.sol
买卖10%滑点,3%销毁,3%回流筑池(1.5%币、1.5%U),3%LP分红 DAPP实现,1%基金会(U到账)用于存储每个地址的余额数量存储授权数量,资产拥有者 owner => 授权调用方 spender => 授权数量
abstract contract AbsToken is IERC20, Ownable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private constant MAX = ~uint256(0); address private usdt; address DEAD = 0x000000000000000000000000000000000000dEaD; modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (string memory Name, string memory Symbol, uint8 Decimals, uint256 Supply, address FundAddress, address DividendAddress){ _name = Name; _symbol = Symbol; _decimals = Decimals; _swapRouter = ISwapRouter(0xB6BA90af76D139AB3170c7df0139636dB6120F7e); usdt = address(0x020a4191a19cc86537b7734A679B84241D227AF6); mainPair = ISwapFactory(_swapRouter.factory()).createPair(address(this), usdt); _allowances[address(this)][address(_swapRouter)] = MAX; IERC20(usdt).approve(address(_swapRouter), MAX); _tTotal = Supply * 10 ** _decimals; _balances[FundAddress] = _tTotal; emit Transfer(address(0), FundAddress, _tTotal); fundAddress = FundAddress; dividendAddress = DividendAddress; _feeWhiteList[FundAddress] = true; _feeWhiteList[DividendAddress] = true; _feeWhiteList[msg.sender] = true; _feeWhiteList[address(this)] = true; _feeWhiteList[address(_swapRouter)] = true; numTokensSellToFund = _tTotal / 10000; _tokenDistributor = new TokenDistributor(usdt); } function symbol() external view override returns (string memory) { return _symbol; } function name() external view override returns (string memory) { return _name; } function decimals() external view override returns (uint8) { return _decimals; } function totalSupply() external view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(msg.sender, 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(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); if (_allowances[sender][msg.sender] != MAX) { _allowances[sender][msg.sender] = _allowances[sender][msg.sender] - amount; } return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); if (_allowances[sender][msg.sender] != MAX) { _allowances[sender][msg.sender] = _allowances[sender][msg.sender] - amount; } return true; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "approve from the zero address"); require(spender != address(0), "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), "Transfer from the zero address"); require(to != address(0), "Transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_blackList[from], "Transfer from the blackList address"); bool takeFee = false; if (from == mainPair || to == mainPair) { if (0 == startTradeBlock) { require(_feeWhiteList[from] || _feeWhiteList[to], "Trade not start"); startTradeBlock = block.number; } if (!_feeWhiteList[from] && !_feeWhiteList[to]) { takeFee = true; if (block.number <= startTradeBlock + 2) { if (to != mainPair) { _blackList[to] = true; } } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToFund; if ( overMinTokenBalance && !inSwap && from != mainPair ) { swapTokenForFund(numTokensSellToFund); } } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "Transfer from the zero address"); require(to != address(0), "Transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_blackList[from], "Transfer from the blackList address"); bool takeFee = false; if (from == mainPair || to == mainPair) { if (0 == startTradeBlock) { require(_feeWhiteList[from] || _feeWhiteList[to], "Trade not start"); startTradeBlock = block.number; } if (!_feeWhiteList[from] && !_feeWhiteList[to]) { takeFee = true; if (block.number <= startTradeBlock + 2) { if (to != mainPair) { _blackList[to] = true; } } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToFund; if ( overMinTokenBalance && !inSwap && from != mainPair ) { swapTokenForFund(numTokensSellToFund); } } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "Transfer from the zero address"); require(to != address(0), "Transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_blackList[from], "Transfer from the blackList address"); bool takeFee = false; if (from == mainPair || to == mainPair) { if (0 == startTradeBlock) { require(_feeWhiteList[from] || _feeWhiteList[to], "Trade not start"); startTradeBlock = block.number; } if (!_feeWhiteList[from] && !_feeWhiteList[to]) { takeFee = true; if (block.number <= startTradeBlock + 2) { if (to != mainPair) { _blackList[to] = true; } } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToFund; if ( overMinTokenBalance && !inSwap && from != mainPair ) { swapTokenForFund(numTokensSellToFund); } } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "Transfer from the zero address"); require(to != address(0), "Transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_blackList[from], "Transfer from the blackList address"); bool takeFee = false; if (from == mainPair || to == mainPair) { if (0 == startTradeBlock) { require(_feeWhiteList[from] || _feeWhiteList[to], "Trade not start"); startTradeBlock = block.number; } if (!_feeWhiteList[from] && !_feeWhiteList[to]) { takeFee = true; if (block.number <= startTradeBlock + 2) { if (to != mainPair) { _blackList[to] = true; } } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToFund; if ( overMinTokenBalance && !inSwap && from != mainPair ) { swapTokenForFund(numTokensSellToFund); } } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "Transfer from the zero address"); require(to != address(0), "Transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_blackList[from], "Transfer from the blackList address"); bool takeFee = false; if (from == mainPair || to == mainPair) { if (0 == startTradeBlock) { require(_feeWhiteList[from] || _feeWhiteList[to], "Trade not start"); startTradeBlock = block.number; } if (!_feeWhiteList[from] && !_feeWhiteList[to]) { takeFee = true; if (block.number <= startTradeBlock + 2) { if (to != mainPair) { _blackList[to] = true; } } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToFund; if ( overMinTokenBalance && !inSwap && from != mainPair ) { swapTokenForFund(numTokensSellToFund); } } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "Transfer from the zero address"); require(to != address(0), "Transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_blackList[from], "Transfer from the blackList address"); bool takeFee = false; if (from == mainPair || to == mainPair) { if (0 == startTradeBlock) { require(_feeWhiteList[from] || _feeWhiteList[to], "Trade not start"); startTradeBlock = block.number; } if (!_feeWhiteList[from] && !_feeWhiteList[to]) { takeFee = true; if (block.number <= startTradeBlock + 2) { if (to != mainPair) { _blackList[to] = true; } } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToFund; if ( overMinTokenBalance && !inSwap && from != mainPair ) { swapTokenForFund(numTokensSellToFund); } } } _tokenTransfer(from, to, amount, takeFee); } uint256 contractTokenBalance = balanceOf(address(this)); function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "Transfer from the zero address"); require(to != address(0), "Transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_blackList[from], "Transfer from the blackList address"); bool takeFee = false; if (from == mainPair || to == mainPair) { if (0 == startTradeBlock) { require(_feeWhiteList[from] || _feeWhiteList[to], "Trade not start"); startTradeBlock = block.number; } if (!_feeWhiteList[from] && !_feeWhiteList[to]) { takeFee = true; if (block.number <= startTradeBlock + 2) { if (to != mainPair) { _blackList[to] = true; } } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToFund; if ( overMinTokenBalance && !inSwap && from != mainPair ) { swapTokenForFund(numTokensSellToFund); } } } _tokenTransfer(from, to, amount, takeFee); } function _tokenTransfer( address sender, address recipient, uint256 tAmount, bool takeFee ) private { _balances[sender] = _balances[sender] - tAmount; uint256 feeAmount; if (takeFee) { feeAmount = tAmount * (lpFee + fundFee + dividendFee) / 10000; _takeTransfer(sender, address(this), feeAmount); uint256 burnAmount = tAmount * (burnFee) / 10000; _takeTransfer(sender, DEAD, burnAmount); feeAmount = feeAmount + burnAmount; } _takeTransfer(sender, recipient, tAmount); } function _tokenTransfer( address sender, address recipient, uint256 tAmount, bool takeFee ) private { _balances[sender] = _balances[sender] - tAmount; uint256 feeAmount; if (takeFee) { feeAmount = tAmount * (lpFee + fundFee + dividendFee) / 10000; _takeTransfer(sender, address(this), feeAmount); uint256 burnAmount = tAmount * (burnFee) / 10000; _takeTransfer(sender, DEAD, burnAmount); feeAmount = feeAmount + burnAmount; } _takeTransfer(sender, recipient, tAmount); } tAmount = tAmount - feeAmount; function swapTokenForFund(uint256 tokenAmount) private lockTheSwap { uint256 lpAmount = tokenAmount * lpFee / (lpFee + dividendFee + fundFee) / 2; IERC20 USDT = IERC20(usdt); uint256 initialBalance = USDT.balanceOf(address(_tokenDistributor)); swapTokensForUsdt(tokenAmount - lpAmount); uint256 newBalance = USDT.balanceOf(address(_tokenDistributor)) - initialBalance; uint256 totalUsdtFee = lpFee / 2 + dividendFee + fundFee; USDT.transferFrom(address(_tokenDistributor), fundAddress, newBalance * fundFee / totalUsdtFee); USDT.transferFrom(address(_tokenDistributor), dividendAddress, newBalance * dividendFee / totalUsdtFee); uint256 lpUsdt = newBalance * lpFee / 2 / totalUsdtFee; USDT.transferFrom(address(_tokenDistributor), address(this), lpUsdt); addLiquidityUsdt(lpAmount, lpUsdt); } function addLiquidityUsdt(uint256 tokenAmount, uint256 usdtAmount) private { _swapRouter.addLiquidity( address(this), usdt, tokenAmount, usdtAmount, 0, 0, fundAddress, block.timestamp ); } function swapTokensForUsdt(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = usdt; _swapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenAmount, path, address(_tokenDistributor), block.timestamp ); } function _takeTransfer( address sender, address to, uint256 tAmount ) private { _balances[to] = _balances[to] + tAmount; emit Transfer(sender, to, tAmount); } receive() external payable {} function setFeeWhiteList(address addr, bool enable) external onlyOwner { _feeWhiteList[addr] = enable; } function isFeeWhiteList(address addr) external view returns (bool){ return _feeWhiteList[addr]; } function removeBlackList(address addr) external onlyOwner { _blackList[addr] = false; } function isBlackList(address addr) external view returns (bool){ return _blackList[addr]; } function claimBalance() public { payable(fundAddress).transfer(address(this).balance); } function claimToken(address token, uint256 amount) public { IERC20(token).transfer(fundAddress, amount); } }
3,283,043
[ 1, 165, 122, 113, 166, 240, 249, 2163, 9, 167, 124, 244, 168, 229, 122, 176, 125, 239, 23, 9, 170, 247, 227, 167, 112, 228, 176, 125, 239, 23, 9, 166, 254, 257, 167, 118, 228, 168, 260, 244, 167, 114, 259, 176, 125, 235, 21, 18, 25, 9, 166, 121, 228, 164, 227, 228, 21, 18, 25, 9, 57, 176, 125, 236, 176, 125, 239, 23, 9, 14461, 166, 235, 233, 168, 123, 100, 463, 7215, 166, 111, 257, 168, 241, 113, 176, 125, 239, 21, 9, 166, 258, 123, 170, 234, 244, 165, 125, 253, 176, 125, 235, 57, 166, 235, 113, 169, 117, 104, 176, 125, 236, 168, 247, 106, 165, 123, 241, 166, 260, 251, 166, 229, 106, 167, 112, 242, 165, 121, 108, 166, 255, 113, 166, 256, 227, 168, 253, 231, 165, 126, 252, 170, 100, 256, 167, 248, 113, 170, 234, 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, 17801, 6835, 15084, 1345, 353, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 203, 203, 203, 203, 203, 565, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 203, 203, 565, 1758, 3238, 584, 7510, 31, 203, 203, 203, 565, 1758, 2030, 1880, 273, 374, 92, 12648, 12648, 12648, 12648, 2787, 72, 41, 69, 40, 31, 203, 203, 565, 9606, 2176, 1986, 12521, 288, 203, 3639, 316, 12521, 273, 638, 31, 203, 3639, 389, 31, 203, 3639, 316, 12521, 273, 629, 31, 203, 565, 289, 203, 203, 565, 3885, 261, 1080, 3778, 1770, 16, 533, 3778, 8565, 16, 2254, 28, 3416, 11366, 16, 2254, 5034, 3425, 1283, 16, 1758, 478, 1074, 1887, 16, 1758, 21411, 26746, 1887, 15329, 203, 3639, 389, 529, 273, 1770, 31, 203, 3639, 389, 7175, 273, 8565, 31, 203, 3639, 389, 31734, 273, 3416, 11366, 31, 203, 203, 3639, 389, 22270, 8259, 273, 4437, 91, 438, 8259, 12, 20, 20029, 26, 12536, 9349, 1727, 6669, 40, 24347, 2090, 23, 31779, 71, 27, 2180, 1611, 5520, 4449, 26, 72, 38, 26, 22343, 42, 27, 73, 1769, 203, 3639, 584, 7510, 273, 1758, 12, 20, 92, 3103, 20, 69, 24, 30380, 69, 3657, 952, 5292, 25, 6418, 70, 4700, 5026, 37, 26, 7235, 38, 5193, 3247, 21, 40, 3787, 27, 6799, 26, 1769, 203, 2 ]
// contracts/token/modules/Lease.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.12; import "./interfaces/ILease.sol"; import "./Taxation.sol"; abstract contract Lease is ILease, Taxation { ////////////////////////////// /// State ////////////////////////////// /// @notice Mapping from token ID to purchase lock status /// @dev Used to prevent reentrancy attacks mapping(uint256 => bool) internal _locked; ////////////////////////////// /// Events ////////////////////////////// /// @notice Alert of lease takeover. /// @param tokenId ID of token. /// @param owner Address of new token owner. /// @param newValuation New owenr's self assessed valuation. event LogLeaseTakeover( uint256 indexed tokenId, address indexed owner, uint256 indexed newValuation ); ////////////////////////////// /// Public Methods ////////////////////////////// /// @dev See {ILease.takeoverLease} function takeoverLease( uint256 tokenId_, uint256 newValuation_, uint256 currentValuation_ ) public payable override _tokenMinted(tokenId_) { // Prevent re-entrancy attack require(!_locked[tokenId_], "Token is locked"); uint256 valuationPriorToTaxCollection = valuationOf(tokenId_); // Prevent front-run. require( valuationPriorToTaxCollection == currentValuation_, "Current valuation is incorrect" ); // New valuation must be greater than zero, even if current valuation is zero, to ensure that // funds are available for deposit. require(newValuation_ > 0, "New valuation cannot be zero"); // Buyer can self-assess the valuation higher the current valuation; this renders unnecessary a second gas payment // if Buyer wants to immediately self-assess the token at a higher valuation. require( newValuation_ >= valuationPriorToTaxCollection, "New valuation must be >= current valuation" ); bool senderIsBeneficiary = msg.sender == beneficiaryOf(tokenId_); // Current owner is a wallet address or the address of this contract // if the token is foreclosed or has never been purchased. address currentOwner = ownerOf(tokenId_); if (senderIsBeneficiary) { if (currentOwner == address(this)) { // If token is owned by contract, beneficiary does not need to pay anything. require(msg.value == 0, "Msg contains value"); } else { // Beneficiary only needs to pay the current valuation, // doesn't need to put down a deposit. require(msg.value == currentValuation_, "Msg contains surplus value"); } } else { // Value sent must be greater the amount being remitted to the current owner; // surplus is necessary for deposit. require( msg.value > valuationPriorToTaxCollection, "Message does not contain surplus value for deposit" ); } // Owner will be seller or this contract if foreclosed. // Prevent an accidental re-purchase. require(msg.sender != ownerOf(tokenId_), "Buyer is already owner"); // After all security checks have occured, lock the token. _locked[tokenId_] = true; // Collect tax. // Note: this may result in unexpected effects for the buyer. For example, // if taxation forecloses on the token, the buyer will be putting down a larger // deposit than they originally anticipated. collectTax(tokenId_); address ownerAfterCollection = ownerOf(tokenId_); bool purchasedFromContract = ownerAfterCollection == address(this); // Token is being purchased for the first time or out of foreclosure if (purchasedFromContract) { // Deposit takes entire msg value _setDeposit(tokenId_, msg.value); // If the token is being purchased for the first time or is being purchased // from foreclosure, last collection time is set to now so that the contract // does not incorrectly consider the taxable period to have begun prior to // foreclosure and overtax the owner. _setLastCollectionTime(tokenId_, block.timestamp); // Note: no remittance occurs. Beneficiary receives no tax on a token that is currently // valued at nothing. } else { _remit( ownerAfterCollection, // Owner receives their self-assessed valuation and the remainder of their deposit. currentValuation_ + depositOf(tokenId_), RemittanceTriggers.LeaseTakeover ); } // Update deposit if (senderIsBeneficiary) { // Beneficiary doesn't make deposits as no taxes are collected. _setDeposit(tokenId_, 0); } else if (purchasedFromContract) { // Deposit takes entire msg value _setDeposit(tokenId_, msg.value); } else { // Set the new owner's deposit _setDeposit(tokenId_, msg.value - currentValuation_); } // Set the new valuation _setValuation(tokenId_, newValuation_); _transfer(ownerAfterCollection, msg.sender, tokenId_); emit LogLeaseTakeover(tokenId_, msg.sender, newValuation_); // Unlock token _locked[tokenId_] = false; } /// @dev See {ILease.selfAssess} function selfAssess(uint256 tokenId_, uint256 newValuation_) public override _onlyApprovedOrOwner(tokenId_) _collectTax(tokenId_) { uint256 currentValuation = valuationOf(tokenId_); require(newValuation_ > 0, "New valuation cannot be zero"); require(newValuation_ != currentValuation, "New valuation cannot be same"); _setValuation(tokenId_, newValuation_); } }
@dev See {ILease.selfAssess}
function selfAssess(uint256 tokenId_, uint256 newValuation_) public override _onlyApprovedOrOwner(tokenId_) _collectTax(tokenId_) { uint256 currentValuation = valuationOf(tokenId_); require(newValuation_ > 0, "New valuation cannot be zero"); require(newValuation_ != currentValuation, "New valuation cannot be same"); _setValuation(tokenId_, newValuation_); }
15,837,069
[ 1, 9704, 288, 45, 17746, 18, 2890, 2610, 403, 97, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 365, 2610, 403, 12, 11890, 5034, 1147, 548, 67, 16, 2254, 5034, 394, 58, 700, 367, 67, 13, 203, 565, 1071, 203, 565, 3849, 203, 565, 389, 3700, 31639, 1162, 5541, 12, 2316, 548, 67, 13, 203, 565, 389, 14676, 7731, 12, 2316, 548, 67, 13, 203, 225, 288, 203, 565, 2254, 5034, 783, 58, 700, 367, 273, 21748, 367, 951, 12, 2316, 548, 67, 1769, 203, 565, 2583, 12, 2704, 58, 700, 367, 67, 405, 374, 16, 315, 1908, 21748, 367, 2780, 506, 3634, 8863, 203, 565, 2583, 12, 2704, 58, 700, 367, 67, 480, 783, 58, 700, 367, 16, 315, 1908, 21748, 367, 2780, 506, 1967, 8863, 203, 203, 565, 389, 542, 58, 700, 367, 12, 2316, 548, 67, 16, 394, 58, 700, 367, 67, 1769, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x00391d08b3e68e476a774ada379258264eb74485 //Contract name: DipTge //Balance: 0 Ether //Verification Date: 6/22/2018 //Transacion Count: 14 // CODE STARTS HERE pragma solidity 0.4.24; // File: contracts/tokensale/DipTgeInterface.sol contract DipTgeInterface { function tokenIsLocked(address _contributor) public constant returns (bool); } // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @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; } } // File: zeppelin-solidity/contracts/token/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: zeppelin-solidity/contracts/token/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // File: zeppelin-solidity/contracts/token/PausableToken.sol /** * @title Pausable token * * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // File: contracts/token/DipToken.sol /** * @title DIP Token * @dev The Decentralized Insurance Platform Token. * @author Christoph Mussenbrock * @copyright 2017 Etherisc GmbH */ pragma solidity 0.4.24; contract DipToken is PausableToken, MintableToken { string public constant name = "Decentralized Insurance Protocol"; string public constant symbol = "DIP"; uint256 public constant decimals = 18; uint256 public constant MAXIMUM_SUPPLY = 10**9 * 10**18; // 1 Billion 1'000'000'000 DipTgeInterface public DipTokensale; constructor() public { DipTokensale = DipTgeInterface(owner); } modifier shouldNotBeLockedIn(address _contributor) { // after LockIntTime2, we don't need to check anymore, and // the DipTokensale contract is no longer required. require(DipTokensale.tokenIsLocked(_contributor) == false); _; } /** * @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 returns (bool) { if (totalSupply.add(_amount) > MAXIMUM_SUPPLY) { return false; } return super.mint(_to, _amount); } /** * Owner can transfer back tokens which have been sent to this contract by mistake. * @param _token address of token contract of the respective tokens * @param _to where to send the tokens */ function salvageTokens(ERC20Basic _token, address _to) onlyOwner public { _token.transfer(_to, _token.balanceOf(this)); } function transferFrom(address _from, address _to, uint256 _value) shouldNotBeLockedIn(_from) public returns (bool) { return super.transferFrom(_from, _to, _value); } function transfer(address to, uint256 value) shouldNotBeLockedIn(msg.sender) public returns (bool) { return super.transfer(to, value); } } // File: zeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != 0x0); token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > endTime; } } // File: contracts/tokensale/DipWhitelistedCrowdsale.sol /** * @title DIP Token Generating Event * @dev The Decentralized Insurance Platform Token. * @author Christoph Mussenbrock * @copyright 2017 Etherisc GmbH */ pragma solidity 0.4.24; contract DipWhitelistedCrowdsale is Ownable { using SafeMath for uint256; struct ContributorData { uint256 allowance; uint256 contributionAmount; uint256 tokensIssued; bool airdrop; uint256 bonus; // 0 == 0%, 4 == 25%, 10 == 10% uint256 lockupPeriod; // 0, 1 or 2 (years) } mapping (address => ContributorData) public contributorList; event Whitelisted(address indexed _contributor, uint256 _allowance, bool _airdrop, uint256 _bonus, uint256 _lockupPeriod); /** * Push contributor data to the contract before the crowdsale */ function editContributors ( address[] _contributorAddresses, uint256[] _contributorAllowance, bool[] _airdrop, uint256[] _bonus, uint256[] _lockupPeriod ) onlyOwner public { // Check if input data is consistent require( _contributorAddresses.length == _contributorAllowance.length && _contributorAddresses.length == _airdrop.length && _contributorAddresses.length == _bonus.length && _contributorAddresses.length == _lockupPeriod.length ); for (uint256 cnt = 0; cnt < _contributorAddresses.length; cnt = cnt.add(1)) { require(_bonus[cnt] == 0 || _bonus[cnt] == 4 || _bonus[cnt] == 10); require(_lockupPeriod[cnt] <= 2); address contributor = _contributorAddresses[cnt]; contributorList[contributor].allowance = _contributorAllowance[cnt]; contributorList[contributor].airdrop = _airdrop[cnt]; contributorList[contributor].bonus = _bonus[cnt]; contributorList[contributor].lockupPeriod = _lockupPeriod[cnt]; emit Whitelisted( _contributorAddresses[cnt], _contributorAllowance[cnt], _airdrop[cnt], _bonus[cnt], _lockupPeriod[cnt] ); } } } // File: zeppelin-solidity/contracts/crowdsale/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: contracts/tokensale/DipTge.sol /** * @title DIP Token Generating Event * @notice The Decentralized Insurance Platform Token. * @author Christoph Mussenbrock * * @copyright 2017 Etherisc GmbH */ pragma solidity 0.4.24; contract DipTge is DipWhitelistedCrowdsale, FinalizableCrowdsale { using SafeMath for uint256; enum state { pendingStart, priorityPass, crowdsale, crowdsaleEnded } uint256 public startOpenPpTime; uint256 public hardCap; uint256 public lockInTime1; // token lock-in period for team, ECA, US accredited investors uint256 public lockInTime2; // token lock-in period for founders state public crowdsaleState = state.pendingStart; event DipTgeStarted(uint256 _time); event CrowdsaleStarted(uint256 _time); event HardCapReached(uint256 _time); event DipTgeEnded(uint256 _time); event TokenAllocated(address _beneficiary, uint256 _amount); constructor( uint256 _startTime, uint256 _startOpenPpTime, uint256 _endTime, uint256 _lockInTime1, uint256 _lockInTime2, uint256 _hardCap, uint256 _rate, address _wallet ) Crowdsale(_startTime, _endTime, _rate, _wallet) public { // Check arguments require(_startTime >= block.timestamp); require(_startOpenPpTime >= _startTime); require(_endTime >= _startOpenPpTime); require(_lockInTime1 >= _endTime); require(_lockInTime2 > _lockInTime1); require(_hardCap > 0); require(_rate > 0); require(_wallet != 0x0); // Set contract fields startOpenPpTime = _startOpenPpTime; hardCap = _hardCap; lockInTime1 = _lockInTime1; lockInTime2 = _lockInTime2; DipToken(token).pause(); } function setRate(uint256 _rate) onlyOwner public { require(crowdsaleState == state.pendingStart); rate = _rate; } function unpauseToken() onlyOwner external { DipToken(token).unpause(); } /** * Calculate the maximum remaining contribution allowed for an address * @param _contributor the address of the contributor * @return maxContribution maximum allowed amount in wei */ function calculateMaxContribution(address _contributor) public constant returns (uint256 _maxContribution) { uint256 maxContrib = 0; if (crowdsaleState == state.priorityPass) { maxContrib = contributorList[_contributor].allowance.sub(contributorList[_contributor].contributionAmount); if (maxContrib > hardCap.sub(weiRaised)) { maxContrib = hardCap.sub(weiRaised); } } else if (crowdsaleState == state.crowdsale) { if (contributorList[_contributor].allowance > 0) { maxContrib = hardCap.sub(weiRaised); } } return maxContrib; } /** * Calculate amount of tokens * This is used twice: * 1) For calculation of token amount plus optional bonus from wei amount contributed * In this case, rate is the defined exchange rate of ETH against DIP. * 2) For calculation of token amount plus optional bonus from DIP token amount * In the second case, rate == 1 because we have already calculated DIP tokens from RSC amount * by applying a factor of 10/32. * @param _contributor the address of the contributor * @param _amount contribution amount * @return _tokens amount of tokens */ function calculateTokens(address _contributor, uint256 _amount, uint256 _rate) public constant returns (uint256 _tokens) { uint256 bonus = contributorList[_contributor].bonus; assert(bonus == 0 || bonus == 4 || bonus == 10); if (bonus > 0) { _tokens = _amount.add(_amount.div(bonus)).mul(_rate); } else { _tokens = _amount.mul(_rate); } } /** * Set the current state of the crowdsale. */ function setCrowdsaleState() public { if (weiRaised >= hardCap && crowdsaleState != state.crowdsaleEnded) { crowdsaleState = state.crowdsaleEnded; emit HardCapReached(block.timestamp); emit DipTgeEnded(block.timestamp); } else if ( block.timestamp >= startTime && block.timestamp < startOpenPpTime && crowdsaleState != state.priorityPass ) { crowdsaleState = state.priorityPass; emit DipTgeStarted(block.timestamp); } else if ( block.timestamp >= startOpenPpTime && block.timestamp <= endTime && crowdsaleState != state.crowdsale ) { crowdsaleState = state.crowdsale; emit CrowdsaleStarted(block.timestamp); } else if ( crowdsaleState != state.crowdsaleEnded && block.timestamp > endTime ) { crowdsaleState = state.crowdsaleEnded; emit DipTgeEnded(block.timestamp); } } /** * The token buying function. * @param _beneficiary receiver of tokens. */ function buyTokens(address _beneficiary) public payable { require(_beneficiary != 0x0); require(validPurchase()); require(contributorList[_beneficiary].airdrop == false); setCrowdsaleState(); uint256 weiAmount = msg.value; uint256 maxContrib = calculateMaxContribution(_beneficiary); uint256 refund; if (weiAmount > maxContrib) { refund = weiAmount.sub(maxContrib); weiAmount = maxContrib; } // stop here if transaction does not yield tokens require(weiAmount > 0); // calculate token amount to be created uint256 tokens = calculateTokens(_beneficiary, weiAmount, rate); assert(tokens > 0); // update state weiRaised = weiRaised.add(weiAmount); require(token.mint(_beneficiary, tokens)); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); contributorList[_beneficiary].contributionAmount = contributorList[_beneficiary].contributionAmount.add(weiAmount); contributorList[_beneficiary].tokensIssued = contributorList[_beneficiary].tokensIssued.add(tokens); wallet.transfer(weiAmount); if (refund != 0) _beneficiary.transfer(refund); } /** * Check if token is locked. */ function tokenIsLocked(address _contributor) public constant returns (bool) { if (block.timestamp < lockInTime1 && contributorList[_contributor].lockupPeriod == 1) { return true; } else if (block.timestamp < lockInTime2 && contributorList[_contributor].lockupPeriod == 2) { return true; } return false; } /** * Distribute tokens to selected team members & founders. * Unit of Allowance is ETH and is converted in number of tokens by multiplying with Rate. * This can be called by any whitelisted beneficiary. */ function airdrop() public { airdropFor(msg.sender); } /** * Alternatively to airdrop(); tokens can be directly sent to beneficiaries by this function * This can be called only once. */ function airdropFor(address _beneficiary) public { require(_beneficiary != 0x0); require(contributorList[_beneficiary].airdrop == true); require(contributorList[_beneficiary].tokensIssued == 0); require(contributorList[_beneficiary].allowance > 0); setCrowdsaleState(); require(crowdsaleState == state.crowdsaleEnded); uint256 amount = contributorList[_beneficiary].allowance.mul(rate); require(token.mint(_beneficiary, amount)); emit TokenAllocated(_beneficiary, amount); contributorList[_beneficiary].tokensIssued = contributorList[_beneficiary].tokensIssued.add(amount); } /** * Creates an new ERC20 Token contract for the DIP Token. * Overrides Crowdsale function * @return the created token */ function createTokenContract() internal returns (MintableToken) { return new DipToken(); } /** * Finalize sale and perform cleanup actions. */ function finalization() internal { uint256 maxSupply = DipToken(token).MAXIMUM_SUPPLY(); token.mint(wallet, maxSupply.sub(token.totalSupply())); // Alternativly, hardcode remaining token distribution. token.finishMinting(); token.transferOwnership(owner); } /** * Owner can transfer back tokens which have been sent to this contract by mistake. * @param _token address of token contract of the respective tokens * @param _to where to send the tokens */ function salvageTokens(ERC20Basic _token, address _to) onlyOwner external { _token.transfer(_to, _token.balanceOf(this)); } }
* @title FinalizableCrowdsale @dev Extension of Crowdsale where an owner can do extra work after finishing./
contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } function finalization() internal { } }
994,319
[ 1, 7951, 6934, 39, 492, 2377, 5349, 225, 10021, 434, 385, 492, 2377, 5349, 1625, 392, 3410, 848, 741, 2870, 1440, 1839, 4076, 310, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 16269, 6934, 39, 492, 2377, 5349, 353, 385, 492, 2377, 5349, 16, 14223, 6914, 288, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 225, 1426, 1071, 29200, 1235, 273, 629, 31, 203, 203, 225, 871, 16269, 1235, 5621, 203, 203, 203, 225, 445, 12409, 1435, 1338, 5541, 1071, 288, 203, 565, 2583, 12, 5, 291, 7951, 1235, 1769, 203, 565, 2583, 12, 5332, 28362, 10663, 203, 203, 565, 727, 1588, 5621, 203, 565, 16269, 1235, 5621, 203, 203, 565, 29200, 1235, 273, 638, 31, 203, 225, 289, 203, 203, 225, 445, 727, 1588, 1435, 2713, 288, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.0; // Sources flattened with hardhat v2.8.3 https://hardhat.org // File contracts/Math/Math.sol /** * @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(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // File contracts/Curve/IveFXS.sol pragma abicoder v2; interface IveFXS { struct LockedBalance { int128 amount; uint256 end; } function commit_transfer_ownership(address addr) external; function apply_transfer_ownership() external; function commit_smart_wallet_checker(address addr) external; function apply_smart_wallet_checker() external; function toggleEmergencyUnlock() external; function recoverERC20(address token_addr, uint256 amount) external; function get_last_user_slope(address addr) external view returns (int128); function user_point_history__ts(address _addr, uint256 _idx) external view returns (uint256); function locked__end(address _addr) external view returns (uint256); function checkpoint() external; function deposit_for(address _addr, uint256 _value) external; function create_lock(uint256 _value, uint256 _unlock_time) external; function increase_amount(uint256 _value) external; function increase_unlock_time(uint256 _unlock_time) external; function withdraw() external; function balanceOf(address addr) external view returns (uint256); function balanceOf(address addr, uint256 _t) external view returns (uint256); function balanceOfAt(address addr, uint256 _block) external view returns (uint256); function totalSupply() external view returns (uint256); function totalSupply(uint256 t) external view returns (uint256); function totalSupplyAt(uint256 _block) external view returns (uint256); function totalFXSSupply() external view returns (uint256); function totalFXSSupplyAt(uint256 _block) external view returns (uint256); function changeController(address _newController) external; function token() external view returns (address); function supply() external view returns (uint256); function locked(address addr) external view returns (LockedBalance memory); function epoch() external view returns (uint256); function point_history(uint256 arg0) external view returns (int128 bias, int128 slope, uint256 ts, uint256 blk, uint256 fxs_amt); function user_point_history(address arg0, uint256 arg1) external view returns (int128 bias, int128 slope, uint256 ts, uint256 blk, uint256 fxs_amt); function user_point_epoch(address arg0) external view returns (uint256); function slope_changes(uint256 arg0) external view returns (int128); function controller() external view returns (address); function transfersEnabled() external view returns (bool); function emergencyUnlockActive() external view returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); function version() external view returns (string memory); function decimals() external view returns (uint256); function future_smart_wallet_checker() external view returns (address); function smart_wallet_checker() external view returns (address); function admin() external view returns (address); function future_admin() external view returns (address); } // File contracts/Curve/IFraxGaugeController.sol // https://github.com/swervefi/swerve/edit/master/packages/swerve-contracts/interfaces/IGaugeController.sol interface IFraxGaugeController { struct Point { uint256 bias; uint256 slope; } struct VotedSlope { uint256 slope; uint256 power; uint256 end; } // Public variables function admin() external view returns (address); function future_admin() external view returns (address); function token() external view returns (address); function voting_escrow() external view returns (address); function n_gauge_types() external view returns (int128); function n_gauges() external view returns (int128); function gauge_type_names(int128) external view returns (string memory); function gauges(uint256) external view returns (address); function vote_user_slopes(address, address) external view returns (VotedSlope memory); function vote_user_power(address) external view returns (uint256); function last_user_vote(address, address) external view returns (uint256); function points_weight(address, uint256) external view returns (Point memory); function time_weight(address) external view returns (uint256); function points_sum(int128, uint256) external view returns (Point memory); function time_sum(uint256) external view returns (uint256); function points_total(uint256) external view returns (uint256); function time_total() external view returns (uint256); function points_type_weight(int128, uint256) external view returns (uint256); function time_type_weight(uint256) external view returns (uint256); // Getter functions function gauge_types(address) external view returns (int128); function gauge_relative_weight(address) external view returns (uint256); function gauge_relative_weight(address, uint256) external view returns (uint256); function get_gauge_weight(address) external view returns (uint256); function get_type_weight(int128) external view returns (uint256); function get_total_weight() external view returns (uint256); function get_weights_sum_per_type(int128) external view returns (uint256); // External functions function commit_transfer_ownership(address) external; function apply_transfer_ownership() external; function add_gauge( address, int128, uint256 ) external; function checkpoint() external; function checkpoint_gauge(address) external; function global_emission_rate() external view returns (uint256); function gauge_relative_weight_write(address) external returns (uint256); function gauge_relative_weight_write(address, uint256) external returns (uint256); function add_type(string memory, uint256) external; function change_type_weight(int128, uint256) external; function change_gauge_weight(address, uint256) external; function change_global_emission_rate(uint256) external; function vote_for_gauge_weights(address, uint256) external; } // File contracts/Curve/IFraxGaugeFXSRewardsDistributor.sol interface IFraxGaugeFXSRewardsDistributor { function acceptOwnership() external; function curator_address() external view returns(address); function currentReward(address gauge_address) external view returns(uint256 reward_amount); function distributeReward(address gauge_address) external returns(uint256 weeks_elapsed, uint256 reward_tally); function distributionsOn() external view returns(bool); function gauge_whitelist(address) external view returns(bool); function is_middleman(address) external view returns(bool); function last_time_gauge_paid(address) external view returns(uint256); function nominateNewOwner(address _owner) external; function nominatedOwner() external view returns(address); function owner() external view returns(address); function recoverERC20(address tokenAddress, uint256 tokenAmount) external; function setCurator(address _new_curator_address) external; function setGaugeController(address _gauge_controller_address) external; function setGaugeState(address _gauge_address, bool _is_middleman, bool _is_active) external; function setTimelock(address _new_timelock) external; function timelock_address() external view returns(address); function toggleDistributions() external; } // File contracts/Common/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return 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; } } // File contracts/Math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File 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 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/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/ERC20.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ 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 returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address.approve(address spender, uint256 amount) */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ 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 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); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of `from`'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of `from`'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File contracts/Uniswap/TransferHelper.sol // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // 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/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 () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File contracts/Staking/Owned.sol // https://docs.synthetix.io/contracts/Owned contract Owned { address public owner; address public nominatedOwner; constructor (address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_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); } // File contracts/Staking/FraxUnifiedFarmTemplate.sol pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ====================== FraxUnifiedFarmTemplate ===================== // ==================================================================== // Migratable Farming contract that accounts for veFXS // Overrideable for UniV3, ERC20s, etc // New for V2 // - Two reward tokens possible // - Can add to existing locked stakes // - Contract is aware of proxied veFXS // - veFXS multiplier formula changed // Apes together strong // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Dennis: github.com/denett // Sam Sun: https://github.com/samczsun // Originally inspired by Synthetix.io, but heavily modified by the Frax team // (Locked, veFXS, and UniV3 portions are new) // https://raw.githubusercontent.com/Synthetixio/synthetix/develop/contracts/StakingRewards.sol contract FraxUnifiedFarmTemplate is Owned, ReentrancyGuard { using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Instances IveFXS private veFXS = IveFXS(0xc8418aF6358FFddA74e09Ca9CC3Fe03Ca6aDC5b0); // Frax related address internal frax_address = 0x853d955aCEf822Db058eb8505911ED77F175b99e; bool internal frax_is_token0; uint256 private fraxPerLPStored; // Constant for various precisions uint256 internal constant MULTIPLIER_PRECISION = 1e18; // Time tracking uint256 public periodFinish; uint256 public lastUpdateTime; // Lock time and multiplier settings uint256 public lock_max_multiplier = uint256(3e18); // E18. 1x = e18 uint256 public lock_time_for_max_multiplier = 3 * 365 * 86400; // 3 years uint256 public lock_time_min = 86400; // 1 * 86400 (1 day) // veFXS related uint256 public vefxs_boost_scale_factor = uint256(4e18); // E18. 4x = 4e18; 100 / scale_factor = % vefxs supply needed for max boost uint256 public vefxs_max_multiplier = uint256(2e18); // E18. 1x = 1e18 uint256 public vefxs_per_frax_for_max_boost = uint256(2e18); // E18. 2e18 means 2 veFXS must be held by the staker per 1 FRAX mapping(address => uint256) internal _vefxsMultiplierStored; mapping(address => bool) internal valid_vefxs_proxies; mapping(address => mapping(address => bool)) internal proxy_allowed_stakers; // Reward addresses, gauge addresses, reward rates, and reward managers mapping(address => address) public rewardManagers; // token addr -> manager addr address[] internal rewardTokens; address[] internal gaugeControllers; address[] internal rewardDistributors; uint256[] internal rewardRatesManual; mapping(address => uint256) public rewardTokenAddrToIdx; // token addr -> token index // Reward period uint256 public rewardsDuration = 604800; // 7 * 86400 (7 days) // Reward tracking uint256[] private rewardsPerTokenStored; mapping(address => mapping(uint256 => uint256)) private userRewardsPerTokenPaid; // staker addr -> token id -> paid amount mapping(address => mapping(uint256 => uint256)) private rewards; // staker addr -> token id -> reward amount mapping(address => uint256) internal lastRewardClaimTime; // staker addr -> timestamp // Gauge tracking uint256[] private last_gauge_relative_weights; uint256[] private last_gauge_time_totals; // Balance tracking uint256 internal _total_liquidity_locked; uint256 internal _total_combined_weight; mapping(address => uint256) internal _locked_liquidity; mapping(address => uint256) internal _combined_weights; // List of valid migrators (set by governance) mapping(address => bool) internal valid_migrators; // Stakers set which migrator(s) they want to use mapping(address => mapping(address => bool)) internal staker_allowed_migrators; mapping(address => address) public staker_designated_proxies; // Keep public so users can see on the frontend if they have a proxy // Greylists mapping(address => bool) internal greylist; // Admin booleans for emergencies, migrations, and overrides bool public stakesUnlocked; // Release locked stakes in case of emergency bool internal migrationsOn; // Used for migrations. Prevents new stakes, but allows LP and reward withdrawals bool internal withdrawalsPaused; // For emergencies bool internal rewardsCollectionPaused; // For emergencies bool internal stakingPaused; // For emergencies /* ========== STRUCTS ========== */ // In children... /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == owner || msg.sender == 0x8412ebf45bAC1B340BbE8F318b928C466c4E39CA, "Not owner or timelock"); _; } modifier onlyTknMgrs(address reward_token_address) { require(msg.sender == owner || isTokenManagerFor(msg.sender, reward_token_address), "Not owner or tkn mgr"); _; } modifier isMigrating() { require(migrationsOn == true, "Not in migration"); _; } modifier updateRewardAndBalance(address account, bool sync_too) { _updateRewardAndBalance(account, sync_too); _; } /* ========== CONSTRUCTOR ========== */ constructor ( address _owner, address[] memory _rewardTokens, address[] memory _rewardManagers, uint256[] memory _rewardRatesManual, address[] memory _gaugeControllers, address[] memory _rewardDistributors ) Owned(_owner) { // Address arrays rewardTokens = _rewardTokens; gaugeControllers = _gaugeControllers; rewardDistributors = _rewardDistributors; rewardRatesManual = _rewardRatesManual; for (uint256 i = 0; i < _rewardTokens.length; i++){ // For fast token address -> token ID lookups later rewardTokenAddrToIdx[_rewardTokens[i]] = i; // Initialize the stored rewards rewardsPerTokenStored.push(0); // Initialize the reward managers rewardManagers[_rewardTokens[i]] = _rewardManagers[i]; // Push in empty relative weights to initialize the array last_gauge_relative_weights.push(0); // Push in empty time totals to initialize the array last_gauge_time_totals.push(0); } // Other booleans stakesUnlocked = false; // Initialization lastUpdateTime = block.timestamp; periodFinish = block.timestamp + rewardsDuration; } /* ============= VIEWS ============= */ // ------ REWARD RELATED ------ // See if the caller_addr is a manager for the reward token function isTokenManagerFor(address caller_addr, address reward_token_addr) public view returns (bool){ if (caller_addr == owner) return true; // Contract owner else if (rewardManagers[reward_token_addr] == caller_addr) return true; // Reward manager return false; } // All the reward tokens function getAllRewardTokens() external view returns (address[] memory) { return rewardTokens; } // Last time the reward was applicable function lastTimeRewardApplicable() internal view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardRates(uint256 token_idx) public view returns (uint256 rwd_rate) { address gauge_controller_address = gaugeControllers[token_idx]; if (gauge_controller_address != address(0)) { rwd_rate = (IFraxGaugeController(gauge_controller_address).global_emission_rate() * last_gauge_relative_weights[token_idx]) / 1e18; } else { rwd_rate = rewardRatesManual[token_idx]; } } // Amount of reward tokens per LP token / liquidity unit function rewardsPerToken() public view returns (uint256[] memory newRewardsPerTokenStored) { if (_total_liquidity_locked == 0 || _total_combined_weight == 0) { return rewardsPerTokenStored; } else { newRewardsPerTokenStored = new uint256[](rewardTokens.length); for (uint256 i = 0; i < rewardsPerTokenStored.length; i++){ newRewardsPerTokenStored[i] = rewardsPerTokenStored[i] + ( ((lastTimeRewardApplicable() - lastUpdateTime) * rewardRates(i) * 1e18) / _total_combined_weight ); } return newRewardsPerTokenStored; } } // Amount of reward tokens an account has earned / accrued // Note: In the edge-case of one of the account's stake expiring since the last claim, this will // return a slightly inflated number function earned(address account) public view returns (uint256[] memory new_earned) { uint256[] memory reward_arr = rewardsPerToken(); new_earned = new uint256[](rewardTokens.length); if (_combined_weights[account] > 0){ for (uint256 i = 0; i < rewardTokens.length; i++){ new_earned[i] = ((_combined_weights[account] * (reward_arr[i] - userRewardsPerTokenPaid[account][i])) / 1e18) + rewards[account][i]; } } // if (_combined_weights[account] == 0){ // for (uint256 i = 0; i < rewardTokens.length; i++){ // new_earned[i] = 0; // } // } // else { // for (uint256 i = 0; i < rewardTokens.length; i++){ // new_earned[i] = ((_combined_weights[account] * (reward_arr[i] - userRewardsPerTokenPaid[account][i])) / 1e18) // + rewards[account][i]; // } // } } // Total reward tokens emitted in the given period function getRewardForDuration() external view returns (uint256[] memory rewards_per_duration_arr) { rewards_per_duration_arr = new uint256[](rewardRatesManual.length); for (uint256 i = 0; i < rewardRatesManual.length; i++){ rewards_per_duration_arr[i] = rewardRates(i) * rewardsDuration; } } // ------ LIQUIDITY AND WEIGHTS ------ // User locked liquidity / LP tokens function totalLiquidityLocked() external view returns (uint256) { return _total_liquidity_locked; } // Total locked liquidity / LP tokens function lockedLiquidityOf(address account) external view returns (uint256) { return _locked_liquidity[account]; } // Total combined weight function totalCombinedWeight() external view returns (uint256) { return _total_combined_weight; } // Total 'balance' used for calculating the percent of the pool the account owns // Takes into account the locked stake time multiplier and veFXS multiplier function combinedWeightOf(address account) external view returns (uint256) { return _combined_weights[account]; } // Calculated the combined weight for an account function calcCurCombinedWeight(address account) public virtual view returns ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) { revert("Need cCCW logic"); } // ------ LOCK RELATED ------ // Multiplier amount, given the length of the lock function lockMultiplier(uint256 secs) public view returns (uint256) { return Math.min( lock_max_multiplier, uint256(MULTIPLIER_PRECISION) + ( (secs * (lock_max_multiplier - MULTIPLIER_PRECISION)) / lock_time_for_max_multiplier ) ) ; } // ------ FRAX RELATED ------ function userStakedFrax(address account) public view returns (uint256) { return (fraxPerLPStored * _locked_liquidity[account]) / MULTIPLIER_PRECISION; } // Meant to be overridden function fraxPerLPToken() public virtual view returns (uint256) { revert("Need fPLPT logic"); } // ------ veFXS RELATED ------ function minVeFXSForMaxBoost(address account) public view returns (uint256) { return (userStakedFrax(account) * vefxs_per_frax_for_max_boost) / MULTIPLIER_PRECISION; } function veFXSMultiplier(address account) public view returns (uint256 vefxs_multiplier) { // Use either the user's or their proxy's veFXS balance uint256 vefxs_bal_to_use = 0; { uint256 vefxs_user_bal = veFXS.balanceOf(account); uint256 vefxs_proxy_bal = veFXS.balanceOf(staker_designated_proxies[account]); vefxs_bal_to_use = (vefxs_user_bal > vefxs_proxy_bal ? vefxs_user_bal : vefxs_proxy_bal); } // First option based on fraction of total veFXS supply, with an added scale factor uint256 mult_optn_1 = (vefxs_bal_to_use * vefxs_max_multiplier * vefxs_boost_scale_factor) / (veFXS.totalSupply() * MULTIPLIER_PRECISION); // Second based on old method, where the amount of FRAX staked comes into play uint256 mult_optn_2; { uint256 veFXS_needed_for_max_boost = minVeFXSForMaxBoost(account); if (veFXS_needed_for_max_boost > 0){ uint256 user_vefxs_fraction = (vefxs_bal_to_use * MULTIPLIER_PRECISION) / veFXS_needed_for_max_boost; mult_optn_2 = (user_vefxs_fraction * vefxs_max_multiplier) / MULTIPLIER_PRECISION; } else mult_optn_2 = 0; // This will happen with the first stake, when user_staked_frax is 0 } // Select the higher of the three vefxs_multiplier = (mult_optn_1 > mult_optn_2 ? mult_optn_1 : mult_optn_2); // Cap the boost to the vefxs_max_multiplier if (vefxs_multiplier > vefxs_max_multiplier) vefxs_multiplier = vefxs_max_multiplier; } /* =============== MUTATIVE FUNCTIONS =============== */ // ------ MIGRATIONS ------ // Staker can allow a migrator function stakerToggleMigrator(address migrator_address) external { require(valid_migrators[migrator_address], "Invalid migrator address"); staker_allowed_migrators[msg.sender][migrator_address] = !staker_allowed_migrators[msg.sender][migrator_address]; } // Staker can allow a veFXS proxy (the proxy will have to toggle them first) function stakerSetVeFXSProxy(address proxy_address) external { require(valid_vefxs_proxies[proxy_address], "Invalid proxy"); require(proxy_allowed_stakers[proxy_address][msg.sender], "Proxy has not allowed you"); staker_designated_proxies[msg.sender] = proxy_address; } // Proxy can allow a staker to use their veFXS balance (the staker will have to reciprocally toggle them too) // Must come before stakerSetVeFXSProxy function proxyToggleStaker(address staker_address) external { require(valid_vefxs_proxies[msg.sender], "Invalid proxy"); proxy_allowed_stakers[msg.sender][staker_address] = !proxy_allowed_stakers[msg.sender][staker_address]; // Disable the staker's set proxy if it was the toggler and is currently on if (staker_designated_proxies[staker_address] == msg.sender){ staker_designated_proxies[staker_address] = address(0); } } // ------ STAKING ------ // In children... // ------ WITHDRAWING ------ // In children... // ------ REWARDS SYNCING ------ function _updateRewardAndBalance(address account, bool sync_too) internal { // Need to retro-adjust some things if the period hasn't been renewed, then start a new one if (sync_too){ sync(); } if (account != address(0)) { // To keep the math correct, the user's combined weight must be recomputed to account for their // ever-changing veFXS balance. ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) = calcCurCombinedWeight(account); // Calculate the earnings first _syncEarned(account); // Update the user's stored veFXS multipliers _vefxsMultiplierStored[account] = new_vefxs_multiplier; // Update the user's and the global combined weights if (new_combined_weight >= old_combined_weight) { uint256 weight_diff = new_combined_weight - old_combined_weight; _total_combined_weight = _total_combined_weight + weight_diff; _combined_weights[account] = old_combined_weight + weight_diff; } else { uint256 weight_diff = old_combined_weight - new_combined_weight; _total_combined_weight = _total_combined_weight - weight_diff; _combined_weights[account] = old_combined_weight - weight_diff; } } } function _syncEarned(address account) internal { if (account != address(0)) { // Calculate the earnings uint256[] memory earned_arr = earned(account); // Update the rewards array for (uint256 i = 0; i < earned_arr.length; i++){ rewards[account][i] = earned_arr[i]; } // Update the rewards paid array for (uint256 i = 0; i < earned_arr.length; i++){ userRewardsPerTokenPaid[account][i] = rewardsPerTokenStored[i]; } } } // ------ REWARDS CLAIMING ------ function _getRewardExtraLogic(address rewardee, address destination_address) internal virtual { revert("Need gREL logic"); } // Two different getReward functions are needed because of delegateCall and msg.sender issues function getReward(address destination_address) external nonReentrant returns (uint256[] memory) { require(rewardsCollectionPaused == false, "Rewards collection paused"); return _getReward(msg.sender, destination_address); } // No withdrawer == msg.sender check needed since this is only internally callable function _getReward(address rewardee, address destination_address) internal updateRewardAndBalance(rewardee, true) returns (uint256[] memory rewards_before) { // Update the rewards array and distribute rewards rewards_before = new uint256[](rewardTokens.length); for (uint256 i = 0; i < rewardTokens.length; i++){ rewards_before[i] = rewards[rewardee][i]; rewards[rewardee][i] = 0; TransferHelper.safeTransfer(rewardTokens[i], destination_address, rewards_before[i]); } // Handle additional reward logic _getRewardExtraLogic(rewardee, destination_address); // Update the last reward claim time lastRewardClaimTime[rewardee] = block.timestamp; } // ------ FARM SYNCING ------ // If the period expired, renew it function retroCatchUp() internal { // Pull in rewards from the rewards distributor, if applicable for (uint256 i = 0; i < rewardDistributors.length; i++){ address reward_distributor_address = rewardDistributors[i]; if (reward_distributor_address != address(0)) { IFraxGaugeFXSRewardsDistributor(reward_distributor_address).distributeReward(address(this)); } } // 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 num_periods_elapsed = uint256(block.timestamp - periodFinish) / rewardsDuration; // Floor division to the nearest period // Make sure there are enough tokens to renew the reward period for (uint256 i = 0; i < rewardTokens.length; i++){ require((rewardRates(i) * rewardsDuration * (num_periods_elapsed + 1)) <= ERC20(rewardTokens[i]).balanceOf(address(this)), string(abi.encodePacked("Not enough reward tokens available: ", rewardTokens[i])) ); } // uint256 old_lastUpdateTime = lastUpdateTime; // uint256 new_lastUpdateTime = block.timestamp; // lastUpdateTime = periodFinish; periodFinish = periodFinish + ((num_periods_elapsed + 1) * rewardsDuration); // Update the rewards and time _updateStoredRewardsAndTime(); // Update the fraxPerLPStored fraxPerLPStored = fraxPerLPToken(); } function _updateStoredRewardsAndTime() internal { // Get the rewards uint256[] memory rewards_per_token = rewardsPerToken(); // Update the rewardsPerTokenStored for (uint256 i = 0; i < rewardsPerTokenStored.length; i++){ rewardsPerTokenStored[i] = rewards_per_token[i]; } // Update the last stored time lastUpdateTime = lastTimeRewardApplicable(); } function sync_gauge_weights(bool force_update) public { // Loop through the gauge controllers for (uint256 i = 0; i < gaugeControllers.length; i++){ address gauge_controller_address = gaugeControllers[i]; if (gauge_controller_address != address(0)) { if (force_update || (block.timestamp > last_gauge_time_totals[i])){ // Update the gauge_relative_weight last_gauge_relative_weights[i] = IFraxGaugeController(gauge_controller_address).gauge_relative_weight_write(address(this), block.timestamp); last_gauge_time_totals[i] = IFraxGaugeController(gauge_controller_address).time_total(); } } } } function sync() public { // Sync the gauge weight, if applicable sync_gauge_weights(false); if (block.timestamp >= periodFinish) { retroCatchUp(); } else { _updateStoredRewardsAndTime(); } } function sync_other() external { // Update the fraxPerLPStored fraxPerLPStored = fraxPerLPToken(); } /* ========== RESTRICTED FUNCTIONS - Curator / migrator callable ========== */ // ------ FARM SYNCING ------ // In children... // ------ PAUSES AND GREYLISTING ------ function setPauses( bool _stakingPaused, bool _withdrawalsPaused, bool _rewardsCollectionPaused ) external onlyByOwnGov { stakingPaused = _stakingPaused; withdrawalsPaused = _withdrawalsPaused; rewardsCollectionPaused = _rewardsCollectionPaused; } function greylistAddress(address _address) external onlyByOwnGov { greylist[_address] = !(greylist[_address]); } /* ========== RESTRICTED FUNCTIONS - Owner or timelock only ========== */ function unlockStakes() external onlyByOwnGov { stakesUnlocked = !stakesUnlocked; } function toggleMigrations() external onlyByOwnGov { migrationsOn = !migrationsOn; } // Adds supported migrator address function toggleMigrator(address migrator_address) external onlyByOwnGov { valid_migrators[migrator_address] = !valid_migrators[migrator_address]; } // Adds a valid veFXS proxy address function toggleValidVeFXSProxy(address _proxy_addr) external onlyByOwnGov { valid_vefxs_proxies[_proxy_addr] = !valid_vefxs_proxies[_proxy_addr]; } // Added to support recovering LP Rewards and other mistaken tokens from other systems to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyTknMgrs(tokenAddress) { // Check if the desired token is a reward token bool isRewardToken = false; for (uint256 i = 0; i < rewardTokens.length; i++){ if (rewardTokens[i] == tokenAddress) { isRewardToken = true; break; } } // Only the reward managers can take back their reward tokens // Also, other tokens, like the staking token, airdrops, or accidental deposits, can be withdrawn by the owner if ( (isRewardToken && rewardManagers[tokenAddress] == msg.sender) || (!isRewardToken && (msg.sender == owner)) ) { TransferHelper.safeTransfer(tokenAddress, msg.sender, tokenAmount); return; } // If none of the above conditions are true else { revert("No valid tokens to recover"); } } function setMiscVariables( uint256[6] memory _misc_vars // [0]: uint256 _lock_max_multiplier, // [1] uint256 _vefxs_max_multiplier, // [2] uint256 _vefxs_per_frax_for_max_boost, // [3] uint256 _vefxs_boost_scale_factor, // [4] uint256 _lock_time_for_max_multiplier, // [5] uint256 _lock_time_min ) external onlyByOwnGov { require(_misc_vars[0] >= MULTIPLIER_PRECISION, "Must be >= MUL PREC"); require((_misc_vars[1] >= 0) && (_misc_vars[2] >= 0) && (_misc_vars[3] >= 0), "Must be >= 0"); require((_misc_vars[4] >= 1) && (_misc_vars[5] >= 1), "Must be >= 1"); lock_max_multiplier = _misc_vars[0]; vefxs_max_multiplier = _misc_vars[1]; vefxs_per_frax_for_max_boost = _misc_vars[2]; vefxs_boost_scale_factor = _misc_vars[3]; lock_time_for_max_multiplier = _misc_vars[4]; lock_time_min = _misc_vars[5]; } // The owner or the reward token managers can set reward rates function setRewardVars(address reward_token_address, uint256 _new_rate, address _gauge_controller_address, address _rewards_distributor_address) external onlyTknMgrs(reward_token_address) { rewardRatesManual[rewardTokenAddrToIdx[reward_token_address]] = _new_rate; gaugeControllers[rewardTokenAddrToIdx[reward_token_address]] = _gauge_controller_address; rewardDistributors[rewardTokenAddrToIdx[reward_token_address]] = _rewards_distributor_address; } // The owner or the reward token managers can change managers function changeTokenManager(address reward_token_address, address new_manager_address) external onlyTknMgrs(reward_token_address) { rewardManagers[reward_token_address] = new_manager_address; } /* ========== A CHICKEN ========== */ // // ,~. // ,-'__ `-, // {,-' `. } ,') // ,( a ) `-.__ ,',')~, // <=.) ( `-.__,==' ' ' '} // ( ) /) // `-'\ , ) // | \ `~. / // \ `._ \ / // \ `._____,' ,' // `-. ,' // `-._ _,-' // 77jj' // //_|| // __//--'/` // ,--'/` ' // // [hjw] https://textart.io/art/vw6Sa3iwqIRGkZsN1BC2vweF/chicken } // File contracts/Misc_AMOs/vesper/IVPool.sol interface IVPool { function DOMAIN_SEPARATOR() external view returns (bytes32); function MAX_BPS() external view returns (uint256); function VERSION() external view returns (string memory); function acceptGovernorship() external; function addInList(address _listToUpdate, address _addressToAdd) external; function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function availableCreditLimit(address _strategy) external view returns (uint256); function balanceOf(address account) external view returns (uint256); function convertFrom18(uint256 _amount) external view returns (uint256); function decimalConversionFactor() external view returns (uint256); function decimals() external view returns (uint8); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function deposit(uint256 _amount) external; function depositWithPermit(uint256 _amount, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s) external; function excessDebt(address _strategy) external view returns (uint256); function feeCollector() external view returns (address); function feeWhitelist() external view returns (address); function getStrategies() external view returns (address[] memory); function getWithdrawQueue() external view returns (address[] memory); function governor() external view returns (address); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function initialize(string memory _name, string memory _symbol, address _token, address _poolAccountant, address _addressListFactory) external; function keepers() external view returns (address); function maintainers() external view returns (address); function migrateStrategy(address _old, address _new) external; function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool); function name() external view returns (string memory); function nonces(address) external view returns (uint256); function open() external; function pause() external; function paused() external view returns (bool); function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function poolAccountant() external view returns (address); function poolRewards() external view returns (address); function pricePerShare() external view returns (uint256); function removeFromList(address _listToUpdate, address _addressToRemove) external; function reportEarning(uint256 _profit, uint256 _loss, uint256 _payback) external; function reportLoss(uint256 _loss) external; function shutdown() external; function stopEverything() external view returns (bool); function strategy(address _strategy) external view returns (bool _active, uint256 _interestFee, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio); function sweepERC20(address _fromToken) external; function symbol() external view returns (string memory); function token() external view returns (address); function tokensHere() external view returns (uint256); function totalDebt() external view returns (uint256); function totalDebtOf(address _strategy) external view returns (uint256); function totalDebtRatio() external view returns (uint256); function totalSupply() external view returns (uint256); function totalValue() external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function transferGovernorship(address _proposedGovernor) external; function unpause() external; function updateFeeCollector(address _newFeeCollector) external; function updatePoolRewards(address _newPoolRewards) external; function updateWithdrawFee(uint256 _newWithdrawFee) external; function whitelistedWithdraw(uint256 _shares) external; function withdraw(uint256 _shares) external; function withdrawFee() external view returns (uint256); } // File contracts/Staking/FraxUnifiedFarm_ERC20.sol // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================= FraxUnifiedFarm_ERC20 ====================== // ==================================================================== // For ERC20 Tokens // Uses FraxUnifiedFarmTemplate.sol // -------------------- VARIES -------------------- // G-UNI // import "../Misc_AMOs/gelato/IGUniPool.sol"; // mStable // import '../Misc_AMOs/mstable/IFeederPool.sol'; // // StakeDAO sdETH-FraxPut // import '../Misc_AMOs/stakedao/IOpynPerpVault.sol'; // StakeDAO Vault // import '../Misc_AMOs/stakedao/IStakeDaoVault.sol'; // Uniswap V2 // import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; // Vesper // ------------------------------------------------ contract FraxUnifiedFarm_ERC20 is FraxUnifiedFarmTemplate { /* ========== STATE VARIABLES ========== */ // -------------------- VARIES -------------------- // G-UNI // IGUniPool public stakingToken; // mStable // IFeederPool public stakingToken; // sdETH-FraxPut Vault // IOpynPerpVault public stakingToken; // StakeDAO Vault // IStakeDaoVault public stakingToken; // Uniswap V2 // IUniswapV2Pair public stakingToken; // Vesper IVPool public stakingToken; // ------------------------------------------------ // Stake tracking mapping(address => LockedStake[]) public lockedStakes; /* ========== STRUCTS ========== */ // Struct for the stake struct LockedStake { bytes32 kek_id; uint256 start_timestamp; uint256 liquidity; uint256 ending_timestamp; uint256 lock_multiplier; // 6 decimals of precision. 1x = 1000000 } /* ========== CONSTRUCTOR ========== */ constructor ( address _owner, address[] memory _rewardTokens, address[] memory _rewardManagers, uint256[] memory _rewardRatesManual, address[] memory _gaugeControllers, address[] memory _rewardDistributors, address _stakingToken ) FraxUnifiedFarmTemplate(_owner, _rewardTokens, _rewardManagers, _rewardRatesManual, _gaugeControllers, _rewardDistributors) { // -------------------- VARIES -------------------- // G-UNI // stakingToken = IGUniPool(_stakingToken); // address token0 = address(stakingToken.token0()); // frax_is_token0 = token0 == frax_address; // mStable // stakingToken = IFeederPool(_stakingToken); // StakeDAO sdETH-FraxPut Vault // stakingToken = IOpynPerpVault(_stakingToken); // StakeDAO Vault // stakingToken = IStakeDaoVault(_stakingToken); // Uniswap V2 // stakingToken = IUniswapV2Pair(_stakingToken); // address token0 = stakingToken.token0(); // if (token0 == frax_address) frax_is_token0 = true; // else frax_is_token0 = false; // Vesper stakingToken = IVPool(_stakingToken); // address token0 = address(stakingToken.token0()); // frax_is_token0 = token0 == frax_address; // ------------------------------------------------ } /* ============= VIEWS ============= */ // ------ FRAX RELATED ------ function fraxPerLPToken() public view override returns (uint256) { // Get the amount of FRAX 'inside' of the lp tokens uint256 frax_per_lp_token; // G-UNI // ============================================ // { // (uint256 reserve0, uint256 reserve1) = stakingToken.getUnderlyingBalances(); // uint256 total_frax_reserves = frax_is_token0 ? reserve0 : reserve1; // frax_per_lp_token = (total_frax_reserves * 1e18) / stakingToken.totalSupply(); // } // mStable // ============================================ // { // uint256 total_frax_reserves; // (, IFeederPool.BassetData memory vaultData) = (stakingToken.getBasset(frax_address)); // total_frax_reserves = uint256(vaultData.vaultBalance); // frax_per_lp_token = (total_frax_reserves * 1e18) / stakingToken.totalSupply(); // } // StakeDAO sdETH-FraxPut Vault // ============================================ // { // uint256 frax3crv_held = stakingToken.totalUnderlyingControlled(); // // Optimistically assume 50/50 FRAX/3CRV ratio in the metapool to save gas // frax_per_lp_token = ((frax3crv_held * 1e18) / stakingToken.totalSupply()) / 2; // } // StakeDAO Vault // ============================================ // { // uint256 frax3crv_held = stakingToken.balance(); // // Optimistically assume 50/50 FRAX/3CRV ratio in the metapool to save gas // frax_per_lp_token = ((frax3crv_held * 1e18) / stakingToken.totalSupply()) / 2; // } // Uniswap V2 // ============================================ // { // uint256 total_frax_reserves; // (uint256 reserve0, uint256 reserve1, ) = (stakingToken.getReserves()); // if (frax_is_token0) total_frax_reserves = reserve0; // else total_frax_reserves = reserve1; // frax_per_lp_token = (total_frax_reserves * 1e18) / stakingToken.totalSupply(); // } // Vesper // ============================================ frax_per_lp_token = stakingToken.pricePerShare(); return frax_per_lp_token; } // ------ LIQUIDITY AND WEIGHTS ------ // Calculated the combined weight for an account function calcCurCombinedWeight(address account) public override view returns ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) { // Get the old combined weight old_combined_weight = _combined_weights[account]; // Get the veFXS multipliers // For the calculations, use the midpoint (analogous to midpoint Riemann sum) new_vefxs_multiplier = veFXSMultiplier(account); uint256 midpoint_vefxs_multiplier; if (_locked_liquidity[account] == 0 && _combined_weights[account] == 0) { // This is only called for the first stake to make sure the veFXS multiplier is not cut in half midpoint_vefxs_multiplier = new_vefxs_multiplier; } else { midpoint_vefxs_multiplier = (new_vefxs_multiplier + _vefxsMultiplierStored[account]) / 2; } // Loop through the locked stakes, first by getting the liquidity * lock_multiplier portion new_combined_weight = 0; for (uint256 i = 0; i < lockedStakes[account].length; i++) { LockedStake memory thisStake = lockedStakes[account][i]; uint256 lock_multiplier = thisStake.lock_multiplier; // If the lock is expired if (thisStake.ending_timestamp <= block.timestamp) { // If the lock expired in the time since the last claim, the weight needs to be proportionately averaged this time if (lastRewardClaimTime[account] < thisStake.ending_timestamp){ uint256 time_before_expiry = thisStake.ending_timestamp - lastRewardClaimTime[account]; uint256 time_after_expiry = block.timestamp - thisStake.ending_timestamp; // Get the weighted-average lock_multiplier uint256 numerator = (lock_multiplier * time_before_expiry) + (MULTIPLIER_PRECISION * time_after_expiry); lock_multiplier = numerator / (time_before_expiry + time_after_expiry); } // Otherwise, it needs to just be 1x else { lock_multiplier = MULTIPLIER_PRECISION; } } uint256 liquidity = thisStake.liquidity; uint256 combined_boosted_amount = (liquidity * (lock_multiplier + midpoint_vefxs_multiplier)) / MULTIPLIER_PRECISION; new_combined_weight = new_combined_weight + combined_boosted_amount; } } // ------ LOCK RELATED ------ // All the locked stakes for a given account function lockedStakesOf(address account) external view returns (LockedStake[] memory) { return lockedStakes[account]; } // Returns the length of the locked stakes for a given account function lockedStakesOfLength(address account) external view returns (uint256) { return lockedStakes[account].length; } // // All the locked stakes for a given account [old-school method] // function lockedStakesOfMultiArr(address account) external view returns ( // bytes32[] memory kek_ids, // uint256[] memory start_timestamps, // uint256[] memory liquidities, // uint256[] memory ending_timestamps, // uint256[] memory lock_multipliers // ) { // for (uint256 i = 0; i < lockedStakes[account].length; i++){ // LockedStake memory thisStake = lockedStakes[account][i]; // kek_ids[i] = thisStake.kek_id; // start_timestamps[i] = thisStake.start_timestamp; // liquidities[i] = thisStake.liquidity; // ending_timestamps[i] = thisStake.ending_timestamp; // lock_multipliers[i] = thisStake.lock_multiplier; // } // } /* =============== MUTATIVE FUNCTIONS =============== */ // ------ STAKING ------ function _getStake(address staker_address, bytes32 kek_id) internal view returns (LockedStake memory locked_stake, uint256 arr_idx) { for (uint256 i = 0; i < lockedStakes[staker_address].length; i++){ if (kek_id == lockedStakes[staker_address][i].kek_id){ locked_stake = lockedStakes[staker_address][i]; arr_idx = i; break; } } require(locked_stake.kek_id == kek_id, "Stake not found"); } // Add additional LPs to an existing locked stake function lockAdditional(bytes32 kek_id, uint256 addl_liq) updateRewardAndBalance(msg.sender, true) public { // Get the stake and its index (LockedStake memory thisStake, uint256 theArrayIndex) = _getStake(msg.sender, kek_id); // Calculate the new amount uint256 new_amt = thisStake.liquidity + addl_liq; // Checks require(addl_liq >= 0, "Must be nonzero"); // Pull the tokens from the sender TransferHelper.safeTransferFrom(address(stakingToken), msg.sender, address(this), addl_liq); // Update the stake lockedStakes[msg.sender][theArrayIndex] = LockedStake( kek_id, thisStake.start_timestamp, new_amt, thisStake.ending_timestamp, thisStake.lock_multiplier ); // Update liquidities _total_liquidity_locked += addl_liq; _locked_liquidity[msg.sender] += addl_liq; // Need to call to update the combined weights _updateRewardAndBalance(msg.sender, false); } // Two different stake functions are needed because of delegateCall and msg.sender issues (important for migration) function stakeLocked(uint256 liquidity, uint256 secs) nonReentrant external { _stakeLocked(msg.sender, msg.sender, liquidity, secs, block.timestamp); } function _stakeLockedInternalLogic( address source_address, uint256 liquidity ) internal virtual { revert("Need _stakeLockedInternalLogic logic"); } // If this were not internal, and source_address had an infinite approve, this could be exploitable // (pull funds from source_address and stake for an arbitrary staker_address) function _stakeLocked( address staker_address, address source_address, uint256 liquidity, uint256 secs, uint256 start_timestamp ) internal updateRewardAndBalance(staker_address, true) { require(stakingPaused == false || valid_migrators[msg.sender] == true, "Staking paused or in migration"); require(greylist[staker_address] == false, "Address has been greylisted"); require(secs >= lock_time_min, "Minimum stake time not met"); require(secs <= lock_time_for_max_multiplier,"Trying to lock for too long"); // Pull in the required token(s) // Varies per farm TransferHelper.safeTransferFrom(address(stakingToken), source_address, address(this), liquidity); // Get the lock multiplier and kek_id uint256 lock_multiplier = lockMultiplier(secs); bytes32 kek_id = keccak256(abi.encodePacked(staker_address, start_timestamp, liquidity, _locked_liquidity[staker_address])); // Create the locked stake lockedStakes[staker_address].push(LockedStake( kek_id, start_timestamp, liquidity, start_timestamp + secs, lock_multiplier )); // Update liquidities _total_liquidity_locked += liquidity; _locked_liquidity[staker_address] += liquidity; // Need to call again to make sure everything is correct _updateRewardAndBalance(staker_address, false); emit StakeLocked(staker_address, liquidity, secs, kek_id, source_address); } // ------ WITHDRAWING ------ // Two different withdrawLocked functions are needed because of delegateCall and msg.sender issues (important for migration) function withdrawLocked(bytes32 kek_id, address destination_address) nonReentrant external { require(withdrawalsPaused == false, "Withdrawals paused"); _withdrawLocked(msg.sender, destination_address, kek_id); } // No withdrawer == msg.sender check needed since this is only internally callable and the checks are done in the wrapper // functions like migrator_withdraw_locked() and withdrawLocked() function _withdrawLocked( address staker_address, address destination_address, bytes32 kek_id ) internal { // Collect rewards first and then update the balances _getReward(staker_address, destination_address); // Get the stake and its index (LockedStake memory thisStake, uint256 theArrayIndex) = _getStake(staker_address, kek_id); require(block.timestamp >= thisStake.ending_timestamp || stakesUnlocked == true || valid_migrators[msg.sender] == true, "Stake is still locked!"); uint256 liquidity = thisStake.liquidity; if (liquidity > 0) { // Update liquidities _total_liquidity_locked = _total_liquidity_locked - liquidity; _locked_liquidity[staker_address] = _locked_liquidity[staker_address] - liquidity; // Remove the stake from the array delete lockedStakes[staker_address][theArrayIndex]; // Give the tokens to the destination_address // Should throw if insufficient balance stakingToken.transfer(destination_address, liquidity); // Need to call again to make sure everything is correct _updateRewardAndBalance(staker_address, false); emit WithdrawLocked(staker_address, liquidity, kek_id, destination_address); } } function _getRewardExtraLogic(address rewardee, address destination_address) internal override { // Do nothing } /* ========== RESTRICTED FUNCTIONS - Curator / migrator callable ========== */ // Migrator can stake for someone else (they won't be able to withdraw it back though, only staker_address can). function migrator_stakeLocked_for(address staker_address, uint256 amount, uint256 secs, uint256 start_timestamp) external isMigrating { require(staker_allowed_migrators[staker_address][msg.sender] && valid_migrators[msg.sender], "Mig. invalid or unapproved"); _stakeLocked(staker_address, msg.sender, amount, secs, start_timestamp); } // Used for migrations function migrator_withdraw_locked(address staker_address, bytes32 kek_id) external isMigrating { require(staker_allowed_migrators[staker_address][msg.sender] && valid_migrators[msg.sender], "Mig. invalid or unapproved"); _withdrawLocked(staker_address, msg.sender, kek_id); } /* ========== RESTRICTED FUNCTIONS - Owner or timelock only ========== */ // Inherited... /* ========== EVENTS ========== */ event StakeLocked(address indexed user, uint256 amount, uint256 secs, bytes32 kek_id, address source_address); event WithdrawLocked(address indexed user, uint256 liquidity, bytes32 kek_id, address destination_address); } // File contracts/Staking/Variants/FraxUnifiedFarm_ERC20_Vesper_Orbit_FRAX.sol contract FraxUnifiedFarm_ERC20_Vesper_Orbit_FRAX is FraxUnifiedFarm_ERC20 { constructor ( address _owner, address[] memory _rewardTokens, address[] memory _rewardManagers, uint256[] memory _rewardRates, address[] memory _gaugeControllers, address[] memory _rewardDistributors, address _stakingToken ) FraxUnifiedFarm_ERC20(_owner , _rewardTokens, _rewardManagers, _rewardRates, _gaugeControllers, _rewardDistributors, _stakingToken) {} }
Total locked liquidity / LP tokens
function lockedLiquidityOf(address account) external view returns (uint256) { return _locked_liquidity[account]; }
193,426
[ 1, 5269, 8586, 4501, 372, 24237, 342, 511, 52, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 48, 18988, 24237, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 15091, 67, 549, 372, 24237, 63, 4631, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/math/Math.sol pragma solidity 0.5.16; library Math { function MAX818(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN910(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE710(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity 0.5.16; library SafeMath { function ADD553(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB354(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB354(a, b, "SafeMath: subtraction overflow"); } function SUB354(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL618(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV720(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV720(a, b, "SafeMath: division by zero"); } function DIV720(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function MOD811(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD811(a, b, "SafeMath: modulo by zero"); } function MOD811(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity 0.5.16; contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER101() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA729() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/ownership/Ownable.sol pragma solidity 0.5.16; contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED297(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = _MSGSENDER101(); emit OWNERSHIPTRANSFERRED297(address(0), _owner); } function OWNER579() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER471() { //inject NONSTANDARD NAMING require(ISOWNER602(), "Ownable: caller is not the owner"); _; } function ISOWNER602() public view returns (bool) { //inject NONSTANDARD NAMING return _MSGSENDER101() == _owner; } function RENOUNCEOWNERSHIP987() public ONLYOWNER471 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED297(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP49(address newOwner) public ONLYOWNER471 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP728(newOwner); } function _TRANSFEROWNERSHIP728(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED297(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity 0.5.16; interface IERC20 { function TOTALSUPPLY250() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF938(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER79(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function MINT2(address account, uint amount) external; //inject NONSTANDARD NAMING function ALLOWANCE644(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE576(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM482(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER160(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL369(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity 0.5.16; library Address { function ISCONTRACT625(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // 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); } function TOPAYABLE310(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE700(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity 0.5.16; library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER546(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.TRANSFER79.selector, to, value)); } function SAFETRANSFERFROM6(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.TRANSFERFROM482.selector, from, to, value)); } function SAFEAPPROVE811(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // 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.ALLOWANCE644(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.APPROVE576.selector, spender, value)); } function SAFEINCREASEALLOWANCE917(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE644(address(this), spender).ADD553(value); CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.APPROVE576.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE400(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE644(address(this), spender).SUB354(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.APPROVE576.selector, spender, newAllowance)); } function CALLOPTIONALRETURN509(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).ISCONTRACT625(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity 0.5.16; contract IRewardDistributionRecipient is Ownable { address rewardDistribution; function NOTIFYREWARDAMOUNT190(uint256 reward) external; //inject NONSTANDARD NAMING modifier ONLYREWARDDISTRIBUTION587() { //inject NONSTANDARD NAMING require(_MSGSENDER101() == rewardDistribution, "Caller is not reward distribution"); _; } function SETREWARDDISTRIBUTION306(address _rewardDistribution) //inject NONSTANDARD NAMING external ONLYOWNER471 { rewardDistribution = _rewardDistribution; } } pragma solidity 0.5.16; contract GOFTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public stakeToken = IERC20(0x514910771AF9Ca656af840dff83E8264EcF986CA); uint256 private _totalSupply; mapping(address => uint256) private _balances; function TOTALSUPPLY250() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF938(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function STAKE102(uint256 amount) public { //inject NONSTANDARD NAMING _totalSupply = _totalSupply.ADD553(amount); _balances[msg.sender] = _balances[msg.sender].ADD553(amount); stakeToken.SAFETRANSFERFROM6(msg.sender, address(this), amount); } function WITHDRAW201(uint256 amount) public { //inject NONSTANDARD NAMING _totalSupply = _totalSupply.SUB354(amount); _balances[msg.sender] = _balances[msg.sender].SUB354(amount); stakeToken.SAFETRANSFER546(msg.sender, amount); } } pragma solidity 0.5.16; contract GOFLINKPool is GOFTokenWrapper, IRewardDistributionRecipient { IERC20 public gof = IERC20(0x488E0369f9BC5C40C002eA7c1fe4fd01A198801c); uint256 public constant duration144 = 7 days; //inject NONSTANDARD NAMING uint256 public constant starttime308 = 1599652800; //utc+8 2020-09-09 20:00:00 //inject NONSTANDARD NAMING uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored = 0; bool private open = true; uint256 private constant _gunit942 = 1e18; //inject NONSTANDARD NAMING mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; // Unclaimed rewards event REWARDADDED578(uint256 reward); //inject NONSTANDARD NAMING event STAKED569(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAWN869(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event REWARDPAID604(address indexed user, uint256 reward); //inject NONSTANDARD NAMING event SETOPEN70(bool _open); //inject NONSTANDARD NAMING modifier UPDATEREWARD304(address account) { //inject NONSTANDARD NAMING rewardPerTokenStored = REWARDPERTOKEN70(); lastUpdateTime = LASTTIMEREWARDAPPLICABLE508(); if (account != address(0)) { rewards[account] = EARNED147(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function LASTTIMEREWARDAPPLICABLE508() public view returns (uint256) { //inject NONSTANDARD NAMING return Math.MIN910(block.timestamp, periodFinish); } function REWARDPERTOKEN70() public view returns (uint256) { //inject NONSTANDARD NAMING if (TOTALSUPPLY250() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.ADD553( LASTTIMEREWARDAPPLICABLE508() .SUB354(lastUpdateTime) .MUL618(rewardRate) .MUL618(_gunit942) .DIV720(TOTALSUPPLY250()) ); } function EARNED147(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return BALANCEOF938(account) .MUL618(REWARDPERTOKEN70().SUB354(userRewardPerTokenPaid[account])) .DIV720(_gunit942) .ADD553(rewards[account]); } function STAKE102(uint256 amount) public CHECKOPEN514 CHECKSTART795 UPDATEREWARD304(msg.sender){ //inject NONSTANDARD NAMING require(amount > 0, "Golff-Link-POOL: Cannot stake 0"); super.STAKE102(amount); emit STAKED569(msg.sender, amount); } function WITHDRAW201(uint256 amount) public CHECKSTART795 UPDATEREWARD304(msg.sender){ //inject NONSTANDARD NAMING require(amount > 0, "Golff-Link-POOL: Cannot withdraw 0"); super.WITHDRAW201(amount); emit WITHDRAWN869(msg.sender, amount); } function EXIT662() external { //inject NONSTANDARD NAMING WITHDRAW201(BALANCEOF938(msg.sender)); GETREWARD668(); } function GETREWARD668() public CHECKSTART795 UPDATEREWARD304(msg.sender){ //inject NONSTANDARD NAMING uint256 reward = EARNED147(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; gof.SAFETRANSFER546(msg.sender, reward); emit REWARDPAID604(msg.sender, reward); } } modifier CHECKSTART795(){ //inject NONSTANDARD NAMING require(block.timestamp > starttime308,"Golff-Link-POOL: Not start"); _; } modifier CHECKOPEN514() { //inject NONSTANDARD NAMING require(open, "Golff-Link-POOL: Pool is closed"); _; } function GETPERIODFINISH470() external view returns (uint256) { //inject NONSTANDARD NAMING return periodFinish; } function ISOPEN95() external view returns (bool) { //inject NONSTANDARD NAMING return open; } function SETOPEN315(bool _open) external ONLYOWNER471 { //inject NONSTANDARD NAMING open = _open; emit SETOPEN70(_open); } function NOTIFYREWARDAMOUNT190(uint256 reward) //inject NONSTANDARD NAMING external ONLYREWARDDISTRIBUTION587 CHECKOPEN514 UPDATEREWARD304(address(0)){ if (block.timestamp > starttime308){ if (block.timestamp >= periodFinish) { uint256 period = block.timestamp.SUB354(starttime308).DIV720(duration144).ADD553(1); periodFinish = starttime308.ADD553(period.MUL618(duration144)); rewardRate = reward.DIV720(periodFinish.SUB354(block.timestamp)); } else { uint256 remaining = periodFinish.SUB354(block.timestamp); uint256 leftover = remaining.MUL618(rewardRate); rewardRate = reward.ADD553(leftover).DIV720(remaining); } lastUpdateTime = block.timestamp; }else { rewardRate = reward.DIV720(duration144); periodFinish = starttime308.ADD553(duration144); lastUpdateTime = starttime308; } gof.MINT2(address(this),reward); emit REWARDADDED578(reward); // avoid overflow to lock assets _CHECKREWARDRATE734(); } function _CHECKREWARDRATE734() internal view returns (uint256) { //inject NONSTANDARD NAMING return duration144.MUL618(rewardRate).MUL618(_gunit942); } }
utc+8 2020-09-09 20:00:00 inject NONSTANDARD NAMING
uint256 public constant starttime308 = 1599652800;
5,362,693
[ 1, 17892, 15, 28, 26599, 20, 17, 5908, 17, 5908, 4200, 30, 713, 30, 713, 202, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 5381, 23437, 5082, 28, 273, 4711, 2733, 9222, 6030, 713, 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 ]
pragma solidity ^0.5.0; import './ERCX.sol'; import '../Interface/IERCXMetadata.sol'; contract ERCXMetadata is ERC165, ERCX, IERCXMetadata { // item name string internal _name; // item symbol string internal _symbol; // Base URI string private _baseURI; // Optional mapping for item URIs mapping(uint256 => string) private _itemURIs; bytes4 private constant InterfaceId_ERCXMetadata = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('itemURI(uint256)')); /** * @dev Constructor function */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERCX via ERC165 _registerInterface(InterfaceId_ERCXMetadata); } /** * @dev Gets the item name * @return string representing the item name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the item symbol * @return string representing the item symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given item ID * Throws if the item ID does not exist. May return an empty string. * @param itemId uint256 ID of the item to query */ function itemURI(uint256 itemId) public view returns (string memory) { require( _exists(itemId,1), "URI query for nonexistent item"); string memory _itemURI = _itemURIs[itemId]; // Even if there is a base URI, it is only appended to non-empty item-specific URIs if (bytes(_itemURI).length == 0) { return ""; } else { // abi.encodePacked is being used to concatenate strings return string(abi.encodePacked(_baseURI, _itemURI)); } } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a preffix in {itemURI} to each item's URI, when * they are non-empty. */ function baseURI() external view returns (string memory) { return _baseURI; } /** * @dev Internal function to set the item URI for a given item * Reverts if the item ID does not exist * @param itemId uint256 ID of the item to set its URI * @param uri string URI to assign */ function _setItemURI(uint256 itemId, string memory uri) internal { require(_exists(itemId,1)); _itemURIs[itemId] = uri; } /** * @dev Internal function to set the base URI for all item IDs. It is * automatically added as a prefix to the value returned in {itemURI}. * * _Available since v2.5.0._ */ function _setBaseURI(string memory baseUri) internal { _baseURI = baseUri; } /** * @dev Internal function to burn a specific item * Reverts if the item does not exist * @param itemId uint256 ID of the item being burned by the msg.sender */ function _burn(uint256 itemId) internal { super._burn(itemId); // Clear metadata (if any) if (bytes(_itemURIs[itemId]).length != 0) { delete _itemURIs[itemId]; } } }
* @dev Internal function to burn a specific item Reverts if the item does not exist @param itemId uint256 ID of the item being burned by the msg.sender/ Clear metadata (if any)
function _burn(uint256 itemId) internal { super._burn(itemId); if (bytes(_itemURIs[itemId]).length != 0) { delete _itemURIs[itemId]; } }
12,610,835
[ 1, 3061, 445, 358, 18305, 279, 2923, 761, 868, 31537, 309, 326, 761, 1552, 486, 1005, 225, 18424, 2254, 5034, 1599, 434, 326, 761, 3832, 18305, 329, 635, 326, 1234, 18, 15330, 19, 10121, 1982, 261, 430, 1281, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 70, 321, 12, 11890, 5034, 18424, 13, 2713, 288, 203, 565, 2240, 6315, 70, 321, 12, 1726, 548, 1769, 203, 203, 565, 309, 261, 3890, 24899, 1726, 1099, 2520, 63, 1726, 548, 65, 2934, 2469, 480, 374, 13, 288, 203, 1377, 1430, 389, 1726, 1099, 2520, 63, 1726, 548, 15533, 203, 565, 289, 203, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2019-07-31 */ /* pragma solidity ^0.4.24; */ pragma solidity ^0.5.0; // File: contracts/math/SafeMath.sol // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol // @title SafeMath: overflow/underflow checks // @notice Math operations with safety checks that throw on error library SafeMath { // @notice 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; } // @notice Integer division of two numbers, truncating the quotient. function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } // @notice Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } // @notice 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; } // @notice Returns fractional amount function getFractionalAmount(uint256 _amount, uint256 _percentage) internal pure returns (uint256) { /* return div(mul(_amount, _percentage), 100); */ } } // File: contracts/interfaces/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface ERC20 { function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address _who) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/interfaces/DividendInterface.sol interface DividendInterface{ function issueDividends(uint _amount) external payable returns (bool); // @dev Total number of tokens in existence function totalSupply() external view returns (uint256); function getERC20() external view returns (address); } // File: contracts/interfaces/KyberInterface.sol // @notice Trade via the Kyber Proxy Contract interface KyberInterface { function getExpectedRate(address src, address dest, uint srcQty) external view returns (uint expectedRate, uint slippageRate); function trade(address src, uint srcAmount, address dest, address destAddress, uint maxDestAmount,uint minConversionRate, address walletId) external payable returns(uint); } // File: contracts/interfaces/MinterInterface.sol interface MinterInterface { function cloneToken(string calldata _uri, address _erc20Address) external returns (address asset); function mintAssetTokens(address _assetAddress, address _receiver, uint256 _amount) external returns (bool); function changeTokenController(address _assetAddress, address _newController) external returns (bool); } // File: contracts/interfaces/CrowdsaleReserveInterface.sol interface CrowdsaleReserveInterface { function issueETH(address _receiver, uint256 _amount) external returns (bool); function receiveETH(address _payer) external payable returns (bool); function refundETHAsset(address _asset, uint256 _amount) external returns (bool); function issueERC20(address _receiver, uint256 _amount, address _tokenAddress) external returns (bool); function requestERC20(address _payer, uint256 _amount, address _tokenAddress) external returns (bool); function approveERC20(address _receiver, uint256 _amount, address _tokenAddress) external returns (bool); function refundERC20Asset(address _asset, uint256 _amount, address _tokenAddress) external returns (bool); } // File: contracts/crowdsale/CrowdsaleERC20.sol interface Events { function transaction(string calldata _message, address _from, address _to, uint _amount, address _token) external; function asset(string calldata _message, string calldata _uri, address _assetAddress, address _manager) external; } interface DB { function addressStorage(bytes32 _key) external view returns (address); function uintStorage(bytes32 _key) external view returns (uint); function setUint(bytes32 _key, uint _value) external; function deleteUint(bytes32 _key) external; function setBool(bytes32 _key, bool _value) external; function boolStorage(bytes32 _key) external view returns (bool); } // @title An asset crowdsale contract which accepts funding from ERC20 tokens. // @notice Begins a crowdfunding period for a digital asset, minting asset dividend tokens to investors when particular ERC20 token is received // @author Kyle Dewhurst, MyBit Foundation // @notice creates a dividend token to represent the newly created asset. contract CrowdsaleERC20{ using SafeMath for uint256; DB private database; Events private events; MinterInterface private minter; CrowdsaleReserveInterface private reserve; KyberInterface private kyber; // @notice Constructor: initializes database instance // @param: The address for the platform database constructor(address _database, address _events, address _kyber) public{ database = DB(_database); events = Events(_events); minter = MinterInterface(database.addressStorage(keccak256(abi.encodePacked("contract", "Minter")))); reserve = CrowdsaleReserveInterface(database.addressStorage(keccak256(abi.encodePacked("contract", "CrowdsaleReserve")))); kyber = KyberInterface(_kyber); } // @notice Investors can send ERC20 tokens here to fund an asset, receiving an equivalent number of asset-tokens. // @dev investor must approve this contract to transfer tokens // @param (address) _assetAddress = The address of the asset tokens, investor wishes to purchase // @param (uint) _amount = The amount to spend purchasing this asset function buyAssetOrderERC20(address _assetAddress, uint _amount, address _paymentToken) external payable returns (bool) { require(database.addressStorage(keccak256(abi.encodePacked("asset.manager", _assetAddress))) != address(0), "Invalid asset"); require(now <= database.uintStorage(keccak256(abi.encodePacked("crowdsale.deadline", _assetAddress))), "Past deadline"); require(!database.boolStorage(keccak256(abi.encodePacked("crowdsale.finalized", _assetAddress))), "Crowdsale finalized"); if(_paymentToken == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)){ require(msg.value == _amount, 'Msg.value does not match amount'); } else { require(msg.value == 0, 'Msg.value should equal zero'); } ERC20 fundingToken = ERC20(DividendInterface(_assetAddress).getERC20()); uint fundingRemaining = database.uintStorage(keccak256(abi.encodePacked("crowdsale.remaining", _assetAddress))); uint collected; //This will be the value received by the contract after any conversions uint amount; //The number of tokens that will be minted //Check if the payment token is the same as the funding token. If not, convert, else just collect the funds if(_paymentToken == address(fundingToken)){ collected = collectPayment(msg.sender, _amount, fundingRemaining, fundingToken); } else { collected = convertTokens(msg.sender, _amount, fundingToken, ERC20(_paymentToken), fundingRemaining); } require(collected > 0); if(collected < fundingRemaining){ amount = collected.mul(100).div(uint(100).add(database.uintStorage(keccak256(abi.encodePacked("platform.fee"))))); database.setUint(keccak256(abi.encodePacked("crowdsale.remaining", _assetAddress)), fundingRemaining.sub(collected)); require(minter.mintAssetTokens(_assetAddress, msg.sender, amount), "Investor minting failed"); require(fundingToken.transfer(address(reserve), collected)); } else { amount = fundingRemaining.mul(100).div(uint(100).add(database.uintStorage(keccak256(abi.encodePacked("platform.fee"))))); database.setBool(keccak256(abi.encodePacked("crowdsale.finalized", _assetAddress)), true); database.deleteUint(keccak256(abi.encodePacked("crowdsale.remaining", _assetAddress))); require(minter.mintAssetTokens(_assetAddress, msg.sender, amount), "Investor minting failed"); // Send remaining asset tokens to investor require(fundingToken.transfer(address(reserve), fundingRemaining)); events.asset('Crowdsale finalized', '', _assetAddress, msg.sender); if(collected > fundingRemaining){ require(fundingToken.transfer(msg.sender, collected.sub(fundingRemaining))); // return extra funds } } events.transaction('Asset purchased', address(this), msg.sender, amount, _assetAddress); return true; } // @notice This is called once funding has succeeded. Sends Ether to a distribution contract where operator/assetManager can withdraw // @dev The contract manager needs to know the address PlatformDistribution contract function payoutERC20(address _assetAddress) external whenNotPaused returns (bool) { require(database.boolStorage(keccak256(abi.encodePacked("crowdsale.finalized", _assetAddress))), "Crowdsale not finalized"); require(!database.boolStorage(keccak256(abi.encodePacked("crowdsale.paid", _assetAddress))), "Crowdsale has paid out"); //Set paid to true database.setBool(keccak256(abi.encodePacked("crowdsale.paid", _assetAddress)), true); //Setup token address fundingToken = DividendInterface(_assetAddress).getERC20(); //Mint tokens for the asset manager and platform address platformAssetsWallet = database.addressStorage(keccak256(abi.encodePacked("platform.wallet.assets"))); require(platformAssetsWallet != address(0), "Platform assets wallet not set"); require(minter.mintAssetTokens(_assetAddress, database.addressStorage(keccak256(abi.encodePacked("contract", "AssetManagerFunds"))), database.uintStorage(keccak256(abi.encodePacked("asset.managerTokens", _assetAddress)))), "Manager minting failed"); require(minter.mintAssetTokens(_assetAddress, platformAssetsWallet, database.uintStorage(keccak256(abi.encodePacked("asset.platformTokens", _assetAddress)))), "Platform minting failed"); //Get the addresses for the receiver and platform address receiver = database.addressStorage(keccak256(abi.encodePacked("asset.manager", _assetAddress))); address platformFundsWallet = database.addressStorage(keccak256(abi.encodePacked("platform.wallet.funds"))); require(receiver != address(0) && platformFundsWallet != address(0), "Platform funds walllet or receiver address not set"); //Calculate amounts for platform and receiver uint amount = database.uintStorage(keccak256(abi.encodePacked("crowdsale.goal", _assetAddress))); uint platformFee = amount.getFractionalAmount(database.uintStorage(keccak256(abi.encodePacked("platform.fee")))); //Transfer funds to receiver and platform require(reserve.issueERC20(platformFundsWallet, platformFee, fundingToken), 'Platform funds not paid'); require(reserve.issueERC20(receiver, amount, fundingToken), 'Receiver funds not paid'); //Delete crowdsale start time database.deleteUint(keccak256(abi.encodePacked("crowdsale.start", _assetAddress))); //Increase asset count for manager address manager = database.addressStorage(keccak256(abi.encodePacked("asset.manager", _assetAddress))); database.setUint(keccak256(abi.encodePacked("manager.assets", manager)), database.uintStorage(keccak256(abi.encodePacked("manager.assets", manager))).add(1)); //Emit event events.transaction('Asset payout', _assetAddress, receiver, amount, fundingToken); return true; } function cancel(address _assetAddress) external whenNotPaused validAsset(_assetAddress) beforeDeadline(_assetAddress) notFinalized(_assetAddress) returns (bool){ require(msg.sender == database.addressStorage(keccak256(abi.encodePacked("asset.manager", _assetAddress)))); database.setUint(keccak256(abi.encodePacked("crowdsale.deadline", _assetAddress)), 1); refund(_assetAddress); } // @notice Contributors can retrieve their funds here if crowdsale has paased deadline // @param (address) _assetAddress = The address of the asset which didn't reach it's crowdfunding goals function refund(address _assetAddress) public whenNotPaused validAsset(_assetAddress) afterDeadline(_assetAddress) notFinalized(_assetAddress) returns (bool) { require(database.uintStorage(keccak256(abi.encodePacked("crowdsale.deadline", _assetAddress))) != 0); database.deleteUint(keccak256(abi.encodePacked("crowdsale.deadline", _assetAddress))); DividendInterface assetToken = DividendInterface(_assetAddress); address tokenAddress = assetToken.getERC20(); uint refundValue = assetToken.totalSupply().mul(uint(100).add(database.uintStorage(keccak256(abi.encodePacked("platform.fee"))))).div(100); //total supply plus platform fees reserve.refundERC20Asset(_assetAddress, refundValue, tokenAddress); return true; } //------------------------------------------------------------------------------------------------------------------ // Internal Functions //------------------------------------------------------------------------------------------------------------------ function collectPayment(address user, uint amount, uint max, ERC20 token) private returns (uint){ if(amount > max){ token.transferFrom(user, address(this), max); return max; } else { token.transferFrom(user, address(this), amount); return amount; } } /* function fundBurn(address _investor, uint _amount, bytes4 _sig, ERC20 _burnToken) private returns (uint) { require(_burnToken.transferFrom(_investor, address(this), _amount), "Transfer failed"); // transfer investors tokens into contract uint balanceBefore = _burnToken.balanceOf(this); require(burner.burn(address(this), database.uintStorage(keccak256(abi.encodePacked(_sig, address(this)))), address(_burnToken))); uint change = _burnToken.balanceOf(this) - balanceBefore; return change; } */ function convertTokens(address payable _investor, uint _amount, /*bytes4 _sig,*/ ERC20 _fundingToken, ERC20 _paymentToken, uint _maxTokens) private returns (uint) { //( , uint minRate) = kyber.getExpectedRate(address(_paymentToken), address(_fundingToken), 0); uint paymentBalanceBefore; uint fundingBalanceBefore; uint change; uint investment; if(address(_paymentToken) == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)){ paymentBalanceBefore = address(this).balance; fundingBalanceBefore = _fundingToken.balanceOf(address(this)); //Convert remaining funds into the funding token kyber.trade.value(_amount)(address(_paymentToken), _amount, address(_fundingToken), address(this), _maxTokens, 0, address(0)); change = _amount.sub(paymentBalanceBefore.sub(address(this).balance)); investment = _fundingToken.balanceOf(address(this)).sub(fundingBalanceBefore); if(change > 0){ _investor.transfer(change); } } else { //Collect funds collectPayment(_investor, _amount, _amount, _paymentToken); // Mitigate ERC20 Approve front-running attack, by initially setting // allowance to 0 require(_paymentToken.approve(address(kyber), 0)); // Approve tokens so network can take them during the swap _paymentToken.approve(address(kyber), _amount); paymentBalanceBefore = _paymentToken.balanceOf(address(this)); fundingBalanceBefore = _fundingToken.balanceOf(address(this)); //Convert remaining funds into the funding token kyber.trade(address(_paymentToken), _amount, address(_fundingToken), address(this), _maxTokens, 0, address(0)); // Return any remaining source tokens to user change = _amount.sub(paymentBalanceBefore.sub(_paymentToken.balanceOf(address(this)))); investment = _fundingToken.balanceOf(address(this)).sub(fundingBalanceBefore); if(change > 0){ _paymentToken.transfer(_investor, change); } } emit Convert(address(_paymentToken), change, investment); return investment; } // @notice platform owners can recover tokens here function recoverTokens(address _erc20Token) onlyOwner external { ERC20 thisToken = ERC20(_erc20Token); uint contractBalance = thisToken.balanceOf(address(this)); thisToken.transfer(msg.sender, contractBalance); } // @notice platform owners can destroy contract here function destroy() onlyOwner external { events.transaction('CrowdsaleERC20 destroyed', address(this), msg.sender, address(this).balance, address(0)); //emit LogDestruction(address(this).balance, msg.sender); /* selfdestruct(msg.sender); */ msg.sender.send(address(this).balance); } // @notice fallback function. We need to receive Ether from Kyber Network function () external payable { emit EtherReceived(msg.sender, msg.value); } //------------------------------------------------------------------------------------------------------------------ // Modifiers //------------------------------------------------------------------------------------------------------------------ // @notice Sender must be a registered owner modifier onlyOwner { require(database.boolStorage(keccak256(abi.encodePacked("owner", msg.sender))), "Not owner"); _; } // @notice function won't run if owners have paused this contract modifier whenNotPaused { require(!database.boolStorage(keccak256(abi.encodePacked("paused", address(this))))); _; } // @notice reverts if the asset does not have a token address set in the database modifier validAsset(address _assetAddress) { require(database.addressStorage(keccak256(abi.encodePacked("asset.manager", _assetAddress))) != address(0), "Invalid asset"); _; } // @notice reverts if the funding deadline has not passed modifier beforeDeadline(address _assetAddress) { require(now < database.uintStorage(keccak256(abi.encodePacked("crowdsale.deadline", _assetAddress))), "Before deadline"); _; } // @notice reverts if the funding deadline has already past or crowsale has not started modifier betweenDeadlines(address _assetAddress) { require(now <= database.uintStorage(keccak256(abi.encodePacked("crowdsale.deadline", _assetAddress))), "Past deadline"); require(now >= database.uintStorage(keccak256(abi.encodePacked("crowdsale.start", _assetAddress))), "Before start time"); _; } // @notice reverts if the funding deadline has already past modifier afterDeadline(address _assetAddress) { require(now > database.uintStorage(keccak256(abi.encodePacked("crowdsale.deadline", _assetAddress))), "Before deadline"); _; } // @notice returns true if crowdsale is finshed modifier finalized(address _assetAddress) { require(database.boolStorage(keccak256(abi.encodePacked("crowdsale.finalized", _assetAddress))), "Crowdsale not finalized"); _; } // @notice returns true if crowdsale is not finshed modifier notFinalized(address _assetAddress) { require(!database.boolStorage(keccak256(abi.encodePacked("crowdsale.finalized", _assetAddress))), "Crowdsale finalized"); _; } // @notice returns true if crowdsale has not paid out modifier notPaid(address _assetAddress) { require(!database.boolStorage(keccak256(abi.encodePacked("crowdsale.paid", _assetAddress))), "Crowdsale has paid out"); _; } event Convert(address token, uint change, uint investment); event EtherReceived(address sender, uint amount); }
@notice reverts if the funding deadline has not passed
modifier beforeDeadline(address _assetAddress) { require(now < database.uintStorage(keccak256(abi.encodePacked("crowdsale.deadline", _assetAddress))), "Before deadline"); _; }
5,372,315
[ 1, 266, 31537, 309, 326, 22058, 14096, 711, 486, 2275, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9606, 1865, 15839, 12, 2867, 389, 9406, 1887, 13, 288, 203, 565, 2583, 12, 3338, 411, 2063, 18, 11890, 3245, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 2932, 71, 492, 2377, 5349, 18, 22097, 1369, 3113, 389, 9406, 1887, 3719, 3631, 315, 4649, 14096, 8863, 203, 565, 389, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "./TellorGetters.sol"; /** * @title Tellor Oracle System * @dev Oracle contract where miners can submit the proof of work along with the value. * The logic for this contract is in TellorLibrary.sol, TellorDispute.sol, TellorStake.sol, * and TellorTransfer.sol */ contract Tellor is TellorGetters{ using SafeMath for uint256; event NewTellorToken(address _token); /*Functions*/ constructor (address _tellorToken) public { tellor.uintVars[keccak256("decimals")] = 18; tellor.uintVars[keccak256("disputeFee")] = 10e18; tellor.uintVars[keccak256("minimumStake")] = 100e18; tellor.addressVars[keccak256("tellorToken")] = _tellorToken; emit NewTellorToken(_tellorToken); } /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute(uint256 _requestId, uint256 _timestamp, uint256 _minerIndex) external { tellor.beginDispute(_requestId, _timestamp, _minerIndex); } /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external { tellor.vote(_disputeId, _supportsDispute); } /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external { tellor.tallyVotes(_disputeId); } /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external { tellor.addTip(_requestId, _tip); } /** * @dev Proof of work is called by the miner when they submit the solution (proof of work and value) * @param _requestId the apiId being mined * @param _value of api query */ function submitMiningSolution(uint256 _requestId, uint256 _value) external { tellor.submitMiningSolution(_requestId, _value); } /** * @dev This function allows miners to deposit their stake. * @param _amount is the amount the sender wants to stake */ function depositStake(uint _amount) external { tellor.depositStake(_amount); } /** * @dev This function reselects validators if the originals did not complete the block */ function reselectNewValidators() external{ tellor.reselectNewValidators(); } /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake * @param _amount to unstake */ function requestStakingWithdraw(uint _amount) external { tellor.requestStakingWithdraw(_amount); } /** * @dev This function allows for the dispute fee to be unlocked after the dispute vote has elapsed * @param _disputeId is the disputeId to unlock the fee from */ function unlockDisputeFee (uint _disputeId) external{ tellor.unlockDisputeFee(_disputeId); } /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external { tellor.withdrawStake(); } /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory) { return "Tellor Tributes"; } /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory) { return "TRB"; } /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8) { return 18; } }
* @dev tallies the votes. @param _disputeId is the dispute id/
function tallyVotes(uint256 _disputeId) external { tellor.tallyVotes(_disputeId); }
1,046,190
[ 1, 88, 454, 606, 326, 19588, 18, 225, 389, 2251, 2507, 548, 353, 326, 1015, 2507, 612, 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, 268, 1230, 29637, 12, 11890, 5034, 389, 2251, 2507, 548, 13, 3903, 288, 203, 3639, 9276, 280, 18, 88, 1230, 29637, 24899, 2251, 2507, 548, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x4978dB69dE50602c64d72A3bc6DcBe0e90B040bC/sources/MasterChef.sol
Deposit LP tokens to MasterChef for ANON allocation.
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user .amount .mul(pool.accanonPerShare) .div(1e12) .sub(user.rewardDebt); safeanonTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accanonPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
3,918,329
[ 1, 758, 1724, 511, 52, 2430, 358, 13453, 39, 580, 74, 364, 432, 3993, 13481, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 3576, 18, 15330, 15533, 203, 3639, 1089, 2864, 24899, 6610, 1769, 203, 3639, 309, 261, 1355, 18, 8949, 405, 374, 13, 288, 203, 5411, 2254, 5034, 4634, 273, 729, 203, 7734, 263, 8949, 203, 7734, 263, 16411, 12, 6011, 18, 8981, 304, 265, 2173, 9535, 13, 203, 7734, 263, 2892, 12, 21, 73, 2138, 13, 203, 7734, 263, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 1769, 203, 5411, 4183, 304, 265, 5912, 12, 3576, 18, 15330, 16, 4634, 1769, 203, 3639, 289, 203, 3639, 2845, 18, 9953, 1345, 18, 4626, 5912, 1265, 12, 203, 5411, 1758, 12, 3576, 18, 15330, 3631, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 389, 8949, 203, 3639, 11272, 203, 3639, 729, 18, 8949, 273, 729, 18, 8949, 18, 1289, 24899, 8949, 1769, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 304, 265, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 1769, 203, 3639, 3626, 4019, 538, 305, 12, 3576, 18, 15330, 16, 389, 6610, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x77F67740bD08Ba29A8823EfdD81C25BBA6cBAe50/sources/contracts/OlympusERC20.sol
* @dev Returns the number of values on the set. O(1)./
function length(Bytes4Set storage set) internal view returns (uint256) { return _length(set._inner); }
647,043
[ 1, 1356, 326, 1300, 434, 924, 603, 326, 444, 18, 531, 12, 21, 2934, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 769, 12, 2160, 24, 694, 2502, 444, 13, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 389, 2469, 12, 542, 6315, 7872, 1769, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* * * https://t.me/Hubcoin_Official * * SPDX-License-Identifier: Unlicensed */ pragma solidity ^0.8.0; 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 ) { 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 () { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @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, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract HUB 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) public _isBlacklisted; mapping (address => bool) private _isExcluded; address[] private _excluded; mapping (address => bool) public _isExcludedBal; // list for Max Bal limits uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 500000000 * 10**18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "HubCoin"; string private _symbol = "HUB"; uint8 private _decimals = 18; uint256 public _burnFee = 5; uint256 private _previousBurnFee = _burnFee; uint256 public _taxFee = 5; uint256 private _previousTaxFee = _taxFee; uint256 private _liquidityFee = 12; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _buyFees = 12; uint256 public _sellFees = 12; address public marketing = 0xb7bE3BCb89865d04F32b6D5910CFeA0FCbEEB8E6; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public _maxBalAmount = _tTotal; uint256 public numTokensSellToAddToLiquidity = 1 * 10**18; bool public _taxEnabled = true; event SetTaxEnable(bool enabled); event SetSellFeePercent(uint256 sellFee); event SetBuyFeePercent(uint256 buyFee); event SetTaxFeePercent(uint256 taxFee); event SetMaxBalPercent(uint256 maxBalPercent); event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event TaxEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _rOwned[msg.sender] = _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; _isExcluded[uniswapV2Pair] = true; // excluded from rewards _isExcludedBal[uniswapV2Pair] = true; _isExcludedBal[owner()] = true; _isExcludedBal[address(this)] = true; _isExcludedBal[address(0)] = true; emit Transfer(address(0), msg.sender, _tTotal); _transfer(_msgSender(), address(0), 90000000 * 10**18); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _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 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 excludeFromLimit(address account) public onlyOwner() { require(!_isExcludedBal[account], "Account is already excluded"); _isExcludedBal[account] = true; } function includeInLimit(address account) external onlyOwner() { require(_isExcludedBal[account], "Account is already excluded"); _isExcludedBal[account] = false; } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tBurn ) = _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); if(tLiquidity > 0 ) _takeLiquidity(sender, tLiquidity); if(tBurn > 0) _burn(sender, tBurn); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function setFeeWallet( address _wallet) public onlyOwner { marketing = _wallet; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; emit SetTaxFeePercent(taxFee); } function setSellFeePercent(uint256 sellFee) external onlyOwner() { _sellFees = sellFee; emit SetSellFeePercent(sellFee); } function setBuyFeePercent(uint256 buyFee) external onlyOwner() { _buyFees = buyFee; emit SetBuyFeePercent(buyFee); } function setMaxBalPercent(uint256 maxBalPercent) external onlyOwner() { _maxBalAmount = _tTotal.mul(maxBalPercent).div( 10**3 ); emit SetMaxBalPercent(maxBalPercent); } function setSwapAmount(uint256 amount) external onlyOwner() { numTokensSellToAddToLiquidity = amount; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function setTaxEnable (bool _enable) public onlyOwner { _taxEnabled = _enable; emit SetTaxEnable(_enable); } //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) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tBurn) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate(), tBurn); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity, tBurn); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) { uint256 tBurn = calculateBurnFee(tAmount); uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity).sub(tBurn); return (tTransferAmount, tFee, tLiquidity, tBurn); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate, uint256 tBurn) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rBurn = tBurn.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity).sub(rBurn); 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(address sender, 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); emit Transfer(sender, address(this), tLiquidity); } function _burn(address sender, uint256 tBurn) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tBurn.mul(currentRate); _rOwned[address(0)] = _rOwned[address(0)].add(rLiquidity); if(_isExcluded[address(0)]) _tOwned[address(0)] = _tOwned[address(0)].add(tBurn); emit Transfer(sender, address(0), tBurn); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**3); } function calculateBurnFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_burnFee).div(10**3); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0 && _burnFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _previousBurnFee = _burnFee; _taxFee = 0; _liquidityFee = 0; _burnFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; _burnFee = _previousBurnFee; } 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 addToBlackList (address[] calldata accounts ) public onlyOwner { for (uint256 i =0; i < accounts.length; ++i ) { _isBlacklisted[accounts[i]] = true; } } function removeFromBlackList(address account) public onlyOwner { _isBlacklisted[account] = false; } function _transfer( address from, address to, uint256 amount ) private { require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted"); require(from != address(0), "ERC20: transfer from the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = false; if(from == uniswapV2Pair || to == uniswapV2Pair) { takeFee = true; } if(!_taxEnabled || _isExcludedFromFee[from] || _isExcludedFromFee[to]){ //if any account belongs to _isExcludedFromFee account then remove the fee takeFee = false; } if(from == uniswapV2Pair) { _liquidityFee = _buyFees; } if (to == uniswapV2Pair) { _liquidityFee = _sellFees; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { swapTokensForEth(contractTokenBalance); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 Balance = address(this).balance; (bool succ, ) = address(marketing).call{value: Balance}(""); require(succ, "marketing ETH not sent"); emit SwapAndLiquify(contractTokenBalance, Balance); } 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 ); } //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(!_isExcludedBal[recipient] ) { require(balanceOf(recipient)<= _maxBalAmount, "Balance limit reached"); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tBurn ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); if(tBurn > 0) _burn(sender, tBurn); if(tLiquidity > 0 ) _takeLiquidity(sender, 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, uint256 tBurn ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); if(tBurn > 0) _burn(sender, tBurn); if(tLiquidity > 0 ) _takeLiquidity(sender, 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, uint256 tBurn ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); if(tBurn > 0) _burn(sender, tBurn); if(tLiquidity > 0 ) _takeLiquidity(sender, tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } }
list for Max Bal limits
mapping (address => bool) public _isExcludedBal;
42,542
[ 1, 1098, 364, 4238, 605, 287, 8181, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 261, 2867, 516, 1426, 13, 1071, 389, 291, 16461, 38, 287, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.17; library Defi { struct Position { bytes id; // encoded platform specific id for the position bytes currency; // encoded platform specific currency for the position uint256 amount; // total amount owed or supplied (with interest accrued) uint256 poolLiquidity; // amount of currency left in pool (on supply) uint256 colRatio; // ... (1e27 = 1) (where applicable) (on borrow) bytes interestRateData; // data required to compute the interest rate off-chain } struct PlatformResult { bytes32 id; Position[] borrowPositions; Position[] supplyPositions; } }
encoded platform specific currency for the position
bytes currency;
1,788,036
[ 1, 10787, 4072, 2923, 5462, 364, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1731, 5462, 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, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /* Library Imports */ import { AddressAliasHelper } from "../../standards/AddressAliasHelper.sol"; import { Lib_CrossDomainUtils } from "../../libraries/bridge/Lib_CrossDomainUtils.sol"; import { Lib_DefaultValues } from "../../libraries/constants/Lib_DefaultValues.sol"; import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; /* Interface Imports */ import { IL2CrossDomainMessenger } from "./IL2CrossDomainMessenger.sol"; import { iOVM_L2ToL1MessagePasser } from "../predeploys/iOVM_L2ToL1MessagePasser.sol"; /** * @title 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. * */ contract L2CrossDomainMessenger is IL2CrossDomainMessenger { /************* * Variables * *************/ mapping(bytes32 => bool) public relayedMessages; mapping(bytes32 => bool) public successfulMessages; mapping(bytes32 => bool) public sentMessages; uint256 public messageNonce; address internal xDomainMsgSender = Lib_DefaultValues.DEFAULT_XDOMAIN_SENDER; address public l1CrossDomainMessenger; /*************** * Constructor * ***************/ constructor(address _l1CrossDomainMessenger) { l1CrossDomainMessenger = _l1CrossDomainMessenger; } /******************** * Public Functions * ********************/ // slither-disable-next-line external-function function xDomainMessageSender() public view returns (address) { require( xDomainMsgSender != Lib_DefaultValues.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. */ // slither-disable-next-line external-function function sendMessage( address _target, bytes memory _message, uint32 _gasLimit ) public { bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata( _target, msg.sender, _message, messageNonce ); sentMessages[keccak256(xDomainCalldata)] = true; // Actually send the message. // slither-disable-next-line reentrancy-no-eth, reentrancy-events iOVM_L2ToL1MessagePasser(Lib_PredeployAddresses.L2_TO_L1_MESSAGE_PASSER).passMessageToL1( xDomainCalldata ); // Emit an event before we bump the nonce or the nonce will be off by one. // slither-disable-next-line reentrancy-events emit SentMessage(_target, msg.sender, _message, messageNonce, _gasLimit); // slither-disable-next-line reentrancy-no-eth messageNonce += 1; } /** * Relays a cross domain message to a contract. * @inheritdoc IL2CrossDomainMessenger */ // slither-disable-next-line external-function function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce ) public { // Since it is impossible to deploy a contract to an address on L2 which matches // the alias of the L1CrossDomainMessenger, this check can only pass when it is called in // the first call from of a deposit transaction. Thus reentrancy is prevented here. require( AddressAliasHelper.undoL1ToL2Alias(msg.sender) == l1CrossDomainMessenger, "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 == Lib_PredeployAddresses.L2_TO_L1_MESSAGE_PASSER) { // Write to the successfulMessages mapping and return immediately. successfulMessages[xDomainCalldataHash] = true; return; } xDomainMsgSender = _sender; // slither-disable-next-line reentrancy-no-eth, reentrancy-events, reentrancy-benign (bool success, ) = _target.call(_message); // slither-disable-next-line reentrancy-benign xDomainMsgSender = Lib_DefaultValues.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) { // slither-disable-next-line reentrancy-no-eth successfulMessages[xDomainCalldataHash] = true; // slither-disable-next-line reentrancy-events emit RelayedMessage(xDomainCalldataHash); } else { // slither-disable-next-line reentrancy-events 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)); // slither-disable-next-line reentrancy-benign relayedMessages[relayId] = true; } }
slither-disable-next-line reentrancy-no-eth, reentrancy-events, reentrancy-benign
(bool success, ) = _target.call(_message);
6,389,763
[ 1, 2069, 2927, 17, 8394, 17, 4285, 17, 1369, 283, 8230, 12514, 17, 2135, 17, 546, 16, 283, 8230, 12514, 17, 5989, 16, 283, 8230, 12514, 17, 19425, 724, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 261, 6430, 2216, 16, 262, 273, 389, 3299, 18, 1991, 24899, 2150, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xCf3b485bd11BCa74103D7D3534503bAD3fbdaC6d/sources/contracts/JBFundingCycleStore.sol
/ If the project does not have a funding cycle, return an empty struct. Get a reference to the configuration of the standby funding cycle. If it exists, return its funding cycle if it is approved. Resolve the funding cycle for the latest configured funding cycle. Resolve the funding cycle for the latest configured funding cycle. If the latest funding cycle starts in the future, it must start in the distant future since its not in standby. In this case base the queued cycles on the base cycle.
function queuedOf(uint256 _projectId) external view override returns (JBFundingCycle memory fundingCycle) { if (latestConfigurationOf[_projectId] == 0) return _getStructFor(0, 0); uint256 _standbyFundingCycleConfiguration = _standbyOf(_projectId); if (_standbyFundingCycleConfiguration > 0) { fundingCycle = _getStructFor(_projectId, _standbyFundingCycleConfiguration); if (_isApproved(_projectId, fundingCycle)) return fundingCycle; fundingCycle = _getStructFor(_projectId, fundingCycle.basedOn); fundingCycle = _getStructFor(_projectId, latestConfigurationOf[_projectId]); if (fundingCycle.start > block.timestamp) fundingCycle = _getStructFor(_projectId, fundingCycle.basedOn); } } The funding cycle that is currently active for the specified project. @dev If a current funding cycle of the project is not found, returns an empty funding cycle with all properties set to 0. @param _projectId The ID of the project to get the current funding cycle of. @return fundingCycle The project's current funding cycle.
17,049,512
[ 1, 19, 971, 326, 1984, 1552, 486, 1240, 279, 22058, 8589, 16, 327, 392, 1008, 1958, 18, 968, 279, 2114, 358, 326, 1664, 434, 326, 12842, 1637, 22058, 8589, 18, 971, 518, 1704, 16, 327, 2097, 22058, 8589, 309, 518, 353, 20412, 18, 9910, 326, 22058, 8589, 364, 326, 4891, 4351, 22058, 8589, 18, 9910, 326, 22058, 8589, 364, 326, 4891, 4351, 22058, 8589, 18, 971, 326, 4891, 22058, 8589, 2542, 316, 326, 3563, 16, 518, 1297, 787, 316, 326, 2411, 970, 3563, 3241, 2097, 486, 316, 12842, 1637, 18, 657, 333, 648, 1026, 326, 12234, 15139, 603, 326, 1026, 8589, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 12234, 951, 12, 11890, 5034, 389, 4406, 548, 13, 203, 565, 3903, 203, 565, 1476, 203, 565, 3849, 203, 565, 1135, 261, 8877, 42, 14351, 13279, 3778, 22058, 13279, 13, 203, 225, 288, 203, 565, 309, 261, 13550, 1750, 951, 63, 67, 4406, 548, 65, 422, 374, 13, 327, 389, 588, 3823, 1290, 12, 20, 16, 374, 1769, 203, 203, 565, 2254, 5034, 389, 10145, 1637, 42, 14351, 13279, 1750, 273, 389, 10145, 1637, 951, 24899, 4406, 548, 1769, 203, 203, 565, 309, 261, 67, 10145, 1637, 42, 14351, 13279, 1750, 405, 374, 13, 288, 203, 1377, 22058, 13279, 273, 389, 588, 3823, 1290, 24899, 4406, 548, 16, 389, 10145, 1637, 42, 14351, 13279, 1750, 1769, 203, 203, 1377, 309, 261, 67, 291, 31639, 24899, 4406, 548, 16, 22058, 13279, 3719, 327, 22058, 13279, 31, 203, 203, 1377, 22058, 13279, 273, 389, 588, 3823, 1290, 24899, 4406, 548, 16, 22058, 13279, 18, 12261, 1398, 1769, 203, 1377, 22058, 13279, 273, 389, 588, 3823, 1290, 24899, 4406, 548, 16, 4891, 1750, 951, 63, 67, 4406, 548, 19226, 203, 203, 1377, 309, 261, 74, 14351, 13279, 18, 1937, 405, 1203, 18, 5508, 13, 203, 3639, 22058, 13279, 273, 389, 588, 3823, 1290, 24899, 4406, 548, 16, 22058, 13279, 18, 12261, 1398, 1769, 203, 565, 289, 203, 203, 203, 203, 203, 203, 225, 289, 203, 203, 565, 1021, 22058, 8589, 716, 353, 4551, 2695, 364, 326, 1269, 1984, 18, 203, 203, 565, 632, 5206, 203, 565, 971, 279, 783, 22058, 8589, 434, 326, 1984, 353, 2 ]
// contracts/CollectionItem.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @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 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; } } contract Eterneum is Ownable { /** * @dev Contract Properties */ string private _name; // Token name string private _symbol; // Token symbol uint private _price; // Token Payable price uint256[] private _allTokens; // Array with all token ids, used for enumeration mapping (uint256 => address) private _owners; // Mapping from token ID to owner address mapping (uint256 => string) private _tokenCIDs; // Mapping from token ID to CID /** * @dev Initializes the contract properties by setting a `name`, a `symbol` and a price to the token collection. */ constructor (string memory name_, string memory symbol_, uint price_) { _name = name_; _symbol = symbol_; _price = price_; } /** * @dev Return contract properties */ function name() public view virtual returns (string memory) { return _name; } function symbol() public view virtual returns (string memory) { return _symbol; } function price() public view virtual returns (uint) { return _price; } /* * @dev Change price */ function changePrice(uint price_) public onlyOwner { _price = price_; } /** * @dev Initialize event and method for payable contract */ event Received(address, uint); receive() external payable { emit Received(msg.sender, msg.value); } /** * @dev Tranfert amount from the contract */ function withdraw(uint amount) public onlyOwner() { address payable owner_pay = payable(owner()); owner_pay.transfer(amount); } /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) public view virtual returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "Owner query for nonexistent token"); return owner; } /** * @dev Returns whether `tokenId` exists. * * Tokens start existing when they are minted (`mint`), */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev mint the tokenID */ function mint(address to, uint256 tokenId, string memory tokenCid) external payable { require(to != address(0), "Mint to the zero address"); require(!_exists(tokenId), "Token already minted"); require(bytes(tokenCid).length > 0, "CID is empty"); /* if not owner of contract, pay the price */ if (owner() != _msgSender()) { require(msg.value == _price, "Value sent not match contract Price"); address payable owner_pay = payable(owner()); owner_pay.transfer(msg.value); } _owners[tokenId] = to; _tokenCIDs[tokenId] = tokenCid; _allTokens.push(tokenId); emit Transfer(address(0), to, tokenId); } /** * @dev change the tokenCid - only contract Owner */ function cid(uint256 tokenId, string memory tokenCid) public onlyOwner { require(_exists(tokenId), "Token not already minted"); require(bytes(tokenCid).length > 0, "CID is empty"); _tokenCIDs[tokenId] = tokenCid; } /** * @dev Total number of tokens. */ function totalSupply() public view virtual returns (uint256) { return _allTokens.length; } /** * @dev Return the tokenID associated with the index. */ function tokenByIndex(uint256 index) public view virtual returns (uint256) { require(index < totalSupply(), "Global index out of bounds"); return _allTokens[index]; } /** * @dev Return the CID associated with the tokenID. */ function tokenCID(uint256 tokenId) public view virtual returns (string memory) { require(_exists(tokenId), "CID query for nonexistent token"); return _tokenCIDs[tokenId]; } }
* @dev Tranfert amount from the contract/
function withdraw(uint amount) public onlyOwner() { address payable owner_pay = payable(owner()); owner_pay.transfer(amount); }
10,094,446
[ 1, 17730, 586, 88, 3844, 628, 326, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 11890, 3844, 13, 1071, 1338, 5541, 1435, 288, 203, 3639, 1758, 8843, 429, 3410, 67, 10239, 273, 8843, 429, 12, 8443, 10663, 203, 3639, 3410, 67, 10239, 18, 13866, 12, 8949, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "./token/ERC20/IERC20.sol"; /** * Atomic Swap with Escrow account * * Steps to use Escrow account using executeOrder flow: 1. party1 registers the order 2. party1 creates allowance for Escrow 3. party2 creates allowance for Escrow 4. party2 call executeOrder * * Steps to use onTokenTransfer 1. party1 or party 2 registers an order 2. party1 transfers tokens to Escrow assuming a token supports callback 3. party2 transfers tokens to Escrow assumint a token supports callback */ contract Escrow { mapping (uint256 => Order) orders; struct Order { address party1; IERC20 coin1; uint256 amount1; address party2; IERC20 coin2; uint256 amount2; // this is used by onTokenTransferVersion bool party1Done; bool party2Done; } uint256 private nextOrder = 0; function registerOrder(address recipient, IERC20 coin1, uint256 amount1, IERC20 coin2, uint256 amount2) public returns(uint256) { nextOrder++; orders[nextOrder] = Order(msg.sender, coin1, amount1, recipient, coin2, amount2, false, false); } // onTokenTransfer is a callback by token transfer function // NOTE: unfortunately this function will never be executed as a callback on ERC20 tokens // because of limitaitons of ERC20. function onTokenTransfer(address from, uint256 amount, bytes calldata data) external { uint256 orderID = sliceUint(data, 0); Order storage o = orders[orderID]; if (o.party1 == from ) { require(o.amount1 == amount); if (o.party2Done) { o.coin1.transfer(o.party2, o.amount1); o.coin2.transfer(o.party1, o.amount2); delete orders[orderID]; } else { o.party1Done = true; } } else if (o.party2 == from) { // TODO .... } else { revert("Wrong orderID"); } } // executeOrder is a funciton to work around the ERC20 limitations and execute order based on allowances. // This funcion succeeds only if Escrow has active allowances on coin1 and coin2 repectively for party1 and party2. function executeOrder(uint256 orderID, IERC20 coin1, uint256 amount1, IERC20 coin2, uint256 amount2) public { Order storage o = orders[orderID]; // TODO: verify o paremeters (o.coin1 == coin1 ....) require(coin1.transferFrom(o.party1, o.party2, amount1)); require(coin2.transferFrom(o.party2, o.party1, amount2)); delete orders[orderID]; } // extracts an uint from bytes data function sliceUint(bytes memory data, uint start) internal pure returns (uint) { require(data.length >= start + 32, "slicing out of range"); uint x; assembly { x := mload(add(data, add(0x20, start))) } return x; } }
this is used by onTokenTransferVersion
struct Order { address party1; IERC20 coin1; uint256 amount1; address party2; IERC20 coin2; uint256 amount2; bool party1Done; bool party2Done; } uint256 private nextOrder = 0;
5,490,222
[ 1, 2211, 353, 1399, 635, 603, 1345, 5912, 1444, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1958, 4347, 288, 203, 3639, 1758, 18285, 21, 31, 203, 3639, 467, 654, 39, 3462, 13170, 21, 31, 203, 3639, 2254, 5034, 3844, 21, 31, 203, 3639, 1758, 18285, 22, 31, 203, 3639, 467, 654, 39, 3462, 13170, 22, 31, 203, 3639, 2254, 5034, 3844, 22, 31, 203, 203, 3639, 1426, 18285, 21, 7387, 31, 203, 3639, 1426, 18285, 22, 7387, 31, 203, 565, 289, 203, 565, 2254, 5034, 3238, 1024, 2448, 273, 374, 31, 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 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8; import "@openzeppelin/contracts/access/Ownable.sol"; import "./interfaces/IFeesCalculator.sol"; contract FeesCalculator is IFeesCalculator, Ownable { uint256 private constant PRECISION_DECIMALS = 1e10; uint256 private constant FUNDING_FEE_MIN_RATE = 2000; uint256 private constant FUNDING_FEE_MAX_RATE = 100000; uint256 private constant FUNDING_FEE_BASE_PERIOD = 1 days; uint256 private constant MAX_FUNDING_FEE_PERCENTAGE = 1000000; uint16 private constant CVI_DECIMALS = 100; uint16 private constant MAX_FUNDING_FEE_CVI_THRESHOLD = 55; uint16 private constant MIN_FUDNING_FEE_CVI_THRESHOLD = 150; uint16 private constant FUNDING_FEE_DIVISION_FACTOR = 5; uint16 private constant MAX_PERCENTAGE = 10000; uint16 private constant COLATERAL_VALUES_NUM = 101; // From 0.00 to 1.00 inclusive uint16 public maxCVIValue; uint16 public override depositFeePercent = 0; uint16 public override withdrawFeePercent = 0; uint16 public override openPositionFeePercent = 15; uint16 public override openPositionLPFeePercent = 15; uint16 public override closePositionLPFeePercent = 0; uint16 public buyingPremiumFeeMaxPercent = 1000; uint16 public closingPremiumFeeMaxPercent = 1000; uint16 public override closePositionFeePercent = 30; uint16 public buyingPremiumThreshold = 6500; // 1.0 is MAX_PERCENTAGE = 10000 uint16 public closePositionMaxFeePercent = 300; uint16 public maxTurbulenceFeePercentToTrim = 100; uint16 public turbulenceStepPercent = 1000; uint16 public override turbulenceIndicatorPercent = 0; uint32 public adjustedVolumeTimestamp; uint16 public volumeTimeWindow = 2 hours; uint16 public volumeFeeTimeWindow = 1 hours; uint16 public maxVolumeFeeDeltaCollateral = 400; // 100% is MAX_PERCENTAGE = 10000 uint16 public midVolumeFee = 0; // 100% is MAX_PERCENTAGE = 10000 uint16 public maxVolumeFee = 130; // 100% is MAX_PERCENTAGE = 10000 uint32 public closeAdjustedVolumeTimestamp; uint16 public closeVolumeTimeWindow = 2 hours; uint16 public closeVolumeFeeTimeWindow = 1 hours; uint16 public closeMaxVolumeFeeDeltaCollateral = 400; // 100% is MAX_PERCENTAGE = 10000 uint16 public closeMidVolumeFee = 0; // 100% is MAX_PERCENTAGE = 10000 uint16 public closeMaxVolumeFee = 80; // 100% is MAX_PERCENTAGE = 10000 uint256 public oracleHeartbeatPeriod = 55 minutes; uint256 public closePositionFeeDecayPeriod = 24 hours; uint256 public fundingFeeConstantRate = 3000; uint16 public turbulenceDeviationThresholdPercent = 7000; // 1.0 is MAX_PERCENTAGE = 10000 uint16 public turbulenceDeviationPercentage = 500; // 1.0 is MAX_PERCENTAGE = 10000 uint16[] public collateralToBuyingPremiumMapping = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 6, 8, 9, 11, 14, 16, 20, 24, 29, 35, 42, 52, 63, 77, 94, 115, 140, 172, 212, 261, 323, 399, 495, 615, 765, 953, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000]; ICVIOracle public cviOracle; address public stateUpdator; modifier onlyStateUpdator { require(msg.sender == stateUpdator, "Not allowed"); _; } constructor(ICVIOracle _cviOracle, uint16 _maxCVIValue) { maxCVIValue = _maxCVIValue; cviOracle = _cviOracle; } function updateTurbulenceIndicatorPercent(uint256 _totalTime, uint256 _newRounds, uint16 _lastCVIValue, uint16 _currCVIValue) external override onlyStateUpdator { uint16 updatedTurbulenceIndicatorPercent = calculateTurbulenceIndicatorPercent(_totalTime, _newRounds, _lastCVIValue, _currCVIValue); if (updatedTurbulenceIndicatorPercent != turbulenceIndicatorPercent) { turbulenceIndicatorPercent = updatedTurbulenceIndicatorPercent; } } function updateAdjustedTimestamp(uint256 _collateralRatio, uint256 _lastCollateralRatio) external override onlyStateUpdator { uint256 deltaCollateral = _collateralRatio - _lastCollateralRatio; // Note: must be greater than 0 adjustedVolumeTimestamp = getAdjustedTimestamp(adjustedVolumeTimestamp, deltaCollateral, volumeTimeWindow, maxVolumeFeeDeltaCollateral); } function updateCloseAdjustedTimestamp(uint256 _collateralRatio, uint256 _lastCollateralRatio) external override onlyStateUpdator { uint256 deltaCollateral = _lastCollateralRatio - _collateralRatio; // Note: must be greater than 0 closeAdjustedVolumeTimestamp = getAdjustedTimestamp(closeAdjustedVolumeTimestamp, deltaCollateral, closeVolumeTimeWindow, closeMaxVolumeFeeDeltaCollateral); } function setOracle(ICVIOracle _cviOracle) external override onlyOwner { cviOracle = _cviOracle; } function setStateUpdator(address _newUpdator) external override onlyOwner { stateUpdator = _newUpdator; } function setDepositFee(uint16 _newDepositFeePercentage) external override onlyOwner { require(_newDepositFeePercentage < MAX_PERCENTAGE, "Fee exceeds maximum"); depositFeePercent = _newDepositFeePercentage; } function setWithdrawFee(uint16 _newWithdrawFeePercentage) external override onlyOwner { require(_newWithdrawFeePercentage < MAX_PERCENTAGE, "Fee exceeds maximum"); withdrawFeePercent = _newWithdrawFeePercentage; } function setOpenPositionFee(uint16 _newOpenPositionFeePercentage) external override onlyOwner { require(_newOpenPositionFeePercentage < MAX_PERCENTAGE, "Fee exceeds maximum"); openPositionFeePercent = _newOpenPositionFeePercentage; } function setClosePositionFee(uint16 _newClosePositionFeePercentage) external override onlyOwner { require(_newClosePositionFeePercentage < MAX_PERCENTAGE, "Fee exceeds maximum"); require(_newClosePositionFeePercentage <= closePositionMaxFeePercent, "Min fee above max fee"); closePositionFeePercent = _newClosePositionFeePercentage; } function setOpenPositionLPFee(uint16 _newOpenPositionLPFeePercent) external override onlyOwner { require(_newOpenPositionLPFeePercent < MAX_PERCENTAGE, "Fee exceeds maximum"); openPositionLPFeePercent = _newOpenPositionLPFeePercent; } function setClosePositionLPFee(uint16 _newClosePositionLPFeePercent) external override onlyOwner { require(_newClosePositionLPFeePercent < MAX_PERCENTAGE, "Fee exceeds maximum"); closePositionLPFeePercent = _newClosePositionLPFeePercent; } function setClosePositionMaxFee(uint16 _newClosePositionMaxFeePercentage) external override onlyOwner { require(_newClosePositionMaxFeePercentage < MAX_PERCENTAGE, "Fee exceeds maximum"); require(_newClosePositionMaxFeePercentage >= closePositionFeePercent, "Max fee below min fee"); closePositionMaxFeePercent = _newClosePositionMaxFeePercentage; } function setClosePositionFeeDecay(uint256 _newClosePositionFeeDecayPeriod) external override onlyOwner { require(_newClosePositionFeeDecayPeriod > 0, "Period must be positive"); closePositionFeeDecayPeriod = _newClosePositionFeeDecayPeriod; } function setOracleHeartbeatPeriod(uint256 _newOracleHeartbeatPeriod) external override onlyOwner { require(_newOracleHeartbeatPeriod > 0, "Heartbeat must be positive"); oracleHeartbeatPeriod = _newOracleHeartbeatPeriod; } function setBuyingPremiumFeeMax(uint16 _newBuyingPremiumFeeMaxPercentage) external override onlyOwner { require(_newBuyingPremiumFeeMaxPercentage < MAX_PERCENTAGE, "Fee exceeds maximum"); buyingPremiumFeeMaxPercent = _newBuyingPremiumFeeMaxPercentage; } function setBuyingPremiumThreshold(uint16 _newBuyingPremiumThreshold) external override onlyOwner { require(_newBuyingPremiumThreshold < MAX_PERCENTAGE, "Threshold exceeds maximum"); buyingPremiumThreshold = _newBuyingPremiumThreshold; } function setClosingPremiumFeeMax(uint16 _newClosingPremiumFeeMaxPercentage) external override onlyOwner { require(_newClosingPremiumFeeMaxPercentage < MAX_PERCENTAGE, "Fee exceeds maximum"); closingPremiumFeeMaxPercent = _newClosingPremiumFeeMaxPercentage; } function setCollateralToBuyingPremiumMapping(uint16[] calldata _newCollateralToBuyingPremiumMapping) external override onlyOwner { require(_newCollateralToBuyingPremiumMapping.length == COLATERAL_VALUES_NUM, "Bad mapping size"); collateralToBuyingPremiumMapping = _newCollateralToBuyingPremiumMapping; } function setFundingFeeConstantRate(uint16 _newfundingFeeConstantRate) external override onlyOwner { require(_newfundingFeeConstantRate < FUNDING_FEE_MAX_RATE, "Fee exceeds maximum"); fundingFeeConstantRate = _newfundingFeeConstantRate; } function setTurbulenceStep(uint16 _newTurbulenceStepPercentage) external override onlyOwner { require(_newTurbulenceStepPercentage < MAX_PERCENTAGE, "Step exceeds maximum"); turbulenceStepPercent = _newTurbulenceStepPercentage; } function setMaxTurbulenceFeePercentToTrim(uint16 _newMaxTurbulenceFeePercentToTrim) external override onlyOwner { require(_newMaxTurbulenceFeePercentToTrim < MAX_PERCENTAGE, "Fee exceeds maximum"); maxTurbulenceFeePercentToTrim = _newMaxTurbulenceFeePercentToTrim; } function setTurbulenceDeviationThresholdPercent(uint16 _newTurbulenceDeviationThresholdPercent) external override onlyOwner { require(_newTurbulenceDeviationThresholdPercent < MAX_PERCENTAGE, "Threshold exceeds maximum"); turbulenceDeviationThresholdPercent = _newTurbulenceDeviationThresholdPercent; } function setTurbulenceDeviationPercent(uint16 _newTurbulenceDeviationPercentage) external override onlyOwner { require(_newTurbulenceDeviationPercentage < MAX_PERCENTAGE, "Deviation exceeds maximum"); turbulenceDeviationPercentage = _newTurbulenceDeviationPercentage; } function setVolumeTimeWindow(uint16 _newVolumeTimeWindow) external override onlyOwner { volumeTimeWindow = _newVolumeTimeWindow; } function setVolumeFeeTimeWindow(uint16 _newVolumeFeeTimeWindow) external override onlyOwner { volumeFeeTimeWindow = _newVolumeFeeTimeWindow; } function setMaxVolumeFeeDeltaCollateral(uint16 _newMaxVolumeFeeDeltaCollateral) external override onlyOwner { maxVolumeFeeDeltaCollateral = _newMaxVolumeFeeDeltaCollateral; } function setMidVolumeFee(uint16 _newMidVolumeFee) external override onlyOwner { midVolumeFee = _newMidVolumeFee; } function setMaxVolumeFee(uint16 _newMaxVolumeFee) external override onlyOwner { maxVolumeFee = _newMaxVolumeFee; } function setCloseVolumeTimeWindow(uint16 _newCloseVolumeTimeWindow) external override onlyOwner { closeVolumeTimeWindow = _newCloseVolumeTimeWindow; } function setCloseVolumeFeeTimeWindow(uint16 _newCloseVolumeFeeTimeWindow) external override onlyOwner { closeVolumeFeeTimeWindow = _newCloseVolumeFeeTimeWindow; } function setCloseMaxVolumeFeeDeltaCollateral(uint16 _newCloseMaxVolumeFeeDeltaCollateral) external override onlyOwner { closeMaxVolumeFeeDeltaCollateral = _newCloseMaxVolumeFeeDeltaCollateral; } function setCloseMidVolumeFee(uint16 _newCloseMidVolumeFee) external override onlyOwner { closeMidVolumeFee = _newCloseMidVolumeFee; } function setCloseMaxVolumeFee(uint16 _newCloseMaxVolumeFee) external override onlyOwner { closeMaxVolumeFee = _newCloseMaxVolumeFee; } function calculateTurbulenceIndicatorPercent(uint256 totalTime, uint256 newRounds, uint16 _lastCVIValue, uint16 _currCVIValue) public view override returns (uint16) { uint16 updatedTurbulenceIndicatorPercent = turbulenceIndicatorPercent; uint256 CVIDeltaPercent = uint256(_currCVIValue > _lastCVIValue ? (_currCVIValue - _lastCVIValue) : (_lastCVIValue - _currCVIValue)) * MAX_PERCENTAGE / _lastCVIValue; uint256 maxAllowedTurbulenceTimes = CVIDeltaPercent * MAX_PERCENTAGE / (uint256(turbulenceDeviationThresholdPercent) * turbulenceDeviationPercentage); uint256 decayTimes = 0; uint256 turbulenceTimes = 0; uint256 totalHeartbeats = totalTime / oracleHeartbeatPeriod; if (newRounds > totalHeartbeats) { turbulenceTimes = newRounds - totalHeartbeats; turbulenceTimes = turbulenceTimes > maxAllowedTurbulenceTimes ? maxAllowedTurbulenceTimes : turbulenceTimes; decayTimes = newRounds - turbulenceTimes; } else { decayTimes = newRounds; } for (uint256 i = 0; i < decayTimes; i++) { updatedTurbulenceIndicatorPercent = updatedTurbulenceIndicatorPercent / 2; } if (updatedTurbulenceIndicatorPercent < maxTurbulenceFeePercentToTrim) { updatedTurbulenceIndicatorPercent = 0; } for (uint256 i = 0; i < turbulenceTimes; i++) { updatedTurbulenceIndicatorPercent = updatedTurbulenceIndicatorPercent + uint16(uint256(buyingPremiumFeeMaxPercent) * turbulenceStepPercent / MAX_PERCENTAGE); } if (updatedTurbulenceIndicatorPercent > buyingPremiumFeeMaxPercent) { updatedTurbulenceIndicatorPercent = buyingPremiumFeeMaxPercent; } return updatedTurbulenceIndicatorPercent; } function calculateBuyingPremiumFee(uint168 _tokenAmount, uint8 _leverage, uint256 _collateralRatio, uint256 _lastCollateralRatio, bool _withVolumeFee) external view override returns (uint168 buyingPremiumFee, uint16 combinedPremiumFeePercentage) { (buyingPremiumFee, combinedPremiumFeePercentage) = _calculateBuyingPremiumFeeWithParameters(_tokenAmount, _leverage, _collateralRatio, _lastCollateralRatio, _withVolumeFee, turbulenceIndicatorPercent, adjustedVolumeTimestamp); } function calculateBuyingPremiumFeeWithAddendum(uint168 _tokenAmount, uint8 _leverage, uint256 _collateralRatio, uint256 _lastCollateralRatio, bool _withVolumeFee, uint16 _turbulenceIndicatorPercent) external view override returns (uint168 buyingPremiumFee, uint16 combinedPremiumFeePercentage) { (buyingPremiumFee, combinedPremiumFeePercentage) = _calculateBuyingPremiumFeeWithParameters(_tokenAmount, _leverage, _collateralRatio, _lastCollateralRatio, _withVolumeFee, _turbulenceIndicatorPercent, getAdjustedTimestamp(adjustedVolumeTimestamp, _collateralRatio - _lastCollateralRatio, volumeTimeWindow, maxVolumeFeeDeltaCollateral)); } function calculateClosingPremiumFee(uint256 /*_tokenAmount*/, uint256 /*_collateralRatio*/, uint256 /*_lastCollateralRatio*/, bool _withVolumeFee) external view override returns (uint16 combinedPremiumFeePercentage) { return _calculateClosingPremiumFee(_withVolumeFee, closeAdjustedVolumeTimestamp); } function calculateClosingPremiumFeeWithAddendum(uint256 _collateralRatio, uint256 _lastCollateralRatio, bool _withVolumeFee) external view override returns (uint16 combinedPremiumFeePercentage) { return _calculateClosingPremiumFee(_withVolumeFee, getAdjustedTimestamp(closeAdjustedVolumeTimestamp, _lastCollateralRatio - _collateralRatio, closeVolumeTimeWindow, closeMaxVolumeFeeDeltaCollateral)); } function calculateSingleUnitFundingFee(CVIValue[] memory _cviValues) public override view returns (uint256 fundingFee) { for (uint8 i = 0; i < _cviValues.length; i++) { fundingFee = fundingFee + calculateSingleUnitPeriodFundingFee(_cviValues[i]); } } function updateSnapshots(uint256 _latestTimestamp, uint256 _blockTimestampSnapshot, uint256 _latestTimestampSnapshot, uint80 latestOracleRoundId) external override view returns (SnapshotUpdate memory snapshotUpdate) { (uint16 cviValue, uint80 periodEndRoundId, uint256 periodEndTimestamp) = cviOracle.getCVILatestRoundData(); snapshotUpdate.cviValue = cviValue; snapshotUpdate.cviValueTimestamp = periodEndTimestamp; snapshotUpdate.latestSnapshot = _blockTimestampSnapshot; if (snapshotUpdate.latestSnapshot != 0) { // Block was already updated snapshotUpdate.singleUnitFundingFee = 0; return snapshotUpdate; } if (_latestTimestamp == 0) { // For first recorded block snapshotUpdate.latestSnapshot = PRECISION_DECIMALS; snapshotUpdate.updatedSnapshot = true; snapshotUpdate.newLatestRoundId = periodEndRoundId; snapshotUpdate.updatedLatestRoundId = true; snapshotUpdate.updatedLatestTimestamp = true; snapshotUpdate.singleUnitFundingFee = 0; return snapshotUpdate; } uint80 periodStartRoundId = latestOracleRoundId; require(periodEndRoundId >= periodStartRoundId, "Bad round id"); snapshotUpdate.totalRounds = periodEndRoundId - periodStartRoundId; uint256 cviValuesNum = snapshotUpdate.totalRounds > 0 ? 2 : 1; IFeesCalculator.CVIValue[] memory cviValues = new IFeesCalculator.CVIValue[](cviValuesNum); if (snapshotUpdate.totalRounds > 0) { (uint16 periodStartCVIValue, uint256 periodStartTimestamp) = cviOracle.getCVIRoundData(periodStartRoundId); cviValues[0] = IFeesCalculator.CVIValue(periodEndTimestamp - _latestTimestamp, periodStartCVIValue); cviValues[1] = IFeesCalculator.CVIValue(block.timestamp - periodEndTimestamp, cviValue); snapshotUpdate.newLatestRoundId = periodEndRoundId; snapshotUpdate.updatedLatestRoundId = true; snapshotUpdate.totalTime = periodEndTimestamp - periodStartTimestamp; snapshotUpdate.updatedTurbulenceData = true; } else { cviValues[0] = IFeesCalculator.CVIValue(block.timestamp - _latestTimestamp, cviValue); } snapshotUpdate.singleUnitFundingFee = calculateSingleUnitFundingFee(cviValues); snapshotUpdate.latestSnapshot = _latestTimestampSnapshot + snapshotUpdate.singleUnitFundingFee; snapshotUpdate.updatedSnapshot = true; snapshotUpdate.updatedLatestTimestamp = true; } function calculateClosePositionFeePercent(uint256 _creationTimestamp, bool _isNoLockPositionAddress) external view override returns (uint16) { if (block.timestamp - _creationTimestamp >= closePositionFeeDecayPeriod || _isNoLockPositionAddress) { return closePositionFeePercent; } uint16 decay = uint16((closePositionMaxFeePercent - closePositionFeePercent) * (block.timestamp - _creationTimestamp) / closePositionFeeDecayPeriod); return closePositionMaxFeePercent - decay; } function calculateWithdrawFeePercent(uint256) external view override returns (uint16) { return withdrawFeePercent; } function openPositionFees() external view override returns (uint16 openPositionFeePercentResult, uint16 buyingPremiumFeeMaxPercentResult) { openPositionFeePercentResult = openPositionFeePercent; buyingPremiumFeeMaxPercentResult = buyingPremiumFeeMaxPercent; } function calculateSingleUnitPeriodFundingFee(CVIValue memory _cviValue) private view returns (uint256 fundingFee) { if (_cviValue.cviValue == 0 || _cviValue.period == 0) { return 0; } uint256 fundingFeeRatePercents = FUNDING_FEE_MAX_RATE; uint16 integerCVIValue = _cviValue.cviValue / CVI_DECIMALS; if (integerCVIValue > MAX_FUNDING_FEE_CVI_THRESHOLD) { if (integerCVIValue >= MIN_FUDNING_FEE_CVI_THRESHOLD) { fundingFeeRatePercents = FUNDING_FEE_MIN_RATE; } else { // Defining as memory to keep function pure and save storage space + reads uint24[5] memory fundingFeeCoefficients = [100000, 114869, 131950, 151571, 174110]; uint256 exponent = (integerCVIValue - MAX_FUNDING_FEE_CVI_THRESHOLD) / FUNDING_FEE_DIVISION_FACTOR; uint256 coefficientIndex = (integerCVIValue - MAX_FUNDING_FEE_CVI_THRESHOLD) % FUNDING_FEE_DIVISION_FACTOR; // Note: overflow is not possible as the exponent can only get larger, and other parts are constants // However, 2 ** exponent can overflow if cvi value is wrong require(exponent < 256, "exponent overflow"); fundingFeeRatePercents = PRECISION_DECIMALS / (2 ** exponent) / fundingFeeCoefficients[coefficientIndex] + fundingFeeConstantRate; if (fundingFeeRatePercents > FUNDING_FEE_MAX_RATE) { fundingFeeRatePercents = FUNDING_FEE_MAX_RATE; } } } return PRECISION_DECIMALS * _cviValue.cviValue * fundingFeeRatePercents * _cviValue.period / FUNDING_FEE_BASE_PERIOD / maxCVIValue / MAX_FUNDING_FEE_PERCENTAGE; } function _calculateBuyingPremiumFeeWithParameters(uint168 _tokenAmount, uint8 _leverage, uint256 _collateralRatio, uint256 _lastCollateralRatio, bool _withVolumeFee, uint16 _turbulenceIndicatorPercent, uint32 _adjustedVolumeTimestamp) private view returns (uint168 buyingPremiumFee, uint16 combinedPremiumFeePercentage) { require(_collateralRatio >= _lastCollateralRatio); uint16 buyingPremiumFeePercentage = 0; if (_collateralRatio >= PRECISION_DECIMALS) { buyingPremiumFeePercentage = calculateRelativePercentage(buyingPremiumFeeMaxPercent, _collateralRatio, _lastCollateralRatio); } else { if (_collateralRatio >= buyingPremiumThreshold * PRECISION_DECIMALS / MAX_PERCENTAGE) { buyingPremiumFeePercentage = calculateRelativePercentage(collateralToBuyingPremiumMapping[_collateralRatio * 10**2 / PRECISION_DECIMALS], _collateralRatio, _lastCollateralRatio); } } uint16 volumeFeePercentage = calculateVolumeFee(_withVolumeFee, _adjustedVolumeTimestamp, volumeTimeWindow, volumeFeeTimeWindow, midVolumeFee, maxVolumeFee); combinedPremiumFeePercentage = openPositionLPFeePercent + _turbulenceIndicatorPercent + buyingPremiumFeePercentage + volumeFeePercentage; if (combinedPremiumFeePercentage > buyingPremiumFeeMaxPercent) { combinedPremiumFeePercentage = buyingPremiumFeeMaxPercent; } uint256 __buyingPremiumFee = uint256(_tokenAmount) * _leverage * combinedPremiumFeePercentage / MAX_PERCENTAGE; buyingPremiumFee = uint168(__buyingPremiumFee); require(__buyingPremiumFee == buyingPremiumFee, "Too much tokens"); } function _calculateClosingPremiumFee(bool _withVolumeFee, uint32 _adjustedCloseVolumeTimestamp) private view returns (uint16 combinedPremiumFeePercentage) { uint16 closingPremiumFeePercentage = calculateVolumeFee(_withVolumeFee, _adjustedCloseVolumeTimestamp, closeVolumeTimeWindow, closeVolumeFeeTimeWindow, closeMidVolumeFee, closeMaxVolumeFee); combinedPremiumFeePercentage = closePositionLPFeePercent + closingPremiumFeePercentage; if (combinedPremiumFeePercentage > closingPremiumFeeMaxPercent) { combinedPremiumFeePercentage = closingPremiumFeeMaxPercent; } } function calculateVolumeFee(bool _withVolumeFee, uint32 _adjustedVolumeTimestamp, uint16 _volumeTimeWindow, uint16 _volumeFeeTimeWindow, uint16 _midVolumeFee, uint16 _maxVolumeFee) private view returns (uint16 volumeFeePercentage) { if (_withVolumeFee) { if (_adjustedVolumeTimestamp < block.timestamp - _volumeFeeTimeWindow) { volumeFeePercentage = uint16(uint256(_midVolumeFee) * (_adjustedVolumeTimestamp - (block.timestamp - _volumeTimeWindow)) / (_volumeTimeWindow - _volumeFeeTimeWindow)); } else { volumeFeePercentage = uint16(uint256(_midVolumeFee) + (_maxVolumeFee - _midVolumeFee) * (_adjustedVolumeTimestamp - (block.timestamp - _volumeFeeTimeWindow)) / _volumeFeeTimeWindow); } } } function calculateRelativePercentage(uint16 _percentage, uint256 _collateralRatio, uint256 _lastCollateralRatio) private view returns (uint16) { if (_lastCollateralRatio >= buyingPremiumThreshold * PRECISION_DECIMALS / MAX_PERCENTAGE || _collateralRatio == _lastCollateralRatio) { return _percentage; } return uint16(_percentage * (_collateralRatio - buyingPremiumThreshold * PRECISION_DECIMALS / MAX_PERCENTAGE) / (_collateralRatio - _lastCollateralRatio)); } function getAdjustedTimestamp(uint32 _currAdjustedTimetamp, uint256 _deltaCollateral, uint16 _volumeTimeWindow, uint16 _maxVolumeFeeDeltaCollateral) private view returns (uint32 newAdjustedTimestamp) { newAdjustedTimestamp = _currAdjustedTimetamp; if (newAdjustedTimestamp < block.timestamp - _volumeTimeWindow) { newAdjustedTimestamp = uint32(block.timestamp) - _volumeTimeWindow; } newAdjustedTimestamp = uint32(newAdjustedTimestamp + uint256(_volumeTimeWindow) * _deltaCollateral / (_maxVolumeFeeDeltaCollateral * PRECISION_DECIMALS / MAX_PERCENTAGE)); if (newAdjustedTimestamp > block.timestamp) { newAdjustedTimestamp = uint32(block.timestamp); } } } // 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: GPL-3.0 pragma solidity ^0.8; import "./ICVIOracle.sol"; interface IFeesCalculator { struct CVIValue { uint256 period; uint16 cviValue; } struct SnapshotUpdate { uint256 latestSnapshot; uint256 singleUnitFundingFee; uint256 totalTime; uint256 totalRounds; uint256 cviValueTimestamp; uint80 newLatestRoundId; uint16 cviValue; bool updatedSnapshot; bool updatedLatestRoundId; bool updatedLatestTimestamp; bool updatedTurbulenceData; } function updateTurbulenceIndicatorPercent(uint256 totalTime, uint256 newRounds, uint16 lastCVIValue, uint16 currCVIValue) external; function updateAdjustedTimestamp(uint256 collateralRatio, uint256 lastCollateralRatio) external; function updateCloseAdjustedTimestamp(uint256 collateralRatio, uint256 lastCollateralRatio) external; function setOracle(ICVIOracle cviOracle) external; function setStateUpdator(address newUpdator) external; function setDepositFee(uint16 newDepositFeePercentage) external; function setWithdrawFee(uint16 newWithdrawFeePercentage) external; function setOpenPositionFee(uint16 newOpenPositionFeePercentage) external; function setOpenPositionLPFee(uint16 newOpenPositionLPFeePercent) external; function setClosePositionLPFee(uint16 newClosePositionLPFeePercent) external; function setClosePositionFee(uint16 newClosePositionFeePercentage) external; function setClosePositionMaxFee(uint16 newClosePositionMaxFeePercentage) external; function setClosePositionFeeDecay(uint256 newClosePositionFeeDecayPeriod) external; function setOracleHeartbeatPeriod(uint256 newOracleHeartbeatPeriod) external; function setBuyingPremiumFeeMax(uint16 newBuyingPremiumFeeMaxPercentage) external; function setBuyingPremiumThreshold(uint16 newBuyingPremiumThreshold) external; function setClosingPremiumFeeMax(uint16 newClosingPremiumFeeMaxPercentage) external; function setCollateralToBuyingPremiumMapping(uint16[] calldata newCollateralToBuyingPremiumMapping) external; function setFundingFeeConstantRate(uint16 newfundingFeeConstantRate) external; function setTurbulenceStep(uint16 newTurbulenceStepPercentage) external; function setMaxTurbulenceFeePercentToTrim(uint16 newMaxTurbulenceFeePercentToTrim) external; function setTurbulenceDeviationThresholdPercent(uint16 newTurbulenceDeviationThresholdPercent) external; function setTurbulenceDeviationPercent(uint16 newTurbulenceDeviationPercentage) external; function setVolumeTimeWindow(uint16 newVolumeTimeWindow) external; function setVolumeFeeTimeWindow(uint16 newVolumeFeeTimeWindow) external; function setMaxVolumeFeeDeltaCollateral(uint16 newMaxVolumeFeeDeltaCollateral) external; function setMidVolumeFee(uint16 newMidVolumeFee) external; function setMaxVolumeFee(uint16 newMaxVolumeFee) external; function setCloseVolumeTimeWindow(uint16 newCloseVolumeTimeWindow) external; function setCloseVolumeFeeTimeWindow(uint16 newCloseVolumeFeeTimeWindow) external; function setCloseMaxVolumeFeeDeltaCollateral(uint16 newCloseMaxVolumeFeeDeltaCollateral) external; function setCloseMidVolumeFee(uint16 newCloseMidVolumeFee) external; function setCloseMaxVolumeFee(uint16 newCloseMaxVolumeFee) external; function calculateTurbulenceIndicatorPercent(uint256 totalTime, uint256 newRounds, uint16 _lastCVIValue, uint16 _currCVIValue) external view returns (uint16); function calculateBuyingPremiumFee(uint168 tokenAmount, uint8 leverage, uint256 collateralRatio, uint256 lastCollateralRatio, bool withVolumeFee) external view returns (uint168 buyingPremiumFee, uint16 combinedPremiumFeePercentage); function calculateBuyingPremiumFeeWithAddendum(uint168 tokenAmount, uint8 leverage, uint256 collateralRatio, uint256 lastCollateralRatio, bool withVolumeFee, uint16 _turbulenceIndicatorPercent) external view returns (uint168 buyingPremiumFee, uint16 combinedPremiumFeePercentage); function calculateClosingPremiumFee(uint256 tokenAmount, uint256 collateralRatio, uint256 lastCollateralRatio, bool withVolumeFee) external view returns (uint16 combinedPremiumFeePercentage); function calculateClosingPremiumFeeWithAddendum(uint256 collateralRatio, uint256 lastCollateralRatio, bool withVolumeFee) external view returns (uint16 combinedPremiumFeePercentage); function calculateSingleUnitFundingFee(CVIValue[] memory cviValues) external view returns (uint256 fundingFee); function updateSnapshots(uint256 latestTimestamp, uint256 blockTimestampSnapshot, uint256 latestTimestampSnapshot, uint80 latestOracleRoundId) external view returns (SnapshotUpdate memory snapshotUpdate); function calculateClosePositionFeePercent(uint256 creationTimestamp, bool isNoLockPositionAddress) external view returns (uint16); function calculateWithdrawFeePercent(uint256 lastDepositTimestamp) external view returns (uint16); function depositFeePercent() external view returns (uint16); function withdrawFeePercent() external view returns (uint16); function openPositionFeePercent() external view returns (uint16); function closePositionFeePercent() external view returns (uint16); function openPositionLPFeePercent() external view returns (uint16); function closePositionLPFeePercent() external view returns (uint16); function openPositionFees() external view returns (uint16 openPositionFeePercentResult, uint16 buyingPremiumFeeMaxPercentResult); function turbulenceIndicatorPercent() external view returns (uint16); } // 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: GPL-3.0 pragma solidity ^0.8; interface ICVIOracle { function getCVIRoundData(uint80 roundId) external view returns (uint16 cviValue, uint256 cviTimestamp); function getCVILatestRoundData() external view returns (uint16 cviValue, uint80 cviRoundId, uint256 cviTimestamp); function setDeviationCheck(bool newDeviationCheck) external; function setMaxDeviation(uint16 newMaxDeviation) external; }
100% is MAX_PERCENTAGE = 10000
uint16 public maxVolumeFeeDeltaCollateral = 400;
5,979,771
[ 1, 6625, 9, 353, 4552, 67, 3194, 19666, 2833, 273, 12619, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2313, 1071, 943, 4545, 14667, 9242, 13535, 2045, 287, 273, 7409, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/7001/0x3D9892247AEa8BEcc9f487Fb3709DfbCFF3c83c1/sources/contracts/Withdraw.sol
* @title Withdraw @dev This contract enables the withdrawal of ZRC20 tokens./
contract Withdraw is zContract { error WrongGasContract(); error NotEnoughToPayGasFee(); error InvalidZRC20Address(); error ZeroAmount(); function doWithdrawal( address targetZRC20, uint256 amount, bytes32 recipient pragma solidity 0.8.7; ) private { (address gasZRC20, uint256 gasFee) = IZRC20(targetZRC20) .withdrawGasFee(); if (gasZRC20 != targetZRC20) revert WrongGasContract(); if (gasFee >= amount) revert NotEnoughToPayGasFee(); IZRC20(targetZRC20).approve(targetZRC20, gasFee); IZRC20(targetZRC20).withdraw( abi.encodePacked(recipient), amount - gasFee ); } function onCrossChainCall( address zrc20, uint256 amount, bytes calldata message ) external virtual override { if (zrc20 == address(0)) revert InvalidZRC20Address(); if (amount == 0) revert ZeroAmount(); bytes32 recipient = abi.decode(message, (bytes32)); doWithdrawal(zrc20, amount, recipient); } function withdraw(address zrc20, uint256 amount, bytes32 recipient) public { if (zrc20 == address(0)) revert InvalidZRC20Address(); if (amount == 0) revert ZeroAmount(); doWithdrawal(zrc20, amount, recipient); } }
13,228,956
[ 1, 1190, 9446, 225, 1220, 6835, 19808, 326, 598, 9446, 287, 434, 2285, 11529, 3462, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3423, 9446, 353, 998, 8924, 288, 203, 565, 555, 24668, 27998, 8924, 5621, 203, 565, 555, 2288, 664, 4966, 774, 9148, 27998, 14667, 5621, 203, 565, 555, 1962, 62, 11529, 3462, 1887, 5621, 203, 565, 555, 12744, 6275, 5621, 203, 203, 565, 445, 741, 1190, 9446, 287, 12, 203, 3639, 1758, 1018, 62, 11529, 3462, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1731, 1578, 8027, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 27, 31, 203, 565, 262, 3238, 288, 203, 3639, 261, 2867, 16189, 62, 11529, 3462, 16, 2254, 5034, 16189, 14667, 13, 273, 467, 62, 11529, 3462, 12, 3299, 62, 11529, 3462, 13, 203, 5411, 263, 1918, 9446, 27998, 14667, 5621, 203, 203, 3639, 309, 261, 31604, 62, 11529, 3462, 480, 1018, 62, 11529, 3462, 13, 15226, 24668, 27998, 8924, 5621, 203, 3639, 309, 261, 31604, 14667, 1545, 3844, 13, 15226, 2288, 664, 4966, 774, 9148, 27998, 14667, 5621, 203, 203, 3639, 467, 62, 11529, 3462, 12, 3299, 62, 11529, 3462, 2934, 12908, 537, 12, 3299, 62, 11529, 3462, 16, 16189, 14667, 1769, 203, 3639, 467, 62, 11529, 3462, 12, 3299, 62, 11529, 3462, 2934, 1918, 9446, 12, 203, 5411, 24126, 18, 3015, 4420, 329, 12, 20367, 3631, 203, 5411, 3844, 300, 16189, 14667, 203, 3639, 11272, 203, 565, 289, 203, 203, 565, 445, 603, 13941, 3893, 1477, 12, 203, 3639, 1758, 998, 1310, 3462, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1731, 745, 892, 883, 203, 565, 262, 3903, 5024, 3849, 288, 203, 3639, 309, 2 ]
///////////////////////////////////////////////////////////////////////////////////// //version 2.0 //Author: Taurus //Copyright: [email protected] // //NOTE: non-view functions cannot return values, only possible way is event //Changes from v0.9x. Each node has unique address as identifier. All pools removed //All req and prov handled in the mapping. //update 12/12: pools cannot be removed, since we need to track who are active, cannot search in mapping. /////////////////////////////////////////////////////////////////////////////////////// pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; //return self-defined type contract TaskContract { //list mapping (address => Provider) public providerList; //All here mapping (address => Request) public requestList; //All here mapping (address => uint256) public balanceList; //reqID => balance //ID - counter uint256 private providerCount; //+1 each time uint256 private requestCount; constructor() public { //sol 5.0 syntax providerCount = 0; requestCount = 0; } struct Request { uint256 reqID; //requestID is not identifier uint256 blockNumber; //record the time of submition address payable provider; //record the provider assigned to this request uint64 time; //time uint16 target; //target 0-100.00 uint256 price; //the max amount he can pay bytes dataID; //dataID used to fetch the off-chain data bytes resultID; //dataID to fetch the result uint64 numValidations; //user defined the validation address payable [] validators; //multisignature from validations bool[] signatures; //true or false array bool isValid; //the final flag byte status; //0: 'pending', 1:'providing', 2: validating, 3: complete } struct Provider { uint256 provID; uint256 blockNumber; uint64 maxTime; //max time uint16 maxTarget; //max target he need uint256 minPrice; //lowest price can accept bool available; //if ready to be assigned } event SystemInfo (address payable addr, bytes info); event PairingInfo (address payable reqAddr, address payable provAddr, bytes info); address payable [] providerPool; address payable [] pendingPool; address payable [] providingPool; address payable [] validatingPool; ///////////////////////////////////////////////////////////////////////////////////// // Function called to become a provider. New on List, Map and Pool. // NOTE: cannot use to update. You must stop a previous one and start a new one. // TIPS: gas cost: don't create local copy and write back, modify the storage directly. //gas cost 165K without event / 167K with event / 92K overwrite function startProviding(uint64 maxTime, uint16 maxTarget, uint64 minPrice) public returns (bool) { if(providerList[msg.sender].blockNumber == 0){ //this is new // register a new provider object in the List and map providerList[msg.sender].provID = providerCount; //cost 50k per item edit providerList[msg.sender].blockNumber = block.number; providerList[msg.sender].maxTime = maxTime; providerList[msg.sender].maxTime = maxTime; providerList[msg.sender].maxTarget = maxTarget; providerList[msg.sender].minPrice = minPrice; providerList[msg.sender].available = true; //turn on the flag at LAST // ready for the next providerPool.push(msg.sender); emit SystemInfo (msg.sender, "Provider Added"); providerCount++; assignProvider(msg.sender); return true; } else { if(providerList[msg.sender].available == true){ //can only modify available provider providerList[msg.sender].blockNumber = block.number; providerList[msg.sender].maxTime = maxTime; providerList[msg.sender].maxTarget = maxTarget; providerList[msg.sender].minPrice = minPrice; emit SystemInfo(msg.sender,'Provider Updated'); assignProvider(msg.sender); return true; } } } // Stop a provider, if you know a provider ID. Get em using getProvID() // Must be sent from the provider address or it will be failed. function stopProviding() public returns (bool) { // If the sender is currently an active provider if (providerList[msg.sender].available == true){ //can only stop available provider delete providerList[msg.sender]; //delete from List return ArrayPop(providerPool, msg.sender); //delete from Pool emit SystemInfo(msg.sender, 'Provider Stopped'); } } //update a provider, you must know the provID and must sent from right addr function updateProvider(uint64 maxTime, uint16 maxTarget, uint64 minPrice) public returns (bool) { if(providerList[msg.sender].available == true){ //can only modify available provider providerList[msg.sender].blockNumber = block.number; providerList[msg.sender].maxTime = maxTime; providerList[msg.sender].maxTarget = maxTarget; providerList[msg.sender].minPrice = minPrice; emit SystemInfo(msg.sender,'Provider Updated'); assignProvider(msg.sender); return true; } } // Send a request from user to blockchain. // Assumes price is including the cost for verification function startRequest(uint64 time, uint16 target, uint64 price, bytes memory dataID) payable public returns (bool) { if(requestList[msg.sender].blockNumber == 0){ //register on List requestList[msg.sender].reqID = requestCount; requestList[msg.sender].blockNumber = block.number; requestList[msg.sender].provider = address(0); requestList[msg.sender].time = time; requestList[msg.sender].target = target; requestList[msg.sender].price = price; requestList[msg.sender].dataID = dataID; requestList[msg.sender].numValidations = 1; requestList[msg.sender].status = '0' ; //pending 0x30, not 0 pendingPool.push(msg.sender); emit SystemInfo (msg.sender, "Request Added"); requestCount++; assignRequest(msg.sender); return true; } else { if(requestList[msg.sender].status == '0' ){ //can only update pending request requestList[msg.sender].blockNumber = block.number; requestList[msg.sender].time = time; requestList[msg.sender].target = target; requestList[msg.sender].price = price; requestList[msg.sender].dataID = dataID; emit SystemInfo(msg.sender, 'Request Updated'); return true; } } } function stopRequest() public returns (bool){ if (requestList[msg.sender].status == '0'){ //can only cancel owned pending request delete requestList[msg.sender]; //delete from List emit SystemInfo(msg.sender, 'Request Stopped'); return ArrayPop(pendingPool, msg.sender); //delete from Pool } } function updateRequest(uint64 time, uint16 target, uint64 price, bytes memory dataID) payable public returns (bool) { if(requestList[msg.sender].status == '0' ){ //can only update pending request requestList[msg.sender].blockNumber = block.number; requestList[msg.sender].time = time; requestList[msg.sender].target = target; requestList[msg.sender].price = price; requestList[msg.sender].dataID = dataID; emit SystemInfo(msg.sender, 'Request Updated'); return true; } } // Search in the requestPool, find a job for current provider. Triggered by startProviding // Return true if a match or false if not. // Returns: 0: successfully assigned // 1: searched all providers but find no match // 2: no available provider right now // 3: failure during poping pool function assignProvider(address payable provAddr) private returns (byte){ if(pendingPool.length == 0) return '2'; else { //search throught the requestPool for (uint64 i = 0; i < pendingPool.length; i++){ //save the re-usable reqID , may save gas address payable reqAddr = pendingPool[i]; if( requestList[reqAddr].time <= providerList[provAddr].maxTime && requestList[reqAddr].target <= providerList[provAddr].maxTarget && requestList[reqAddr].price >= providerList[provAddr].minPrice){ //meet the requirement, assign the task //update provider providerList[provAddr].available = false; ArrayPop(providerPool, provAddr); //update request requestList[reqAddr].provider = provAddr; requestList[reqAddr].status = '1'; //providing ArrayPop(pendingPool, reqAddr); //update balanceList addr here is requester's balanceList[reqAddr] += requestList[reqAddr].price; providingPool.push(reqAddr); //status move from pending to providing emit PairingInfo(reqAddr, provAddr, "Request Assigned"); return '0'; } } //after for loop and no match return '1'; } } // Assigning one task to one of the available providers. Only called from requestTask (private) // Search in the providerPool, if no match in the end, return false //could only assign one task at a time //auto sel the first searching result for now, no comparation between multiple availability. //TODO: need ot add preference next patch // Returns: 0: successfully assigned // 1: searched all providers but find no match // 2: no available provider right now // 3: failure during poping pool function assignRequest(address payable reqAddr) private returns (byte) { //provider availability is checked in pool not in list if (providerPool.length == 0) return '2'; else { //if any provider in pool for (uint64 i = 0; i < providerPool.length; i++) { // save the provider's addr, reusable and save gas cost address payable provAddr = providerPool[i]; if(provAddr != address(0) && providerList[provAddr].available == true){ // Check if request conditions meet the providers requirements if (requestList[reqAddr].target <= providerList[provAddr].maxTarget && requestList[reqAddr].time <= providerList[provAddr].maxTime && requestList[reqAddr].price >= providerList[provAddr].minPrice) { //update provider: providerList[provAddr].available = false; ArrayPop(providerPool, provAddr); //update request requestList[reqAddr].provider = provAddr; requestList[reqAddr].status = '1'; //providing ArrayPop(pendingPool, reqAddr); //update balanceList balanceList[reqAddr] += requestList[reqAddr].price; providingPool.push(reqAddr); emit PairingInfo(reqAddr, provAddr, "Request Assigned"); // Let provider listen for this event to see he was selected return '0'; } } } // No provider was found matching the criteria -- request failed //requestList[reqID].addr.transfer(requestList[reqID].price); // Returns the ether to the sender return '1'; } } // Provider will call this when they are done and the data is available. // This will invoke the validation stage but only when the request got enough validators // that req could be moved from pool and marked, // Or that req stays providing function completeRequest(address payable reqAddr, bytes memory resultID) public returns (bool) { // Confirm msg.sender is actually the provider of the task he claims if (msg.sender == requestList[reqAddr].provider) { //change request obj requestList[reqAddr].status = '2'; //validating requestList[reqAddr].resultID = resultID; //move from providing pool to validating Pool. ArrayPop(providingPool, reqAddr); validatingPool.push(reqAddr); //release provider (not necessarily depend on provider) //providerList[providerID[msg.sender]].available = true; emit SystemInfo(reqAddr, 'Request Computation Completed'); //start validation process return validateRequest(reqAddr); } else { return false; } } // Called by assignRequest before finalizing stuff. Contract checks with validators // Returns false if there wasnt enough free providers to send out the required number of validation requests // need validation from 1/10 of nodes -- could change function validateRequest(address payable reqAddr) public returns (bool) { uint64 numValidatorsNeeded = requestList[reqAddr].numValidations; //uint numValidators = providerCount / 10; uint64 validatorsFound = 0; //select # of available provider from the pool and force em to do the validation for (uint64 i = 0; i < providerPool.length; i++) { //get provider ID address payable provID = providerPool[i]; if(provID != requestList[reqAddr].provider){ //validator and computer cannot be same //EVENT: informs validator that they were selected and need to validate emit PairingInfo(reqAddr, provID, 'Validation Assigned to Provider'); validatorsFound++; //remove the providers availablity and pop from pool providerList[provID].available = false; ArrayPop(providerPool, provID); } else continue; //check whether got enough validator if(validatorsFound < numValidatorsNeeded){ continue; } else{ //enough validator emit SystemInfo(reqAddr, 'Enough Validators'); return true; break; } //loop until certain # of validators selected } //exit loop without enough validators emit SystemInfo(reqAddr, 'Not Enough Validators'); } // needs to be more secure by ensuring the submission is coming from someone legit // similar to completeTask but this will sign the validation list of the target Task //TODO: the money part is ommited for now function submitValidation(address payable reqAddr, bool result) public returns (bool) { // Pay the validator // uint partialPayment = requestList[reqID].price / 100; // amount each validator is paid // msg.sender.transfer(partialPayment); // balanceList[requestList[reqID].addr] -= partialPayment; if(msg.sender != requestList[reqAddr].provider) { //validator cannot be provider requestList[reqAddr].validators.push(msg.sender); //push array requestList[reqAddr].signatures.push(result); //edit mapping } //emit ValidationInfo(reqID, provID, 'Validator Signed'); //check if valid emit PairingInfo(reqAddr, msg.sender, 'Validator Signed'); // If enough validations have been submitted if (requestList[reqAddr].validators.length == requestList[reqAddr].numValidations) { //return checkValidation(reqID, requestList[reqID].price - requestList[reqID].numValidationsNeeded * partialPayment); //checkValidation(reqID); } } function checkValidation(address payable reqAddr) public returns (bool) { // Add up successful validations bool flag = false; uint64 successCount = 0; for (uint64 i=0; i<requestList[reqAddr].validators.length; i++) { if (requestList[reqAddr].signatures[i] == true) successCount++; } // if 2/3 of validation attempts were successful // TODO: determine the fraction if (successCount >= requestList[reqAddr].numValidations) { // if 2/3 of validations were valid then provider gets remainder of money //requestList[reqID].provider.transfer(payment); //balanceList[requestList[reqID].addr] -= payment; //TODO: [important] leave out the payment part for now. requestList[reqAddr].isValid = true; // Task was successfully completed! flag = true; } // otherwise, work was invalid, the providers payment goes back to requester else { //requestList[reqID].addr.transfer(payment); //balanceList[requestList[reqID].addr] -= payment; } // EVENT: task is done whether successful or not //emit TaskCompleted(requestList[reqID].addr, reqID); emit SystemInfo(reqAddr, 'Validation Complete'); //popout from pool flag = flag && ArrayPop(validatingPool, reqAddr); return flag; } ///////////////////////////////////////////////////////////////////// // Used to dynamically remove elements from array of open provider spaces. // Using a swap and delete method, search for the desired addr throughout the whole array // delete the desired and swap the whole with last element function ArrayPop(address payable [] storage array, address payable target) private returns (bool) { for(uint64 i = 0; i < array.length; i++){ if (array[i] == target) { //swap last element with hole array[i] = array[array.length-1]; //delete last item delete array[array.length-1]; //decrease size array.length -= 1; return true; } } return false; //fail to search: no matching in pool } ///////////////////////////////////////////////////////////////////////////////// //some helpers defined here function getProvider(address payable ID) public view returns(Provider memory){ return providerList[ID]; } function getRequest(address payable ID) public view returns (Request memory){ return requestList[ID]; } function getProviderCount() public view returns (uint256){ return providerCount; } function getRequestCount() public view returns (uint256){ return requestCount; } function getProviderPool() public view returns (address payable [] memory){ return providerPool; } function getPendingPool() public view returns (address payable [] memory){ return pendingPool; } function getValidatingPool() public view returns (address payable [] memory){ return validatingPool; } function getProvidingPool() public view returns (address payable [] memory){ return providingPool; } function getProviderPoolSize() public view returns (uint256){ return providerPool.length; } function getRequestPoolSize() public view returns (uint256){ return pendingPool.length; } //function getBalance(address addr) public view returns (uint256){ // return balanceList[addr]; //} function listRequests(address payable[] memory IDList) public view returns(Request[50] memory){ Request[50] memory allRequest; for (uint64 i = 0; i < IDList.length; i++){ allRequest[i] = getRequest(IDList[i]); } return allRequest; } function listProviders(address payable[] memory IDList) public view returns(Provider[50] memory){ Provider[50] memory allProvider; //address addr; for (uint64 i = 0; i < IDList.length;i++){ allProvider[i] = getProvider(IDList[i]); } return allProvider; } /* function listAllRequests() public view returns(Request[50] memory){ Request[50] memory allRequest; for (uint64 i = 0; i < requestCount; i++){ allRequest[i] = getRequest(i); } return allRequest; } function listAllProviders() public view returns(Provider[50] memory){ Provider[50] memory allProvider; for (uint64 i = 0; i < providerCount; i++){ allProvider[i] = getProvider(i); } return allProvider; } */ }
Send a request from user to blockchain. Assumes price is including the cost for verification
function startRequest(uint64 time, uint16 target, uint64 price, bytes memory dataID) payable public returns (bool) { if(requestList[msg.sender].blockNumber == 0){ requestList[msg.sender].reqID = requestCount; requestList[msg.sender].blockNumber = block.number; requestList[msg.sender].provider = address(0); requestList[msg.sender].time = time; requestList[msg.sender].target = target; requestList[msg.sender].price = price; requestList[msg.sender].dataID = dataID; requestList[msg.sender].numValidations = 1; pendingPool.push(msg.sender); emit SystemInfo (msg.sender, "Request Added"); requestCount++; assignRequest(msg.sender); return true; requestList[msg.sender].blockNumber = block.number; requestList[msg.sender].time = time; requestList[msg.sender].target = target; requestList[msg.sender].price = price; requestList[msg.sender].dataID = dataID; emit SystemInfo(msg.sender, 'Request Updated'); return true; } } else { }
6,430,858
[ 1, 3826, 279, 590, 628, 729, 358, 16766, 18, 25374, 6205, 353, 6508, 326, 6991, 364, 11805, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 787, 691, 12, 11890, 1105, 813, 16, 2254, 2313, 1018, 16, 2254, 1105, 6205, 16, 1731, 3778, 501, 734, 13, 8843, 429, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 309, 12, 2293, 682, 63, 3576, 18, 15330, 8009, 2629, 1854, 422, 374, 15329, 203, 5411, 590, 682, 63, 3576, 18, 15330, 8009, 3658, 734, 540, 273, 590, 1380, 31, 203, 5411, 590, 682, 63, 3576, 18, 15330, 8009, 2629, 1854, 282, 273, 1203, 18, 2696, 31, 21281, 5411, 590, 682, 63, 3576, 18, 15330, 8009, 6778, 1377, 273, 1758, 12, 20, 1769, 4202, 203, 5411, 590, 682, 63, 3576, 18, 15330, 8009, 957, 1850, 273, 813, 31, 377, 203, 5411, 590, 682, 63, 3576, 18, 15330, 8009, 3299, 3639, 273, 1018, 31, 203, 5411, 590, 682, 63, 3576, 18, 15330, 8009, 8694, 540, 273, 6205, 31, 203, 5411, 590, 682, 63, 3576, 18, 15330, 8009, 892, 734, 3639, 273, 501, 734, 31, 203, 5411, 590, 682, 63, 3576, 18, 15330, 8009, 2107, 1556, 1012, 273, 404, 31, 203, 5411, 4634, 2864, 18, 6206, 12, 3576, 18, 15330, 1769, 203, 5411, 3626, 2332, 966, 261, 3576, 18, 15330, 16, 315, 691, 25808, 8863, 203, 2398, 203, 5411, 590, 1380, 9904, 31, 1377, 203, 5411, 2683, 691, 12, 3576, 18, 15330, 1769, 203, 5411, 327, 638, 31, 203, 7734, 590, 682, 63, 3576, 18, 15330, 8009, 2629, 1854, 565, 273, 1203, 18, 2696, 31, 1850, 203, 7734, 590, 682, 63, 3576, 18, 15330, 8009, 957, 3639, 273, 813, 31, 3639, 203, 7734, 590, 2 ]
// Сочетаемость глаголов (и отглагольных частей речи) с предложным // паттерном. // LC->07.08.2018 facts гл_предл language=Russian { arity=3 //violation_score=-5 generic return=boolean } #define ГЛ_ИНФ(v) инфинитив:v{}, глагол:v{} #region Предлог_В // ------------------- С ПРЕДЛОГОМ 'В' --------------------------- #region Предложный // Глаголы и отглагольные части речи, присоединяющие // предложное дополнение с предлогом В и сущ. в предложном падеже. wordentry_set Гл_В_Предл = { rus_verbs:взорваться{}, // В Дагестане взорвался автомобиль // вернуть после перекомпиляции rus_verbs:подорожать{}, // В Дагестане подорожал хлеб rus_verbs:воевать{}, // Воевал во Франции. rus_verbs:устать{}, // Устали в дороге? rus_verbs:изнывать{}, // В Лондоне Черчилль изнывал от нетерпения. rus_verbs:решить{}, // Что решат в правительстве? rus_verbs:выскакивать{}, // Один из бойцов на улицу выскакивает. rus_verbs:обстоять{}, // В действительности же дело обстояло не так. rus_verbs:подыматься{}, rus_verbs:поехать{}, // поедем в такси! rus_verbs:уехать{}, // он уехал в такси rus_verbs:прибыть{}, // они прибыли в качестве независимых наблюдателей rus_verbs:ОБЛАЧИТЬ{}, rus_verbs:ОБЛАЧАТЬ{}, rus_verbs:ОБЛАЧИТЬСЯ{}, rus_verbs:ОБЛАЧАТЬСЯ{}, rus_verbs:НАРЯДИТЬСЯ{}, rus_verbs:НАРЯЖАТЬСЯ{}, rus_verbs:ПОВАЛЯТЬСЯ{}, // повалявшись в снегу, бежать обратно в тепло. rus_verbs:ПОКРЫВАТЬ{}, // Во многих местах ее покрывали трещины, наросты и довольно плоские выступы. (ПОКРЫВАТЬ) rus_verbs:ПРОЖИГАТЬ{}, // Синий луч искрился белыми пятнами и прожигал в земле дымящуюся борозду. (ПРОЖИГАТЬ) rus_verbs:МЫЧАТЬ{}, // В огромной куче тел жалобно мычали задавленные трупами и раненые бизоны. (МЫЧАТЬ) rus_verbs:РАЗБОЙНИЧАТЬ{}, // Эти существа обычно разбойничали в трехстах милях отсюда (РАЗБОЙНИЧАТЬ) rus_verbs:МАЯЧИТЬ{}, // В отдалении маячили огромные серые туши мастодонтов и мамонтов с изогнутыми бивнями. (МАЯЧИТЬ/ЗАМАЯЧИТЬ) rus_verbs:ЗАМАЯЧИТЬ{}, rus_verbs:НЕСТИСЬ{}, // Кони неслись вперед в свободном и легком галопе (НЕСТИСЬ) rus_verbs:ДОБЫТЬ{}, // Они надеялись застать "медвежий народ" врасплох и добыть в бою голову величайшего из воинов. (ДОБЫТЬ) rus_verbs:СПУСТИТЬ{}, // Время от времени грохот или вопль объявляли о спущенной где-то во дворце ловушке. (СПУСТИТЬ) rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Она сузила глаза, на лице ее стала образовываться маска безумия. (ОБРАЗОВЫВАТЬСЯ) rus_verbs:КИШЕТЬ{}, // в этом районе кишмя кишели разбойники и драконы. (КИШЕТЬ) rus_verbs:ДЫШАТЬ{}, // Она тяжело дышала в тисках гнева (ДЫШАТЬ) rus_verbs:ЗАДЕВАТЬ{}, // тот задевал в нем какую-то струну (ЗАДЕВАТЬ) rus_verbs:УСТУПИТЬ{}, // Так что теперь уступи мне в этом. (УСТУПИТЬ) rus_verbs:ТЕРЯТЬ{}, // Хотя он хорошо питался, он терял в весе (ТЕРЯТЬ/ПОТЕРЯТЬ) rus_verbs:ПоТЕРЯТЬ{}, rus_verbs:УТЕРЯТЬ{}, rus_verbs:РАСТЕРЯТЬ{}, rus_verbs:СМЫКАТЬСЯ{}, // Словно медленно смыкающийся во сне глаз, отверстие медленно закрывалось. (СМЫКАТЬСЯ/СОМКНУТЬСЯ, + оборот с СЛОВНО/БУДТО + вин.п.) rus_verbs:СОМКНУТЬСЯ{}, rus_verbs:РАЗВОРОШИТЬ{}, // Вольф не узнал никаких отдельных слов, но звуки и взаимодействующая высота тонов разворошили что-то в его памяти. (РАЗВОРОШИТЬ) rus_verbs:ПРОСТОЯТЬ{}, // Он поднялся и некоторое время простоял в задумчивости. (ПРОСТОЯТЬ,ВЫСТОЯТЬ,ПОСТОЯТЬ) rus_verbs:ВЫСТОЯТЬ{}, rus_verbs:ПОСТОЯТЬ{}, rus_verbs:ВЗВЕСИТЬ{}, // Он поднял и взвесил в руке один из рогов изобилия. (ВЗВЕСИТЬ/ВЗВЕШИВАТЬ) rus_verbs:ВЗВЕШИВАТЬ{}, rus_verbs:ДРЕЙФОВАТЬ{}, // Он и тогда не упадет, а будет дрейфовать в отбрасываемой диском тени. (ДРЕЙФОВАТЬ) прилагательное:быстрый{}, // Кисель быстр в приготовлении rus_verbs:призвать{}, // В День Воли белорусов призвали побороть страх и лень rus_verbs:призывать{}, rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // этими деньгами смогу воспользоваться в отпуске (ВОСПОЛЬЗОВАТЬСЯ) rus_verbs:КОНКУРИРОВАТЬ{}, // Наши клубы могли бы в Англии конкурировать с лидерами (КОНКУРИРОВАТЬ) rus_verbs:ПОЗВАТЬ{}, // Американскую телеведущую позвали замуж в прямом эфире (ПОЗВАТЬ) rus_verbs:ВЫХОДИТЬ{}, // Районные газеты Вологодчины будут выходить в цвете и новом формате (ВЫХОДИТЬ) rus_verbs:РАЗВОРАЧИВАТЬСЯ{}, // Сюжет фэнтези разворачивается в двух мирах (РАЗВОРАЧИВАТЬСЯ) rus_verbs:ОБСУДИТЬ{}, // В Самаре обсудили перспективы информатизации ветеринарии (ОБСУДИТЬ) rus_verbs:ВЗДРОГНУТЬ{}, // она сильно вздрогнула во сне (ВЗДРОГНУТЬ) rus_verbs:ПРЕДСТАВЛЯТЬ{}, // Сенаторы, представляющие в Комитете по разведке обе партии, поддержали эту просьбу (ПРЕДСТАВЛЯТЬ) rus_verbs:ДОМИНИРОВАТЬ{}, // в химическом составе одной из планет доминирует метан (ДОМИНИРОВАТЬ) rus_verbs:ОТКРЫТЬ{}, // Крым открыл в Москве собственный туристический офис (ОТКРЫТЬ) rus_verbs:ПОКАЗАТЬ{}, // В Пушкинском музее показали золото инков (ПОКАЗАТЬ) rus_verbs:наблюдать{}, // Наблюдаемый в отражении цвет излучения rus_verbs:ПРОЛЕТЕТЬ{}, // Крупный астероид пролетел в непосредственной близости от Земли (ПРОЛЕТЕТЬ) rus_verbs:РАССЛЕДОВАТЬ{}, // В Дагестане расследуют убийство федерального судьи (РАССЛЕДОВАТЬ) rus_verbs:ВОЗОБНОВИТЬСЯ{}, // В Кемеровской области возобновилось движение по трассам международного значения (ВОЗОБНОВИТЬСЯ) rus_verbs:ИЗМЕНИТЬСЯ{}, // изменилась она во всем (ИЗМЕНИТЬСЯ) rus_verbs:СВЕРКАТЬ{}, // за широким окном комнаты город сверкал во тьме разноцветными огнями (СВЕРКАТЬ) rus_verbs:СКОНЧАТЬСЯ{}, // В Риме скончался режиссёр знаменитого сериала «Спрут» (СКОНЧАТЬСЯ) rus_verbs:ПРЯТАТЬСЯ{}, // Cкрытые спутники прячутся в кольцах Сатурна (ПРЯТАТЬСЯ) rus_verbs:ВЫЗЫВАТЬ{}, // этот человек всегда вызывал во мне восхищение (ВЫЗЫВАТЬ) rus_verbs:ВЫПУСТИТЬ{}, // Избирательные бюллетени могут выпустить в форме брошюры (ВЫПУСТИТЬ) rus_verbs:НАЧИНАТЬСЯ{}, // В Москве начинается «марш в защиту детей» (НАЧИНАТЬСЯ) rus_verbs:ЗАСТРЕЛИТЬ{}, // В Дагестане застрелили преподавателя медресе (ЗАСТРЕЛИТЬ) rus_verbs:УРАВНЯТЬ{}, // Госзаказчиков уравняют в правах с поставщиками (УРАВНЯТЬ) rus_verbs:промахнуться{}, // в первой половине невероятным образом промахнулся экс-форвард московского ЦСКА rus_verbs:ОБЫГРАТЬ{}, // "Рубин" сенсационно обыграл в Мадриде вторую команду Испании (ОБЫГРАТЬ) rus_verbs:ВКЛЮЧИТЬ{}, // В Челябинской области включен аварийный роуминг (ВКЛЮЧИТЬ) rus_verbs:УЧАСТИТЬСЯ{}, // В селах Балаковского района участились случаи поджогов стогов сена (УЧАСТИТЬСЯ) rus_verbs:СПАСТИ{}, // В Австралии спасли повисшего на проводе коршуна (СПАСТИ) rus_verbs:ВЫПАСТЬ{}, // Отдельные фрагменты достигли земли, выпав в виде метеоритного дождя (ВЫПАСТЬ) rus_verbs:НАГРАДИТЬ{}, // В Лондоне наградили лауреатов премии Brit Awards (НАГРАДИТЬ) rus_verbs:ОТКРЫТЬСЯ{}, // в Москве открылся первый международный кинофестиваль rus_verbs:ПОДНИМАТЬСЯ{}, // во мне поднималось раздражение rus_verbs:ЗАВЕРШИТЬСЯ{}, // В Италии завершился традиционный Венецианский карнавал (ЗАВЕРШИТЬСЯ) инфинитив:проводить{ вид:несоверш }, // Кузбасские депутаты проводят в Кемерове прием граждан глагол:проводить{ вид:несоверш }, деепричастие:проводя{}, rus_verbs:отсутствовать{}, // Хозяйка квартиры в этот момент отсутствовала rus_verbs:доложить{}, // об итогах своего визита он намерен доложить в американском сенате и Белом доме (ДОЛОЖИТЬ ОБ, В предл) rus_verbs:ИЗДЕВАТЬСЯ{}, // В Эйлате издеваются над туристами (ИЗДЕВАТЬСЯ В предл) rus_verbs:НАРУШИТЬ{}, // В нескольких регионах нарушено наземное транспортное сообщение (НАРУШИТЬ В предл) rus_verbs:БЕЖАТЬ{}, // далеко внизу во тьме бежала невидимая река (БЕЖАТЬ В предл) rus_verbs:СОБРАТЬСЯ{}, // Дмитрий оглядел собравшихся во дворе мальчишек (СОБРАТЬСЯ В предл) rus_verbs:ПОСЛЫШАТЬСЯ{}, // далеко вверху во тьме послышался ответ (ПОСЛЫШАТЬСЯ В предл) rus_verbs:ПОКАЗАТЬСЯ{}, // во дворе показалась высокая фигура (ПОКАЗАТЬСЯ В предл) rus_verbs:УЛЫБНУТЬСЯ{}, // Дмитрий горько улыбнулся во тьме (УЛЫБНУТЬСЯ В предл) rus_verbs:ТЯНУТЬСЯ{}, // убежища тянулись во всех направлениях (ТЯНУТЬСЯ В предл) rus_verbs:РАНИТЬ{}, // В американском университете ранили человека (РАНИТЬ В предл) rus_verbs:ЗАХВАТИТЬ{}, // Пираты освободили корабль, захваченный в Гвинейском заливе (ЗАХВАТИТЬ В предл) rus_verbs:РАЗБЕГАТЬСЯ{}, // люди разбегались во всех направлениях (РАЗБЕГАТЬСЯ В предл) rus_verbs:ПОГАСНУТЬ{}, // во всем доме погас свет (ПОГАСНУТЬ В предл) rus_verbs:ПОШЕВЕЛИТЬСЯ{}, // Дмитрий пошевелился во сне (ПОШЕВЕЛИТЬСЯ В предл) rus_verbs:ЗАСТОНАТЬ{}, // раненый застонал во сне (ЗАСТОНАТЬ В предл) прилагательное:ВИНОВАТЫЙ{}, // во всем виновато вино (ВИНОВАТЫЙ В) rus_verbs:ОСТАВЛЯТЬ{}, // США оставляют в районе Персидского залива только один авианосец (ОСТАВЛЯТЬ В предл) rus_verbs:ОТКАЗЫВАТЬСЯ{}, // В России отказываются от планов авиагруппы в Арктике (ОТКАЗЫВАТЬСЯ В предл) rus_verbs:ЛИКВИДИРОВАТЬ{}, // В Кабардино-Балкарии ликвидирован подпольный завод по переработке нефти (ЛИКВИДИРОВАТЬ В предл) rus_verbs:РАЗОБЛАЧИТЬ{}, // В США разоблачили крупнейшую махинацию с кредитками (РАЗОБЛАЧИТЬ В предл) rus_verbs:СХВАТИТЬ{}, // их схватили во сне (СХВАТИТЬ В предл) rus_verbs:НАЧАТЬ{}, // В Белгороде начали сбор подписей за отставку мэра (НАЧАТЬ В предл) rus_verbs:РАСТИ{}, // Cамая маленькая муха растёт в голове муравья (РАСТИ В предл) rus_verbs:похитить{}, // Двое россиян, похищенных террористами в Сирии, освобождены (похитить в предл) rus_verbs:УЧАСТВОВАТЬ{}, // были застрелены два испанских гражданских гвардейца , участвовавших в слежке (УЧАСТВОВАТЬ В) rus_verbs:УСЫНОВИТЬ{}, // Американцы забирают усыновленных в России детей (УСЫНОВИТЬ В) rus_verbs:ПРОИЗВЕСТИ{}, // вы не увидите мясо или молоко , произведенное в районе (ПРОИЗВЕСТИ В предл) rus_verbs:ОРИЕНТИРОВАТЬСЯ{}, // призван помочь госслужащему правильно ориентироваться в сложных нравственных коллизиях (ОРИЕНТИРОВАТЬСЯ В) rus_verbs:ПОВРЕДИТЬ{}, // В зале игровых автоматов повреждены стены и потолок (ПОВРЕДИТЬ В предл) rus_verbs:ИЗЪЯТЬ{}, // В настоящее время в детском учреждении изъяты суточные пробы пищи (ИЗЪЯТЬ В предл) rus_verbs:СОДЕРЖАТЬСЯ{}, // осужденных , содержащихся в помещениях штрафного изолятора (СОДЕРЖАТЬСЯ В) rus_verbs:ОТЧИСЛИТЬ{}, // был отчислен за неуспеваемость в 2007 году (ОТЧИСЛИТЬ В предл) rus_verbs:проходить{}, // находился на санкционированном митинге , проходившем в рамках празднования Дня народного единства (проходить в предл) rus_verbs:ПОДУМЫВАТЬ{}, // сейчас в правительстве Приамурья подумывают о создании специального пункта помощи туристам (ПОДУМЫВАТЬ В) rus_verbs:ОТРАПОРТОВЫВАТЬ{}, // главы субъектов не просто отрапортовывали в Москве (ОТРАПОРТОВЫВАТЬ В предл) rus_verbs:ВЕСТИСЬ{}, // в городе ведутся работы по установке праздничной иллюминации (ВЕСТИСЬ В) rus_verbs:ОДОБРИТЬ{}, // Одобренным в первом чтении законопроектом (ОДОБРИТЬ В) rus_verbs:ЗАМЫЛИТЬСЯ{}, // ему легче исправлять , то , что замылилось в глазах предыдущего руководства (ЗАМЫЛИТЬСЯ В) rus_verbs:АВТОРИЗОВАТЬСЯ{}, // потом имеют право авторизоваться в системе Международного бакалавриата (АВТОРИЗОВАТЬСЯ В) rus_verbs:ОПУСТИТЬСЯ{}, // Россия опустилась в списке на шесть позиций (ОПУСТИТЬСЯ В предл) rus_verbs:СГОРЕТЬ{}, // Совладелец сгоревшего в Бразилии ночного клуба сдался полиции (СГОРЕТЬ В) частица:нет{}, // В этом нет сомнения. частица:нету{}, // В этом нету сомнения. rus_verbs:поджечь{}, // Поджегший себя в Москве мужчина оказался ветераном-афганцем rus_verbs:ввести{}, // В Молдавии введен запрет на амнистию или помилование педофилов. прилагательное:ДОСТУПНЫЙ{}, // Наиболее интересные таблички доступны в основной экспозиции музея (ДОСТУПНЫЙ В) rus_verbs:ПОВИСНУТЬ{}, // вопрос повис в мглистом демократическом воздухе (ПОВИСНУТЬ В) rus_verbs:ВЗОРВАТЬ{}, // В Ираке смертник взорвал в мечети группу туркменов (ВЗОРВАТЬ В) rus_verbs:ОТНЯТЬ{}, // В Финляндии у россиянки, прибывшей по туристической визе, отняли детей (ОТНЯТЬ В) rus_verbs:НАЙТИ{}, // Я недавно посетил врача и у меня в глазах нашли какую-то фигню (НАЙТИ В предл) rus_verbs:ЗАСТРЕЛИТЬСЯ{}, // Девушка, застрелившаяся в центре Киева, была замешана в скандале с влиятельными людьми (ЗАСТРЕЛИТЬСЯ В) rus_verbs:стартовать{}, // В Страсбурге сегодня стартует зимняя сессия Парламентской ассамблеи Совета Европы (стартовать в) rus_verbs:ЗАКЛАДЫВАТЬСЯ{}, // Отношение к деньгам закладывается в детстве (ЗАКЛАДЫВАТЬСЯ В) rus_verbs:НАПИВАТЬСЯ{}, // Депутатам помешают напиваться в здании Госдумы (НАПИВАТЬСЯ В) rus_verbs:ВЫПРАВИТЬСЯ{}, // Прежде всего было заявлено, что мировая экономика каким-то образом сама выправится в процессе бизнес-цикла (ВЫПРАВИТЬСЯ В) rus_verbs:ЯВЛЯТЬСЯ{}, // она являлась ко мне во всех моих снах (ЯВЛЯТЬСЯ В) rus_verbs:СТАЖИРОВАТЬСЯ{}, // сейчас я стажируюсь в одной компании (СТАЖИРОВАТЬСЯ В) rus_verbs:ОБСТРЕЛЯТЬ{}, // Уроженцы Чечни, обстрелявшие полицейских в центре Москвы, арестованы (ОБСТРЕЛЯТЬ В) rus_verbs:РАСПРОСТРАНИТЬ{}, // Воски — распространённые в растительном и животном мире сложные эфиры высших жирных кислот и высших высокомолекулярных спиртов (РАСПРОСТРАНИТЬ В) rus_verbs:ПРИВЕСТИ{}, // Сравнительная фугасность некоторых взрывчатых веществ приведена в следующей таблице (ПРИВЕСТИ В) rus_verbs:ЗАПОДОЗРИТЬ{}, // Чиновников Минкультуры заподозрили в афере с заповедными землями (ЗАПОДОЗРИТЬ В) rus_verbs:НАСТУПАТЬ{}, // В Гренландии стали наступать ледники (НАСТУПАТЬ В) rus_verbs:ВЫДЕЛЯТЬСЯ{}, // В истории Земли выделяются следующие ледниковые эры (ВЫДЕЛЯТЬСЯ В) rus_verbs:ПРЕДСТАВИТЬ{}, // Данные представлены в хронологическом порядке (ПРЕДСТАВИТЬ В) rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА) rus_verbs:ПОДАВАТЬ{}, // Готовые компоты подают в столовых и кафе (ПОДАВАТЬ В) rus_verbs:ГОТОВИТЬ{}, // Сегодня компот готовят в домашних условиях из сухофруктов или замороженных фруктов и ягод (ГОТОВИТЬ В) rus_verbs:ВОЗДЕЛЫВАТЬСЯ{}, // в настоящее время он повсеместно возделывается в огородах (ВОЗДЕЛЫВАТЬСЯ В) rus_verbs:РАСКЛАДЫВАТЬ{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА) rus_verbs:РАСКЛАДЫВАТЬСЯ{}, rus_verbs:СОБИРАТЬСЯ{}, // Обыкновенно огурцы собираются в полуспелом состоянии (СОБИРАТЬСЯ В) rus_verbs:ПРОГРЕМЕТЬ{}, // В торговом центре Ижевска прогремел взрыв (ПРОГРЕМЕТЬ В) rus_verbs:СНЯТЬ{}, // чтобы снять их во всей красоте. (СНЯТЬ В) rus_verbs:ЯВИТЬСЯ{}, // она явилась к нему во сне. (ЯВИТЬСЯ В) rus_verbs:ВЕРИТЬ{}, // мы же во всем верили капитану. (ВЕРИТЬ В предл) rus_verbs:выдержать{}, // Игра выдержана в научно-фантастическом стиле. (ВЫДЕРЖАННЫЙ В) rus_verbs:ПРЕОДОЛЕТЬ{}, // мы пытались преодолеть ее во многих местах. (ПРЕОДОЛЕТЬ В) инфинитив:НАПИСАТЬ{ aux stress="напис^ать" }, // Программа, написанная в спешке, выполнила недопустимую операцию. (НАПИСАТЬ В) глагол:НАПИСАТЬ{ aux stress="напис^ать" }, прилагательное:НАПИСАННЫЙ{}, rus_verbs:ЕСТЬ{}, // ты даже во сне ел. (ЕСТЬ/кушать В) rus_verbs:УСЕСТЬСЯ{}, // Он удобно уселся в кресле. (УСЕСТЬСЯ В) rus_verbs:ТОРГОВАТЬ{}, // Он торгует в палатке. (ТОРГОВАТЬ В) rus_verbs:СОВМЕСТИТЬ{}, // Он совместил в себе писателя и художника. (СОВМЕСТИТЬ В) rus_verbs:ЗАБЫВАТЬ{}, // об этом нельзя забывать даже во сне. (ЗАБЫВАТЬ В) rus_verbs:поговорить{}, // Давайте поговорим об этом в присутствии адвоката rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ) rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА) rus_verbs:раскрыть{}, // В России раскрыли крупнейшую в стране сеть фальшивомонетчиков (РАСКРЫТЬ В) rus_verbs:соединить{}, // соединить в себе (СОЕДИНИТЬ В предл) rus_verbs:избрать{}, // В Южной Корее избран новый президент (ИЗБРАТЬ В предл) rus_verbs:проводиться{}, // Обыски проводятся в воронежском Доме прав человека (ПРОВОДИТЬСЯ В) безлич_глагол:хватает{}, // В этой статье не хватает ссылок на источники информации. (БЕЗЛИЧ хватать в) rus_verbs:наносить{}, // В ближнем бою наносит мощные удары своим костлявым кулаком. (НАНОСИТЬ В + предл.) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) прилагательное:известный{}, // В Европе сахар был известен ещё римлянам. (ИЗВЕСТНЫЙ В) rus_verbs:выработать{}, // Способы, выработанные во Франции, перешли затем в Германию и другие страны Европы. (ВЫРАБОТАТЬ В) rus_verbs:КУЛЬТИВИРОВАТЬСЯ{}, // Культивируется в регионах с умеренным климатом с умеренным количеством осадков и требует плодородной почвы. (КУЛЬТИВИРОВАТЬСЯ В) rus_verbs:чаять{}, // мама души не чаяла в своих детях (ЧАЯТЬ В) rus_verbs:улыбаться{}, // Вадим улыбался во сне. (УЛЫБАТЬСЯ В) rus_verbs:растеряться{}, // Приезжие растерялись в бетонном лабиринте улиц (РАСТЕРЯТЬСЯ В) rus_verbs:выть{}, // выли волки где-то в лесу (ВЫТЬ В) rus_verbs:ЗАВЕРИТЬ{}, // выступавший заверил нас в намерении выполнить обещание (ЗАВЕРИТЬ В) rus_verbs:ИСЧЕЗНУТЬ{}, // звери исчезли во мраке. (ИСЧЕЗНУТЬ В) rus_verbs:ВСТАТЬ{}, // встать во главе человечества. (ВСТАТЬ В) rus_verbs:УПОТРЕБЛЯТЬ{}, // В Тибете употребляют кирпичный зелёный чай. (УПОТРЕБЛЯТЬ В) rus_verbs:ПОДАВАТЬСЯ{}, // Напиток охлаждается и подаётся в холодном виде. (ПОДАВАТЬСЯ В) rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // в игре используются текстуры большего разрешения (ИСПОЛЬЗОВАТЬСЯ В) rus_verbs:объявить{}, // В газете объявили о конкурсе. rus_verbs:ВСПЫХНУТЬ{}, // во мне вспыхнул гнев. (ВСПЫХНУТЬ В) rus_verbs:КРЫТЬСЯ{}, // В его словах кроется угроза. (КРЫТЬСЯ В) rus_verbs:подняться{}, // В классе вдруг поднялся шум. (подняться в) rus_verbs:наступить{}, // В классе наступила полная тишина. (наступить в) rus_verbs:кипеть{}, // В нём кипит злоба. (кипеть в) rus_verbs:соединиться{}, // В нём соединились храбрость и великодушие. (соединиться в) инфинитив:ПАРИТЬ{ aux stress="пар^ить"}, // Высоко в небе парит орёл, плавно описывая круги. (ПАРИТЬ В) глагол:ПАРИТЬ{ aux stress="пар^ить"}, деепричастие:паря{ aux stress="пар^я" }, прилагательное:ПАРЯЩИЙ{}, прилагательное:ПАРИВШИЙ{}, rus_verbs:СИЯТЬ{}, // Главы собора сияли в лучах солнца. (СИЯТЬ В) rus_verbs:РАСПОЛОЖИТЬ{}, // Гостиница расположена глубоко в горах. (РАСПОЛОЖИТЬ В) rus_verbs:развиваться{}, // Действие в комедии развивается в двух планах. (развиваться в) rus_verbs:ПОСАДИТЬ{}, // Дети посадили у нас во дворе цветы. (ПОСАДИТЬ В) rus_verbs:ИСКОРЕНЯТЬ{}, // Дурные привычки следует искоренять в самом начале. (ИСКОРЕНЯТЬ В) rus_verbs:ВОССТАНОВИТЬ{}, // Его восстановили в правах. (ВОССТАНОВИТЬ В) rus_verbs:ПОЛАГАТЬСЯ{}, // мы полагаемся на него в этих вопросах (ПОЛАГАТЬСЯ В) rus_verbs:УМИРАТЬ{}, // они умирали во сне. (УМИРАТЬ В) rus_verbs:ПРИБАВИТЬ{}, // Она сильно прибавила в весе. (ПРИБАВИТЬ В) rus_verbs:посмотреть{}, // Посмотрите в списке. (посмотреть в) rus_verbs:производиться{}, // Выдача новых паспортов будет производиться в следующем порядке (производиться в) rus_verbs:принять{}, // Документ принят в следующей редакции (принять в) rus_verbs:сверкнуть{}, // меч его сверкнул во тьме. (сверкнуть в) rus_verbs:ВЫРАБАТЫВАТЬ{}, // ты должен вырабатывать в себе силу воли (ВЫРАБАТЫВАТЬ В) rus_verbs:достать{}, // Эти сведения мы достали в Волгограде. (достать в) rus_verbs:звучать{}, // в доме звучала музыка (звучать в) rus_verbs:колебаться{}, // колеблется в выборе (колебаться в) rus_verbs:мешать{}, // мешать в кастрюле суп (мешать в) rus_verbs:нарастать{}, // во мне нарастал гнев (нарастать в) rus_verbs:отбыть{}, // Вадим отбыл в неизвестном направлении (отбыть в) rus_verbs:светиться{}, // во всем доме светилось только окно ее спальни. (светиться в) rus_verbs:вычитывать{}, // вычитывать в книге rus_verbs:гудеть{}, // У него в ушах гудит. rus_verbs:давать{}, // В этой лавке дают в долг? rus_verbs:поблескивать{}, // Красивое стеклышко поблескивало в пыльной траве у дорожки. rus_verbs:разойтись{}, // Они разошлись в темноте. rus_verbs:прибежать{}, // Мальчик прибежал в слезах. rus_verbs:биться{}, // Она билась в истерике. rus_verbs:регистрироваться{}, // регистрироваться в системе rus_verbs:считать{}, // я буду считать в уме rus_verbs:трахаться{}, // трахаться в гамаке rus_verbs:сконцентрироваться{}, // сконцентрироваться в одной точке rus_verbs:разрушать{}, // разрушать в дробилке rus_verbs:засидеться{}, // засидеться в гостях rus_verbs:засиживаться{}, // засиживаться в гостях rus_verbs:утопить{}, // утопить лодку в реке (утопить в реке) rus_verbs:навестить{}, // навестить в доме престарелых rus_verbs:запомнить{}, // запомнить в кэше rus_verbs:убивать{}, // убивать в помещении полиции (-score убивать неодуш. дом.) rus_verbs:базироваться{}, // установка базируется в черте города (ngram черта города - проверить что есть проверка) rus_verbs:покупать{}, // Чаще всего россияне покупают в интернете бытовую технику. rus_verbs:ходить{}, // ходить в пальто (сделать ХОДИТЬ + в + ОДЕЖДА предл.п.) rus_verbs:заложить{}, // диверсанты заложили в помещении бомбу rus_verbs:оглядываться{}, // оглядываться в зеркале rus_verbs:нарисовать{}, // нарисовать в тетрадке rus_verbs:пробить{}, // пробить отверствие в стене rus_verbs:повертеть{}, // повертеть в руке rus_verbs:вертеть{}, // Я вертел в руках rus_verbs:рваться{}, // Веревка рвется в месте надреза rus_verbs:распространяться{}, // распространяться в среде наркоманов rus_verbs:попрощаться{}, // попрощаться в здании морга rus_verbs:соображать{}, // соображать в уме инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, // просыпаться в чужой кровати rus_verbs:заехать{}, // Коля заехал в гости (в гости - устойчивый наречный оборот) rus_verbs:разобрать{}, // разобрать в гараже rus_verbs:помереть{}, // помереть в пути rus_verbs:различить{}, // различить в темноте rus_verbs:рисовать{}, // рисовать в графическом редакторе rus_verbs:проследить{}, // проследить в записях камер слежения rus_verbs:совершаться{}, // Правосудие совершается в суде rus_verbs:задремать{}, // задремать в кровати rus_verbs:ругаться{}, // ругаться в комнате rus_verbs:зазвучать{}, // зазвучать в радиоприемниках rus_verbs:задохнуться{}, // задохнуться в воде rus_verbs:порождать{}, // порождать в неокрепших умах rus_verbs:отдыхать{}, // отдыхать в санатории rus_verbs:упоминаться{}, // упоминаться в предыдущем сообщении rus_verbs:образовать{}, // образовать в пробирке темную взвесь rus_verbs:отмечать{}, // отмечать в списке rus_verbs:подчеркнуть{}, // подчеркнуть в блокноте rus_verbs:плясать{}, // плясать в откружении незнакомых людей rus_verbs:повысить{}, // повысить в звании rus_verbs:поджидать{}, // поджидать в подъезде rus_verbs:отказать{}, // отказать в пересмотре дела rus_verbs:раствориться{}, // раствориться в бензине rus_verbs:отражать{}, // отражать в стихах rus_verbs:дремать{}, // дремать в гамаке rus_verbs:применяться{}, // применяться в домашних условиях rus_verbs:присниться{}, // присниться во сне rus_verbs:трястись{}, // трястись в драндулете rus_verbs:сохранять{}, // сохранять в неприкосновенности rus_verbs:расстрелять{}, // расстрелять в ложбине rus_verbs:рассчитать{}, // рассчитать в программе rus_verbs:перебирать{}, // перебирать в руке rus_verbs:разбиться{}, // разбиться в аварии rus_verbs:поискать{}, // поискать в углу rus_verbs:мучиться{}, // мучиться в тесной клетке rus_verbs:замелькать{}, // замелькать в телевизоре rus_verbs:грустить{}, // грустить в одиночестве rus_verbs:крутить{}, // крутить в банке rus_verbs:объявиться{}, // объявиться в городе rus_verbs:подготовить{}, // подготовить в тайне rus_verbs:различать{}, // различать в смеси rus_verbs:обнаруживать{}, // обнаруживать в крови rus_verbs:киснуть{}, // киснуть в захолустье rus_verbs:оборваться{}, // оборваться в начале фразы rus_verbs:запутаться{}, // запутаться в веревках rus_verbs:общаться{}, // общаться в интимной обстановке rus_verbs:сочинить{}, // сочинить в ресторане rus_verbs:изобрести{}, // изобрести в домашней лаборатории rus_verbs:прокомментировать{}, // прокомментировать в своем блоге rus_verbs:давить{}, // давить в зародыше rus_verbs:повториться{}, // повториться в новом обличье rus_verbs:отставать{}, // отставать в общем зачете rus_verbs:разработать{}, // разработать в лаборатории rus_verbs:качать{}, // качать в кроватке rus_verbs:заменить{}, // заменить в двигателе rus_verbs:задыхаться{}, // задыхаться в душной и влажной атмосфере rus_verbs:забегать{}, // забегать в спешке rus_verbs:наделать{}, // наделать в решении ошибок rus_verbs:исказиться{}, // исказиться в кривом зеркале rus_verbs:тушить{}, // тушить в помещении пожар rus_verbs:охранять{}, // охранять в здании входы rus_verbs:приметить{}, // приметить в кустах rus_verbs:скрыть{}, // скрыть в складках одежды rus_verbs:удерживать{}, // удерживать в заложниках rus_verbs:увеличиваться{}, // увеличиваться в размере rus_verbs:красоваться{}, // красоваться в новом платье rus_verbs:сохраниться{}, // сохраниться в тепле rus_verbs:лечить{}, // лечить в стационаре rus_verbs:смешаться{}, // смешаться в баке rus_verbs:прокатиться{}, // прокатиться в троллейбусе rus_verbs:договариваться{}, // договариваться в закрытом кабинете rus_verbs:опубликовать{}, // опубликовать в официальном блоге rus_verbs:охотиться{}, // охотиться в прериях rus_verbs:отражаться{}, // отражаться в окне rus_verbs:понизить{}, // понизить в должности rus_verbs:обедать{}, // обедать в ресторане rus_verbs:посидеть{}, // посидеть в тени rus_verbs:сообщаться{}, // сообщаться в оппозиционной газете rus_verbs:свершиться{}, // свершиться в суде rus_verbs:ночевать{}, // ночевать в гостинице rus_verbs:темнеть{}, // темнеть в воде rus_verbs:гибнуть{}, // гибнуть в застенках rus_verbs:усиливаться{}, // усиливаться в направлении главного удара rus_verbs:расплыться{}, // расплыться в улыбке rus_verbs:превышать{}, // превышать в несколько раз rus_verbs:проживать{}, // проживать в отдельной коморке rus_verbs:голубеть{}, // голубеть в тепле rus_verbs:исследовать{}, // исследовать в естественных условиях rus_verbs:обитать{}, // обитать в лесу rus_verbs:скучать{}, // скучать в одиночестве rus_verbs:сталкиваться{}, // сталкиваться в воздухе rus_verbs:таиться{}, // таиться в глубине rus_verbs:спасать{}, // спасать в море rus_verbs:заблудиться{}, // заблудиться в лесу rus_verbs:создаться{}, // создаться в новом виде rus_verbs:пошарить{}, // пошарить в кармане rus_verbs:планировать{}, // планировать в программе rus_verbs:отбить{}, // отбить в нижней части rus_verbs:отрицать{}, // отрицать в суде свою вину rus_verbs:основать{}, // основать в пустыне новый город rus_verbs:двоить{}, // двоить в глазах rus_verbs:устоять{}, // устоять в лодке rus_verbs:унять{}, // унять в ногах дрожь rus_verbs:отзываться{}, // отзываться в обзоре rus_verbs:притормозить{}, // притормозить в траве rus_verbs:читаться{}, // читаться в глазах rus_verbs:житься{}, // житься в деревне rus_verbs:заиграть{}, // заиграть в жилах rus_verbs:шевелить{}, // шевелить в воде rus_verbs:зазвенеть{}, // зазвенеть в ушах rus_verbs:зависнуть{}, // зависнуть в библиотеке rus_verbs:затаить{}, // затаить в душе обиду rus_verbs:сознаться{}, // сознаться в совершении rus_verbs:протекать{}, // протекать в легкой форме rus_verbs:выясняться{}, // выясняться в ходе эксперимента rus_verbs:скрестить{}, // скрестить в неволе rus_verbs:наводить{}, // наводить в комнате порядок rus_verbs:значиться{}, // значиться в документах rus_verbs:заинтересовать{}, // заинтересовать в получении результатов rus_verbs:познакомить{}, // познакомить в непринужденной обстановке rus_verbs:рассеяться{}, // рассеяться в воздухе rus_verbs:грохнуть{}, // грохнуть в подвале rus_verbs:обвинять{}, // обвинять в вымогательстве rus_verbs:столпиться{}, // столпиться в фойе rus_verbs:порыться{}, // порыться в сумке rus_verbs:ослабить{}, // ослабить в верхней части rus_verbs:обнаруживаться{}, // обнаруживаться в кармане куртки rus_verbs:спастись{}, // спастись в хижине rus_verbs:прерваться{}, // прерваться в середине фразы rus_verbs:применять{}, // применять в повседневной работе rus_verbs:строиться{}, // строиться в зоне отчуждения rus_verbs:путешествовать{}, // путешествовать в самолете rus_verbs:побеждать{}, // побеждать в честной битве rus_verbs:погубить{}, // погубить в себе артиста rus_verbs:рассматриваться{}, // рассматриваться в следующей главе rus_verbs:продаваться{}, // продаваться в специализированном магазине rus_verbs:разместиться{}, // разместиться в аудитории rus_verbs:повидать{}, // повидать в жизни rus_verbs:настигнуть{}, // настигнуть в пригородах rus_verbs:сгрудиться{}, // сгрудиться в центре загона rus_verbs:укрыться{}, // укрыться в доме rus_verbs:расплакаться{}, // расплакаться в суде rus_verbs:пролежать{}, // пролежать в канаве rus_verbs:замерзнуть{}, // замерзнуть в ледяной воде rus_verbs:поскользнуться{}, // поскользнуться в коридоре rus_verbs:таскать{}, // таскать в руках rus_verbs:нападать{}, // нападать в вольере rus_verbs:просматривать{}, // просматривать в браузере rus_verbs:обдумать{}, // обдумать в дороге rus_verbs:обвинить{}, // обвинить в измене rus_verbs:останавливать{}, // останавливать в дверях rus_verbs:теряться{}, // теряться в догадках rus_verbs:погибать{}, // погибать в бою rus_verbs:обозначать{}, // обозначать в списке rus_verbs:запрещать{}, // запрещать в парке rus_verbs:долететь{}, // долететь в вертолёте rus_verbs:тесниться{}, // тесниться в каморке rus_verbs:уменьшаться{}, // уменьшаться в размере rus_verbs:издавать{}, // издавать в небольшом издательстве rus_verbs:хоронить{}, // хоронить в море rus_verbs:перемениться{}, // перемениться в лице rus_verbs:установиться{}, // установиться в северных областях rus_verbs:прикидывать{}, // прикидывать в уме rus_verbs:затаиться{}, // затаиться в траве rus_verbs:раздобыть{}, // раздобыть в аптеке rus_verbs:перебросить{}, // перебросить в товарном составе rus_verbs:погружаться{}, // погружаться в батискафе rus_verbs:поживать{}, // поживать в одиночестве rus_verbs:признаваться{}, // признаваться в любви rus_verbs:захватывать{}, // захватывать в здании rus_verbs:покачиваться{}, // покачиваться в лодке rus_verbs:крутиться{}, // крутиться в колесе rus_verbs:помещаться{}, // помещаться в ящике rus_verbs:питаться{}, // питаться в столовой rus_verbs:отдохнуть{}, // отдохнуть в пансионате rus_verbs:кататься{}, // кататься в коляске rus_verbs:поработать{}, // поработать в цеху rus_verbs:подразумевать{}, // подразумевать в задании rus_verbs:ограбить{}, // ограбить в подворотне rus_verbs:преуспеть{}, // преуспеть в бизнесе rus_verbs:заерзать{}, // заерзать в кресле rus_verbs:разъяснить{}, // разъяснить в другой статье rus_verbs:продвинуться{}, // продвинуться в изучении rus_verbs:поколебаться{}, // поколебаться в начале rus_verbs:засомневаться{}, // засомневаться в честности rus_verbs:приникнуть{}, // приникнуть в уме rus_verbs:скривить{}, // скривить в усмешке rus_verbs:рассечь{}, // рассечь в центре опухоли rus_verbs:перепутать{}, // перепутать в роддоме rus_verbs:посмеяться{}, // посмеяться в перерыве rus_verbs:отмечаться{}, // отмечаться в полицейском участке rus_verbs:накопиться{}, // накопиться в отстойнике rus_verbs:уносить{}, // уносить в руках rus_verbs:навещать{}, // навещать в больнице rus_verbs:остыть{}, // остыть в проточной воде rus_verbs:запереться{}, // запереться в комнате rus_verbs:обогнать{}, // обогнать в первом круге rus_verbs:убеждаться{}, // убеждаться в неизбежности rus_verbs:подбирать{}, // подбирать в магазине rus_verbs:уничтожать{}, // уничтожать в полете rus_verbs:путаться{}, // путаться в показаниях rus_verbs:притаиться{}, // притаиться в темноте rus_verbs:проплывать{}, // проплывать в лодке rus_verbs:засесть{}, // засесть в окопе rus_verbs:подцепить{}, // подцепить в баре rus_verbs:насчитать{}, // насчитать в диктанте несколько ошибок rus_verbs:оправдаться{}, // оправдаться в суде rus_verbs:созреть{}, // созреть в естественных условиях rus_verbs:раскрываться{}, // раскрываться в подходящих условиях rus_verbs:ожидаться{}, // ожидаться в верхней части rus_verbs:одеваться{}, // одеваться в дорогих бутиках rus_verbs:упрекнуть{}, // упрекнуть в недостатке опыта rus_verbs:грабить{}, // грабить в подворотне rus_verbs:ужинать{}, // ужинать в ресторане rus_verbs:гонять{}, // гонять в жилах rus_verbs:уверить{}, // уверить в безопасности rus_verbs:потеряться{}, // потеряться в лесу rus_verbs:устанавливаться{}, // устанавливаться в комнате rus_verbs:предоставлять{}, // предоставлять в суде rus_verbs:протянуться{}, // протянуться в стене rus_verbs:допрашивать{}, // допрашивать в бункере rus_verbs:проработать{}, // проработать в кабинете rus_verbs:сосредоточить{}, // сосредоточить в своих руках rus_verbs:утвердить{}, // утвердить в должности rus_verbs:сочинять{}, // сочинять в дороге rus_verbs:померкнуть{}, // померкнуть в глазах rus_verbs:показываться{}, // показываться в окошке rus_verbs:похудеть{}, // похудеть в талии rus_verbs:проделывать{}, // проделывать в стене rus_verbs:прославиться{}, // прославиться в интернете rus_verbs:сдохнуть{}, // сдохнуть в нищете rus_verbs:раскинуться{}, // раскинуться в степи rus_verbs:развить{}, // развить в себе способности rus_verbs:уставать{}, // уставать в цеху rus_verbs:укрепить{}, // укрепить в земле rus_verbs:числиться{}, // числиться в списке rus_verbs:образовывать{}, // образовывать в смеси rus_verbs:екнуть{}, // екнуть в груди rus_verbs:одобрять{}, // одобрять в своей речи rus_verbs:запить{}, // запить в одиночестве rus_verbs:забыться{}, // забыться в тяжелом сне rus_verbs:чернеть{}, // чернеть в кислой среде rus_verbs:размещаться{}, // размещаться в гараже rus_verbs:соорудить{}, // соорудить в гараже rus_verbs:развивать{}, // развивать в себе rus_verbs:пастись{}, // пастись в пойме rus_verbs:формироваться{}, // формироваться в верхних слоях атмосферы rus_verbs:ослабнуть{}, // ослабнуть в сочленении rus_verbs:таить{}, // таить в себе инфинитив:пробегать{ вид:несоверш }, глагол:пробегать{ вид:несоверш }, // пробегать в спешке rus_verbs:приостановиться{}, // приостановиться в конце rus_verbs:топтаться{}, // топтаться в грязи rus_verbs:громить{}, // громить в финале rus_verbs:заменять{}, // заменять в основном составе rus_verbs:подъезжать{}, // подъезжать в колясках rus_verbs:вычислить{}, // вычислить в уме rus_verbs:заказывать{}, // заказывать в магазине rus_verbs:осуществить{}, // осуществить в реальных условиях rus_verbs:обосноваться{}, // обосноваться в дупле rus_verbs:пытать{}, // пытать в камере rus_verbs:поменять{}, // поменять в магазине rus_verbs:совершиться{}, // совершиться в суде rus_verbs:пролетать{}, // пролетать в вертолете rus_verbs:сбыться{}, // сбыться во сне rus_verbs:разговориться{}, // разговориться в отделении rus_verbs:преподнести{}, // преподнести в красивой упаковке rus_verbs:напечатать{}, // напечатать в типографии rus_verbs:прорвать{}, // прорвать в центре rus_verbs:раскачиваться{}, // раскачиваться в кресле rus_verbs:задерживаться{}, // задерживаться в дверях rus_verbs:угощать{}, // угощать в кафе rus_verbs:проступать{}, // проступать в глубине rus_verbs:шарить{}, // шарить в математике rus_verbs:увеличивать{}, // увеличивать в конце rus_verbs:расцвести{}, // расцвести в оранжерее rus_verbs:закипеть{}, // закипеть в баке rus_verbs:подлететь{}, // подлететь в вертолете rus_verbs:рыться{}, // рыться в куче rus_verbs:пожить{}, // пожить в гостинице rus_verbs:добираться{}, // добираться в попутном транспорте rus_verbs:перекрыть{}, // перекрыть в коридоре rus_verbs:продержаться{}, // продержаться в барокамере rus_verbs:разыскивать{}, // разыскивать в толпе rus_verbs:освобождать{}, // освобождать в зале суда rus_verbs:подметить{}, // подметить в человеке rus_verbs:передвигаться{}, // передвигаться в узкой юбке rus_verbs:продумать{}, // продумать в уме rus_verbs:извиваться{}, // извиваться в траве rus_verbs:процитировать{}, // процитировать в статье rus_verbs:прогуливаться{}, // прогуливаться в парке rus_verbs:защемить{}, // защемить в двери rus_verbs:увеличиться{}, // увеличиться в объеме rus_verbs:проявиться{}, // проявиться в результатах rus_verbs:заскользить{}, // заскользить в ботинках rus_verbs:пересказать{}, // пересказать в своем выступлении rus_verbs:протестовать{}, // протестовать в здании парламента rus_verbs:указываться{}, // указываться в путеводителе rus_verbs:копошиться{}, // копошиться в песке rus_verbs:проигнорировать{}, // проигнорировать в своей работе rus_verbs:купаться{}, // купаться в речке rus_verbs:подсчитать{}, // подсчитать в уме rus_verbs:разволноваться{}, // разволноваться в классе rus_verbs:придумывать{}, // придумывать в своем воображении rus_verbs:предусмотреть{}, // предусмотреть в программе rus_verbs:завертеться{}, // завертеться в колесе rus_verbs:зачерпнуть{}, // зачерпнуть в ручье rus_verbs:очистить{}, // очистить в химической лаборатории rus_verbs:прозвенеть{}, // прозвенеть в коридорах rus_verbs:уменьшиться{}, // уменьшиться в размере rus_verbs:колыхаться{}, // колыхаться в проточной воде rus_verbs:ознакомиться{}, // ознакомиться в автобусе rus_verbs:ржать{}, // ржать в аудитории rus_verbs:раскинуть{}, // раскинуть в микрорайоне rus_verbs:разлиться{}, // разлиться в воде rus_verbs:сквозить{}, // сквозить в словах rus_verbs:задушить{}, // задушить в объятиях rus_verbs:осудить{}, // осудить в особом порядке rus_verbs:разгромить{}, // разгромить в честном поединке rus_verbs:подслушать{}, // подслушать в кулуарах rus_verbs:проповедовать{}, // проповедовать в сельских районах rus_verbs:озарить{}, // озарить во сне rus_verbs:потирать{}, // потирать в предвкушении rus_verbs:описываться{}, // описываться в статье rus_verbs:качаться{}, // качаться в кроватке rus_verbs:усилить{}, // усилить в центре rus_verbs:прохаживаться{}, // прохаживаться в новом костюме rus_verbs:полечить{}, // полечить в больничке rus_verbs:сниматься{}, // сниматься в римейке rus_verbs:сыскать{}, // сыскать в наших краях rus_verbs:поприветствовать{}, // поприветствовать в коридоре rus_verbs:подтвердиться{}, // подтвердиться в эксперименте rus_verbs:плескаться{}, // плескаться в теплой водичке rus_verbs:расширяться{}, // расширяться в первом сегменте rus_verbs:мерещиться{}, // мерещиться в тумане rus_verbs:сгущаться{}, // сгущаться в воздухе rus_verbs:храпеть{}, // храпеть во сне rus_verbs:подержать{}, // подержать в руках rus_verbs:накинуться{}, // накинуться в подворотне rus_verbs:планироваться{}, // планироваться в закрытом режиме rus_verbs:пробудить{}, // пробудить в себе rus_verbs:побриться{}, // побриться в ванной rus_verbs:сгинуть{}, // сгинуть в пучине rus_verbs:окрестить{}, // окрестить в церкви инфинитив:резюмировать{ вид:соверш }, глагол:резюмировать{ вид:соверш }, // резюмировать в конце выступления rus_verbs:замкнуться{}, // замкнуться в себе rus_verbs:прибавлять{}, // прибавлять в весе rus_verbs:проплыть{}, // проплыть в лодке rus_verbs:растворяться{}, // растворяться в тумане rus_verbs:упрекать{}, // упрекать в небрежности rus_verbs:затеряться{}, // затеряться в лабиринте rus_verbs:перечитывать{}, // перечитывать в поезде rus_verbs:перелететь{}, // перелететь в вертолете rus_verbs:оживать{}, // оживать в теплой воде rus_verbs:заглохнуть{}, // заглохнуть в полете rus_verbs:кольнуть{}, // кольнуть в боку rus_verbs:копаться{}, // копаться в куче rus_verbs:развлекаться{}, // развлекаться в клубе rus_verbs:отливать{}, // отливать в кустах rus_verbs:зажить{}, // зажить в деревне rus_verbs:одолжить{}, // одолжить в соседнем кабинете rus_verbs:заклинать{}, // заклинать в своей речи rus_verbs:различаться{}, // различаться в мелочах rus_verbs:печататься{}, // печататься в типографии rus_verbs:угадываться{}, // угадываться в контурах rus_verbs:обрывать{}, // обрывать в начале rus_verbs:поглаживать{}, // поглаживать в кармане rus_verbs:подписывать{}, // подписывать в присутствии понятых rus_verbs:добывать{}, // добывать в разломе rus_verbs:скопиться{}, // скопиться в воротах rus_verbs:повстречать{}, // повстречать в бане rus_verbs:совпасть{}, // совпасть в упрощенном виде rus_verbs:разрываться{}, // разрываться в точке спайки rus_verbs:улавливать{}, // улавливать в датчике rus_verbs:повстречаться{}, // повстречаться в лифте rus_verbs:отразить{}, // отразить в отчете rus_verbs:пояснять{}, // пояснять в примечаниях rus_verbs:накормить{}, // накормить в столовке rus_verbs:поужинать{}, // поужинать в ресторане инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть в суде инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш }, rus_verbs:топить{}, // топить в молоке rus_verbs:освоить{}, // освоить в работе rus_verbs:зародиться{}, // зародиться в голове rus_verbs:отплыть{}, // отплыть в старой лодке rus_verbs:отстаивать{}, // отстаивать в суде rus_verbs:осуждать{}, // осуждать в своем выступлении rus_verbs:переговорить{}, // переговорить в перерыве rus_verbs:разгораться{}, // разгораться в сердце rus_verbs:укрыть{}, // укрыть в шалаше rus_verbs:томиться{}, // томиться в застенках rus_verbs:клубиться{}, // клубиться в воздухе rus_verbs:сжигать{}, // сжигать в топке rus_verbs:позавтракать{}, // позавтракать в кафешке rus_verbs:функционировать{}, // функционировать в лабораторных условиях rus_verbs:смять{}, // смять в руке rus_verbs:разместить{}, // разместить в интернете rus_verbs:пронести{}, // пронести в потайном кармане rus_verbs:руководствоваться{}, // руководствоваться в работе rus_verbs:нашарить{}, // нашарить в потемках rus_verbs:закрутить{}, // закрутить в вихре rus_verbs:просматриваться{}, // просматриваться в дальней перспективе rus_verbs:распознать{}, // распознать в незнакомце rus_verbs:повеситься{}, // повеситься в камере rus_verbs:обшарить{}, // обшарить в поисках наркотиков rus_verbs:наполняться{}, // наполняется в карьере rus_verbs:засвистеть{}, // засвистеть в воздухе rus_verbs:процветать{}, // процветать в мягком климате rus_verbs:шуршать{}, // шуршать в простенке rus_verbs:подхватывать{}, // подхватывать в полете инфинитив:роиться{}, глагол:роиться{}, // роиться в воздухе прилагательное:роившийся{}, прилагательное:роящийся{}, // деепричастие:роясь{ aux stress="ро^ясь" }, rus_verbs:преобладать{}, // преобладать в тексте rus_verbs:посветлеть{}, // посветлеть в лице rus_verbs:игнорировать{}, // игнорировать в рекомендациях rus_verbs:обсуждаться{}, // обсуждаться в кулуарах rus_verbs:отказывать{}, // отказывать в визе rus_verbs:ощупывать{}, // ощупывать в кармане rus_verbs:разливаться{}, // разливаться в цеху rus_verbs:расписаться{}, // расписаться в получении rus_verbs:учинить{}, // учинить в казарме rus_verbs:плестись{}, // плестись в хвосте rus_verbs:объявляться{}, // объявляться в группе rus_verbs:повышаться{}, // повышаться в первой части rus_verbs:напрягать{}, // напрягать в паху rus_verbs:разрабатывать{}, // разрабатывать в студии rus_verbs:хлопотать{}, // хлопотать в мэрии rus_verbs:прерывать{}, // прерывать в самом начале rus_verbs:каяться{}, // каяться в грехах rus_verbs:освоиться{}, // освоиться в кабине rus_verbs:подплыть{}, // подплыть в лодке rus_verbs:замигать{}, // замигать в темноте rus_verbs:оскорблять{}, // оскорблять в выступлении rus_verbs:торжествовать{}, // торжествовать в душе rus_verbs:поправлять{}, // поправлять в прологе rus_verbs:угадывать{}, // угадывать в размытом изображении rus_verbs:потоптаться{}, // потоптаться в прихожей rus_verbs:переправиться{}, // переправиться в лодочке rus_verbs:увериться{}, // увериться в невиновности rus_verbs:забрезжить{}, // забрезжить в конце тоннеля rus_verbs:утвердиться{}, // утвердиться во мнении rus_verbs:завывать{}, // завывать в трубе rus_verbs:заварить{}, // заварить в заварнике rus_verbs:скомкать{}, // скомкать в руке rus_verbs:перемещаться{}, // перемещаться в капсуле инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться в первом поле rus_verbs:праздновать{}, // праздновать в баре rus_verbs:мигать{}, // мигать в темноте rus_verbs:обучить{}, // обучить в мастерской rus_verbs:орудовать{}, // орудовать в кладовке rus_verbs:упорствовать{}, // упорствовать в заблуждении rus_verbs:переминаться{}, // переминаться в прихожей rus_verbs:подрасти{}, // подрасти в теплице rus_verbs:предписываться{}, // предписываться в законе rus_verbs:приписать{}, // приписать в конце rus_verbs:задаваться{}, // задаваться в своей статье rus_verbs:чинить{}, // чинить в домашних условиях rus_verbs:раздеваться{}, // раздеваться в пляжной кабинке rus_verbs:пообедать{}, // пообедать в ресторанчике rus_verbs:жрать{}, // жрать в чуланчике rus_verbs:исполняться{}, // исполняться в антракте rus_verbs:гнить{}, // гнить в тюрьме rus_verbs:глодать{}, // глодать в конуре rus_verbs:прослушать{}, // прослушать в дороге rus_verbs:истратить{}, // истратить в кабаке rus_verbs:стареть{}, // стареть в одиночестве rus_verbs:разжечь{}, // разжечь в сердце rus_verbs:совещаться{}, // совещаться в кабинете rus_verbs:покачивать{}, // покачивать в кроватке rus_verbs:отсидеть{}, // отсидеть в одиночке rus_verbs:формировать{}, // формировать в умах rus_verbs:захрапеть{}, // захрапеть во сне rus_verbs:петься{}, // петься в хоре rus_verbs:объехать{}, // объехать в автобусе rus_verbs:поселить{}, // поселить в гостинице rus_verbs:предаться{}, // предаться в книге rus_verbs:заворочаться{}, // заворочаться во сне rus_verbs:напрятать{}, // напрятать в карманах rus_verbs:очухаться{}, // очухаться в незнакомом месте rus_verbs:ограничивать{}, // ограничивать в движениях rus_verbs:завертеть{}, // завертеть в руках rus_verbs:печатать{}, // печатать в редакторе rus_verbs:теплиться{}, // теплиться в сердце rus_verbs:увязнуть{}, // увязнуть в зыбучем песке rus_verbs:усмотреть{}, // усмотреть в обращении rus_verbs:отыскаться{}, // отыскаться в запасах rus_verbs:потушить{}, // потушить в горле огонь rus_verbs:поубавиться{}, // поубавиться в размере rus_verbs:зафиксировать{}, // зафиксировать в постоянной памяти rus_verbs:смыть{}, // смыть в ванной rus_verbs:заместить{}, // заместить в кресле rus_verbs:угасать{}, // угасать в одиночестве rus_verbs:сразить{}, // сразить в споре rus_verbs:фигурировать{}, // фигурировать в бюллетене rus_verbs:расплываться{}, // расплываться в глазах rus_verbs:сосчитать{}, // сосчитать в уме rus_verbs:сгуститься{}, // сгуститься в воздухе rus_verbs:цитировать{}, // цитировать в своей статье rus_verbs:помяться{}, // помяться в давке rus_verbs:затрагивать{}, // затрагивать в процессе выполнения rus_verbs:обтереть{}, // обтереть в гараже rus_verbs:подстрелить{}, // подстрелить в пойме реки rus_verbs:растереть{}, // растереть в руке rus_verbs:подавлять{}, // подавлять в зародыше rus_verbs:смешиваться{}, // смешиваться в чане инфинитив:вычитать{ вид:соверш }, глагол:вычитать{ вид:соверш }, // вычитать в книжечке rus_verbs:сократиться{}, // сократиться в обхвате rus_verbs:занервничать{}, // занервничать в кабинете rus_verbs:соприкоснуться{}, // соприкоснуться в полете rus_verbs:обозначить{}, // обозначить в объявлении rus_verbs:обучаться{}, // обучаться в училище rus_verbs:снизиться{}, // снизиться в нижних слоях атмосферы rus_verbs:лелеять{}, // лелеять в сердце rus_verbs:поддерживаться{}, // поддерживаться в суде rus_verbs:уплыть{}, // уплыть в лодочке rus_verbs:резвиться{}, // резвиться в саду rus_verbs:поерзать{}, // поерзать в гамаке rus_verbs:оплатить{}, // оплатить в ресторане rus_verbs:похвастаться{}, // похвастаться в компании rus_verbs:знакомиться{}, // знакомиться в классе rus_verbs:приплыть{}, // приплыть в подводной лодке rus_verbs:зажигать{}, // зажигать в классе rus_verbs:смыслить{}, // смыслить в математике rus_verbs:закопать{}, // закопать в огороде rus_verbs:порхать{}, // порхать в зарослях rus_verbs:потонуть{}, // потонуть в бумажках rus_verbs:стирать{}, // стирать в холодной воде rus_verbs:подстерегать{}, // подстерегать в придорожных кустах rus_verbs:погулять{}, // погулять в парке rus_verbs:предвкушать{}, // предвкушать в воображении rus_verbs:ошеломить{}, // ошеломить в бою rus_verbs:удостовериться{}, // удостовериться в безопасности rus_verbs:огласить{}, // огласить в заключительной части rus_verbs:разбогатеть{}, // разбогатеть в деревне rus_verbs:грохотать{}, // грохотать в мастерской rus_verbs:реализоваться{}, // реализоваться в должности rus_verbs:красть{}, // красть в магазине rus_verbs:нарваться{}, // нарваться в коридоре rus_verbs:застывать{}, // застывать в неудобной позе rus_verbs:толкаться{}, // толкаться в тесной комнате rus_verbs:извлекать{}, // извлекать в аппарате rus_verbs:обжигать{}, // обжигать в печи rus_verbs:запечатлеть{}, // запечатлеть в кинохронике rus_verbs:тренироваться{}, // тренироваться в зале rus_verbs:поспорить{}, // поспорить в кабинете rus_verbs:рыскать{}, // рыскать в лесу rus_verbs:надрываться{}, // надрываться в шахте rus_verbs:сняться{}, // сняться в фильме rus_verbs:закружить{}, // закружить в танце rus_verbs:затонуть{}, // затонуть в порту rus_verbs:побыть{}, // побыть в гостях rus_verbs:почистить{}, // почистить в носу rus_verbs:сгорбиться{}, // сгорбиться в тесной конуре rus_verbs:подслушивать{}, // подслушивать в классе rus_verbs:сгорать{}, // сгорать в танке rus_verbs:разочароваться{}, // разочароваться в артисте инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать в кустиках rus_verbs:мять{}, // мять в руках rus_verbs:подраться{}, // подраться в классе rus_verbs:замести{}, // замести в прихожей rus_verbs:откладываться{}, // откладываться в печени rus_verbs:обозначаться{}, // обозначаться в перечне rus_verbs:просиживать{}, // просиживать в интернете rus_verbs:соприкасаться{}, // соприкасаться в точке rus_verbs:начертить{}, // начертить в тетрадке rus_verbs:уменьшать{}, // уменьшать в поперечнике rus_verbs:тормозить{}, // тормозить в облаке rus_verbs:затевать{}, // затевать в лаборатории rus_verbs:затопить{}, // затопить в бухте rus_verbs:задерживать{}, // задерживать в лифте rus_verbs:прогуляться{}, // прогуляться в лесу rus_verbs:прорубить{}, // прорубить во льду rus_verbs:очищать{}, // очищать в кислоте rus_verbs:полулежать{}, // полулежать в гамаке rus_verbs:исправить{}, // исправить в задании rus_verbs:предусматриваться{}, // предусматриваться в постановке задачи rus_verbs:замучить{}, // замучить в плену rus_verbs:разрушаться{}, // разрушаться в верхней части rus_verbs:ерзать{}, // ерзать в кресле rus_verbs:покопаться{}, // покопаться в залежах rus_verbs:раскаяться{}, // раскаяться в содеянном rus_verbs:пробежаться{}, // пробежаться в парке rus_verbs:полежать{}, // полежать в гамаке rus_verbs:позаимствовать{}, // позаимствовать в книге rus_verbs:снижать{}, // снижать в несколько раз rus_verbs:черпать{}, // черпать в поэзии rus_verbs:заверять{}, // заверять в своей искренности rus_verbs:проглядеть{}, // проглядеть в сумерках rus_verbs:припарковать{}, // припарковать во дворе rus_verbs:сверлить{}, // сверлить в стене rus_verbs:здороваться{}, // здороваться в аудитории rus_verbs:рожать{}, // рожать в воде rus_verbs:нацарапать{}, // нацарапать в тетрадке rus_verbs:затопать{}, // затопать в коридоре rus_verbs:прописать{}, // прописать в правилах rus_verbs:сориентироваться{}, // сориентироваться в обстоятельствах rus_verbs:снизить{}, // снизить в несколько раз rus_verbs:заблуждаться{}, // заблуждаться в своей теории rus_verbs:откопать{}, // откопать в отвалах rus_verbs:смастерить{}, // смастерить в лаборатории rus_verbs:замедлиться{}, // замедлиться в парафине rus_verbs:избивать{}, // избивать в участке rus_verbs:мыться{}, // мыться в бане rus_verbs:сварить{}, // сварить в кастрюльке rus_verbs:раскопать{}, // раскопать в снегу rus_verbs:крепиться{}, // крепиться в держателе rus_verbs:дробить{}, // дробить в мельнице rus_verbs:попить{}, // попить в ресторанчике rus_verbs:затронуть{}, // затронуть в душе rus_verbs:лязгнуть{}, // лязгнуть в тишине rus_verbs:заправлять{}, // заправлять в полете rus_verbs:размножаться{}, // размножаться в неволе rus_verbs:потопить{}, // потопить в Тихом Океане rus_verbs:кушать{}, // кушать в столовой rus_verbs:замолкать{}, // замолкать в замешательстве rus_verbs:измеряться{}, // измеряться в дюймах rus_verbs:сбываться{}, // сбываться в мечтах rus_verbs:задернуть{}, // задернуть в комнате rus_verbs:затихать{}, // затихать в темноте rus_verbs:прослеживаться{}, // прослеживается в журнале rus_verbs:прерываться{}, // прерывается в начале rus_verbs:изображаться{}, // изображается в любых фильмах rus_verbs:фиксировать{}, // фиксировать в данной точке rus_verbs:ослаблять{}, // ослаблять в поясе rus_verbs:зреть{}, // зреть в теплице rus_verbs:зеленеть{}, // зеленеть в огороде rus_verbs:критиковать{}, // критиковать в статье rus_verbs:облететь{}, // облететь в частном вертолете rus_verbs:разбросать{}, // разбросать в комнате rus_verbs:заразиться{}, // заразиться в людном месте rus_verbs:рассеять{}, // рассеять в бою rus_verbs:печься{}, // печься в духовке rus_verbs:поспать{}, // поспать в палатке rus_verbs:заступиться{}, // заступиться в драке rus_verbs:сплетаться{}, // сплетаться в середине rus_verbs:поместиться{}, // поместиться в мешке rus_verbs:спереть{}, // спереть в лавке // инфинитив:ликвидировать{ вид:несоверш }, глагол:ликвидировать{ вид:несоверш }, // ликвидировать в пригороде // инфинитив:ликвидировать{ вид:соверш }, глагол:ликвидировать{ вид:соверш }, rus_verbs:проваляться{}, // проваляться в постели rus_verbs:лечиться{}, // лечиться в стационаре rus_verbs:определиться{}, // определиться в честном бою rus_verbs:обработать{}, // обработать в растворе rus_verbs:пробивать{}, // пробивать в стене rus_verbs:перемешаться{}, // перемешаться в чане rus_verbs:чесать{}, // чесать в паху rus_verbs:пролечь{}, // пролечь в пустынной местности rus_verbs:скитаться{}, // скитаться в дальних странах rus_verbs:затрудняться{}, // затрудняться в выборе rus_verbs:отряхнуться{}, // отряхнуться в коридоре rus_verbs:разыгрываться{}, // разыгрываться в лотерее rus_verbs:помолиться{}, // помолиться в церкви rus_verbs:предписывать{}, // предписывать в рецепте rus_verbs:порваться{}, // порваться в слабом месте rus_verbs:греться{}, // греться в здании rus_verbs:опровергать{}, // опровергать в своем выступлении rus_verbs:помянуть{}, // помянуть в своем выступлении rus_verbs:допросить{}, // допросить в прокуратуре rus_verbs:материализоваться{}, // материализоваться в соседнем здании rus_verbs:рассеиваться{}, // рассеиваться в воздухе rus_verbs:перевозить{}, // перевозить в вагоне rus_verbs:отбывать{}, // отбывать в тюрьме rus_verbs:попахивать{}, // попахивать в отхожем месте rus_verbs:перечислять{}, // перечислять в заключении rus_verbs:зарождаться{}, // зарождаться в дебрях rus_verbs:предъявлять{}, // предъявлять в своем письме rus_verbs:распространять{}, // распространять в сети rus_verbs:пировать{}, // пировать в соседнем селе rus_verbs:начертать{}, // начертать в летописи rus_verbs:расцветать{}, // расцветать в подходящих условиях rus_verbs:царствовать{}, // царствовать в южной части материка rus_verbs:накопить{}, // накопить в буфере rus_verbs:закрутиться{}, // закрутиться в рутине rus_verbs:отработать{}, // отработать в забое rus_verbs:обокрасть{}, // обокрасть в автобусе rus_verbs:прокладывать{}, // прокладывать в снегу rus_verbs:ковырять{}, // ковырять в носу rus_verbs:копить{}, // копить в очереди rus_verbs:полечь{}, // полечь в степях rus_verbs:щебетать{}, // щебетать в кустиках rus_verbs:подчеркиваться{}, // подчеркиваться в сообщении rus_verbs:посеять{}, // посеять в огороде rus_verbs:разъезжать{}, // разъезжать в кабриолете rus_verbs:замечаться{}, // замечаться в лесу rus_verbs:просчитать{}, // просчитать в уме rus_verbs:маяться{}, // маяться в командировке rus_verbs:выхватывать{}, // выхватывать в тексте rus_verbs:креститься{}, // креститься в деревенской часовне rus_verbs:обрабатывать{}, // обрабатывать в растворе кислоты rus_verbs:настигать{}, // настигать в огороде rus_verbs:разгуливать{}, // разгуливать в роще rus_verbs:насиловать{}, // насиловать в квартире rus_verbs:побороть{}, // побороть в себе rus_verbs:учитывать{}, // учитывать в расчетах rus_verbs:искажать{}, // искажать в заметке rus_verbs:пропить{}, // пропить в кабаке rus_verbs:катать{}, // катать в лодочке rus_verbs:припрятать{}, // припрятать в кармашке rus_verbs:запаниковать{}, // запаниковать в бою rus_verbs:рассыпать{}, // рассыпать в траве rus_verbs:застревать{}, // застревать в ограде rus_verbs:зажигаться{}, // зажигаться в сумерках rus_verbs:жарить{}, // жарить в масле rus_verbs:накапливаться{}, // накапливаться в костях rus_verbs:распуститься{}, // распуститься в горшке rus_verbs:проголосовать{}, // проголосовать в передвижном пункте rus_verbs:странствовать{}, // странствовать в автомобиле rus_verbs:осматриваться{}, // осматриваться в хоромах rus_verbs:разворачивать{}, // разворачивать в спортзале rus_verbs:заскучать{}, // заскучать в самолете rus_verbs:напутать{}, // напутать в расчете rus_verbs:перекусить{}, // перекусить в столовой rus_verbs:спасаться{}, // спасаться в автономной капсуле rus_verbs:посовещаться{}, // посовещаться в комнате rus_verbs:доказываться{}, // доказываться в статье rus_verbs:познаваться{}, // познаваться в беде rus_verbs:загрустить{}, // загрустить в одиночестве rus_verbs:оживить{}, // оживить в памяти rus_verbs:переворачиваться{}, // переворачиваться в гробу rus_verbs:заприметить{}, // заприметить в лесу rus_verbs:отравиться{}, // отравиться в забегаловке rus_verbs:продержать{}, // продержать в клетке rus_verbs:выявить{}, // выявить в костях rus_verbs:заседать{}, // заседать в совете rus_verbs:расплачиваться{}, // расплачиваться в первой кассе rus_verbs:проломить{}, // проломить в двери rus_verbs:подражать{}, // подражать в мелочах rus_verbs:подсчитывать{}, // подсчитывать в уме rus_verbs:опережать{}, // опережать во всем rus_verbs:сформироваться{}, // сформироваться в облаке rus_verbs:укрепиться{}, // укрепиться в мнении rus_verbs:отстоять{}, // отстоять в очереди rus_verbs:развертываться{}, // развертываться в месте испытания rus_verbs:замерзать{}, // замерзать во льду rus_verbs:утопать{}, // утопать в снегу rus_verbs:раскаиваться{}, // раскаиваться в содеянном rus_verbs:организовывать{}, // организовывать в пионерлагере rus_verbs:перевестись{}, // перевестись в наших краях rus_verbs:смешивать{}, // смешивать в блендере rus_verbs:ютиться{}, // ютиться в тесной каморке rus_verbs:прождать{}, // прождать в аудитории rus_verbs:подыскивать{}, // подыскивать в женском общежитии rus_verbs:замочить{}, // замочить в сортире rus_verbs:мерзнуть{}, // мерзнуть в тонкой курточке rus_verbs:растирать{}, // растирать в ступке rus_verbs:замедлять{}, // замедлять в парафине rus_verbs:переспать{}, // переспать в палатке rus_verbs:рассекать{}, // рассекать в кабриолете rus_verbs:отыскивать{}, // отыскивать в залежах rus_verbs:опровергнуть{}, // опровергнуть в своем выступлении rus_verbs:дрыхнуть{}, // дрыхнуть в гамаке rus_verbs:укрываться{}, // укрываться в землянке rus_verbs:запечься{}, // запечься в золе rus_verbs:догорать{}, // догорать в темноте rus_verbs:застилать{}, // застилать в коридоре rus_verbs:сыскаться{}, // сыскаться в деревне rus_verbs:переделать{}, // переделать в мастерской rus_verbs:разъяснять{}, // разъяснять в своей лекции rus_verbs:селиться{}, // селиться в центре rus_verbs:оплачивать{}, // оплачивать в магазине rus_verbs:переворачивать{}, // переворачивать в закрытой банке rus_verbs:упражняться{}, // упражняться в остроумии rus_verbs:пометить{}, // пометить в списке rus_verbs:припомниться{}, // припомниться в завещании rus_verbs:приютить{}, // приютить в амбаре rus_verbs:натерпеться{}, // натерпеться в темнице rus_verbs:затеваться{}, // затеваться в клубе rus_verbs:уплывать{}, // уплывать в лодке rus_verbs:скиснуть{}, // скиснуть в бидоне rus_verbs:заколоть{}, // заколоть в боку rus_verbs:замерцать{}, // замерцать в темноте rus_verbs:фиксироваться{}, // фиксироваться в протоколе rus_verbs:запираться{}, // запираться в комнате rus_verbs:съезжаться{}, // съезжаться в каретах rus_verbs:толочься{}, // толочься в ступе rus_verbs:потанцевать{}, // потанцевать в клубе rus_verbs:побродить{}, // побродить в парке rus_verbs:назревать{}, // назревать в коллективе rus_verbs:дохнуть{}, // дохнуть в питомнике rus_verbs:крестить{}, // крестить в деревенской церквушке rus_verbs:рассчитаться{}, // рассчитаться в банке rus_verbs:припарковаться{}, // припарковаться во дворе rus_verbs:отхватить{}, // отхватить в магазинчике rus_verbs:остывать{}, // остывать в холодильнике rus_verbs:составляться{}, // составляться в атмосфере тайны rus_verbs:переваривать{}, // переваривать в тишине rus_verbs:хвастать{}, // хвастать в казино rus_verbs:отрабатывать{}, // отрабатывать в теплице rus_verbs:разлечься{}, // разлечься в кровати rus_verbs:прокручивать{}, // прокручивать в голове rus_verbs:очертить{}, // очертить в воздухе rus_verbs:сконфузиться{}, // сконфузиться в окружении незнакомых людей rus_verbs:выявлять{}, // выявлять в боевых условиях rus_verbs:караулить{}, // караулить в лифте rus_verbs:расставлять{}, // расставлять в бойницах rus_verbs:прокрутить{}, // прокрутить в голове rus_verbs:пересказывать{}, // пересказывать в первой главе rus_verbs:задавить{}, // задавить в зародыше rus_verbs:хозяйничать{}, // хозяйничать в холодильнике rus_verbs:хвалиться{}, // хвалиться в детском садике rus_verbs:оперировать{}, // оперировать в полевом госпитале rus_verbs:формулировать{}, // формулировать в следующей главе rus_verbs:застигнуть{}, // застигнуть в неприглядном виде rus_verbs:замурлыкать{}, // замурлыкать в тепле rus_verbs:поддакивать{}, // поддакивать в споре rus_verbs:прочертить{}, // прочертить в воздухе rus_verbs:отменять{}, // отменять в городе коменданский час rus_verbs:колдовать{}, // колдовать в лаборатории rus_verbs:отвозить{}, // отвозить в машине rus_verbs:трахать{}, // трахать в гамаке rus_verbs:повозиться{}, // повозиться в мешке rus_verbs:ремонтировать{}, // ремонтировать в центре rus_verbs:робеть{}, // робеть в гостях rus_verbs:перепробовать{}, // перепробовать в деле инфинитив:реализовать{ вид:соверш }, инфинитив:реализовать{ вид:несоверш }, // реализовать в новой версии глагол:реализовать{ вид:соверш }, глагол:реализовать{ вид:несоверш }, rus_verbs:покаяться{}, // покаяться в церкви rus_verbs:попрыгать{}, // попрыгать в бассейне rus_verbs:умалчивать{}, // умалчивать в своем докладе rus_verbs:ковыряться{}, // ковыряться в старой технике rus_verbs:расписывать{}, // расписывать в деталях rus_verbs:вязнуть{}, // вязнуть в песке rus_verbs:погрязнуть{}, // погрязнуть в скандалах rus_verbs:корениться{}, // корениться в неспособности выполнить поставленную задачу rus_verbs:зажимать{}, // зажимать в углу rus_verbs:стискивать{}, // стискивать в ладонях rus_verbs:практиковаться{}, // практиковаться в приготовлении соуса rus_verbs:израсходовать{}, // израсходовать в полете rus_verbs:клокотать{}, // клокотать в жерле rus_verbs:обвиняться{}, // обвиняться в растрате rus_verbs:уединиться{}, // уединиться в кладовке rus_verbs:подохнуть{}, // подохнуть в болоте rus_verbs:кипятиться{}, // кипятиться в чайнике rus_verbs:уродиться{}, // уродиться в лесу rus_verbs:продолжиться{}, // продолжиться в баре rus_verbs:расшифровать{}, // расшифровать в специальном устройстве rus_verbs:посапывать{}, // посапывать в кровати rus_verbs:скрючиться{}, // скрючиться в мешке rus_verbs:лютовать{}, // лютовать в отдаленных селах rus_verbs:расписать{}, // расписать в статье rus_verbs:публиковаться{}, // публиковаться в научном журнале rus_verbs:зарегистрировать{}, // зарегистрировать в комитете rus_verbs:прожечь{}, // прожечь в листе rus_verbs:переждать{}, // переждать в окопе rus_verbs:публиковать{}, // публиковать в журнале rus_verbs:морщить{}, // морщить в уголках глаз rus_verbs:спиться{}, // спиться в одиночестве rus_verbs:изведать{}, // изведать в гареме rus_verbs:обмануться{}, // обмануться в ожиданиях rus_verbs:сочетать{}, // сочетать в себе rus_verbs:подрабатывать{}, // подрабатывать в магазине rus_verbs:репетировать{}, // репетировать в студии rus_verbs:рябить{}, // рябить в глазах rus_verbs:намочить{}, // намочить в луже rus_verbs:скатать{}, // скатать в руке rus_verbs:одевать{}, // одевать в магазине rus_verbs:испечь{}, // испечь в духовке rus_verbs:сбрить{}, // сбрить в подмышках rus_verbs:зажужжать{}, // зажужжать в ухе rus_verbs:сберечь{}, // сберечь в тайном месте rus_verbs:согреться{}, // согреться в хижине инфинитив:дебютировать{ вид:несоверш }, инфинитив:дебютировать{ вид:соверш }, // дебютировать в спектакле глагол:дебютировать{ вид:несоверш }, глагол:дебютировать{ вид:соверш }, rus_verbs:переплыть{}, // переплыть в лодочке rus_verbs:передохнуть{}, // передохнуть в тени rus_verbs:отсвечивать{}, // отсвечивать в зеркалах rus_verbs:переправляться{}, // переправляться в лодках rus_verbs:накупить{}, // накупить в магазине rus_verbs:проторчать{}, // проторчать в очереди rus_verbs:проскальзывать{}, // проскальзывать в сообщениях rus_verbs:застукать{}, // застукать в солярии rus_verbs:наесть{}, // наесть в отпуске rus_verbs:подвизаться{}, // подвизаться в новом деле rus_verbs:вычистить{}, // вычистить в саду rus_verbs:кормиться{}, // кормиться в лесу rus_verbs:покурить{}, // покурить в саду rus_verbs:понизиться{}, // понизиться в ранге rus_verbs:зимовать{}, // зимовать в избушке rus_verbs:проверяться{}, // проверяться в службе безопасности rus_verbs:подпирать{}, // подпирать в первом забое rus_verbs:кувыркаться{}, // кувыркаться в постели rus_verbs:похрапывать{}, // похрапывать в постели rus_verbs:завязнуть{}, // завязнуть в песке rus_verbs:трактовать{}, // трактовать в исследовательской статье rus_verbs:замедляться{}, // замедляться в тяжелой воде rus_verbs:шастать{}, // шастать в здании rus_verbs:заночевать{}, // заночевать в пути rus_verbs:наметиться{}, // наметиться в исследованиях рака rus_verbs:освежить{}, // освежить в памяти rus_verbs:оспаривать{}, // оспаривать в суде rus_verbs:умещаться{}, // умещаться в ячейке rus_verbs:искупить{}, // искупить в бою rus_verbs:отсиживаться{}, // отсиживаться в тылу rus_verbs:мчать{}, // мчать в кабриолете rus_verbs:обличать{}, // обличать в своем выступлении rus_verbs:сгнить{}, // сгнить в тюряге rus_verbs:опробовать{}, // опробовать в деле rus_verbs:тренировать{}, // тренировать в зале rus_verbs:прославить{}, // прославить в академии rus_verbs:учитываться{}, // учитываться в дипломной работе rus_verbs:повеселиться{}, // повеселиться в лагере rus_verbs:поумнеть{}, // поумнеть в карцере rus_verbs:перестрелять{}, // перестрелять в воздухе rus_verbs:проведать{}, // проведать в больнице rus_verbs:измучиться{}, // измучиться в деревне rus_verbs:прощупать{}, // прощупать в глубине rus_verbs:изготовлять{}, // изготовлять в сарае rus_verbs:свирепствовать{}, // свирепствовать в популяции rus_verbs:иссякать{}, // иссякать в источнике rus_verbs:гнездиться{}, // гнездиться в дупле rus_verbs:разогнаться{}, // разогнаться в спортивной машине rus_verbs:опознавать{}, // опознавать в неизвестном rus_verbs:засвидетельствовать{}, // засвидетельствовать в суде rus_verbs:сконцентрировать{}, // сконцентрировать в своих руках rus_verbs:редактировать{}, // редактировать в редакторе rus_verbs:покупаться{}, // покупаться в магазине rus_verbs:промышлять{}, // промышлять в роще rus_verbs:растягиваться{}, // растягиваться в коридоре rus_verbs:приобретаться{}, // приобретаться в антикварных лавках инфинитив:подрезать{ вид:несоверш }, инфинитив:подрезать{ вид:соверш }, // подрезать в воде глагол:подрезать{ вид:несоверш }, глагол:подрезать{ вид:соверш }, rus_verbs:запечатлеться{}, // запечатлеться в мозгу rus_verbs:укрывать{}, // укрывать в подвале rus_verbs:закрепиться{}, // закрепиться в первой башне rus_verbs:освежать{}, // освежать в памяти rus_verbs:громыхать{}, // громыхать в ванной инфинитив:подвигаться{ вид:соверш }, инфинитив:подвигаться{ вид:несоверш }, // подвигаться в кровати глагол:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:несоверш }, rus_verbs:добываться{}, // добываться в шахтах rus_verbs:растворить{}, // растворить в кислоте rus_verbs:приплясывать{}, // приплясывать в гримерке rus_verbs:доживать{}, // доживать в доме престарелых rus_verbs:отпраздновать{}, // отпраздновать в ресторане rus_verbs:сотрясаться{}, // сотрясаться в конвульсиях rus_verbs:помыть{}, // помыть в проточной воде инфинитив:увязать{ вид:несоверш }, инфинитив:увязать{ вид:соверш }, // увязать в песке глагол:увязать{ вид:несоверш }, глагол:увязать{ вид:соверш }, прилагательное:увязавший{ вид:несоверш }, rus_verbs:наличествовать{}, // наличествовать в запаснике rus_verbs:нащупывать{}, // нащупывать в кармане rus_verbs:повествоваться{}, // повествоваться в рассказе rus_verbs:отремонтировать{}, // отремонтировать в техцентре rus_verbs:покалывать{}, // покалывать в правом боку rus_verbs:сиживать{}, // сиживать в саду rus_verbs:разрабатываться{}, // разрабатываться в секретных лабораториях rus_verbs:укрепляться{}, // укрепляться в мнении rus_verbs:разниться{}, // разниться во взглядах rus_verbs:сполоснуть{}, // сполоснуть в водичке rus_verbs:скупать{}, // скупать в магазине rus_verbs:почесывать{}, // почесывать в паху rus_verbs:оформлять{}, // оформлять в конторе rus_verbs:распускаться{}, // распускаться в садах rus_verbs:зарябить{}, // зарябить в глазах rus_verbs:загореть{}, // загореть в Испании rus_verbs:очищаться{}, // очищаться в баке rus_verbs:остудить{}, // остудить в холодной воде rus_verbs:разбомбить{}, // разбомбить в горах rus_verbs:издохнуть{}, // издохнуть в бедности rus_verbs:проехаться{}, // проехаться в новой машине rus_verbs:задействовать{}, // задействовать в анализе rus_verbs:произрастать{}, // произрастать в степи rus_verbs:разуться{}, // разуться в прихожей rus_verbs:сооружать{}, // сооружать в огороде rus_verbs:зачитывать{}, // зачитывать в суде rus_verbs:состязаться{}, // состязаться в остроумии rus_verbs:ополоснуть{}, // ополоснуть в молоке rus_verbs:уместиться{}, // уместиться в кармане rus_verbs:совершенствоваться{}, // совершенствоваться в управлении мотоциклом rus_verbs:стираться{}, // стираться в стиральной машине rus_verbs:искупаться{}, // искупаться в прохладной реке rus_verbs:курировать{}, // курировать в правительстве rus_verbs:закупить{}, // закупить в магазине rus_verbs:плодиться{}, // плодиться в подходящих условиях rus_verbs:горланить{}, // горланить в парке rus_verbs:першить{}, // першить в горле rus_verbs:пригрезиться{}, // пригрезиться во сне rus_verbs:исправлять{}, // исправлять в тетрадке rus_verbs:расслабляться{}, // расслабляться в гамаке rus_verbs:скапливаться{}, // скапливаться в нижней части rus_verbs:сплетничать{}, // сплетничают в комнате rus_verbs:раздевать{}, // раздевать в кабинке rus_verbs:окопаться{}, // окопаться в лесу rus_verbs:загорать{}, // загорать в Испании rus_verbs:подпевать{}, // подпевать в церковном хоре rus_verbs:прожужжать{}, // прожужжать в динамике rus_verbs:изучаться{}, // изучаться в дикой природе rus_verbs:заклубиться{}, // заклубиться в воздухе rus_verbs:подметать{}, // подметать в зале rus_verbs:подозреваться{}, // подозреваться в совершении кражи rus_verbs:обогащать{}, // обогащать в специальном аппарате rus_verbs:издаться{}, // издаться в другом издательстве rus_verbs:справить{}, // справить в кустах нужду rus_verbs:помыться{}, // помыться в бане rus_verbs:проскакивать{}, // проскакивать в словах rus_verbs:попивать{}, // попивать в кафе чай rus_verbs:оформляться{}, // оформляться в регистратуре rus_verbs:чирикать{}, // чирикать в кустах rus_verbs:скупить{}, // скупить в магазинах rus_verbs:переночевать{}, // переночевать в гостинице rus_verbs:концентрироваться{}, // концентрироваться в пробирке rus_verbs:одичать{}, // одичать в лесу rus_verbs:ковырнуть{}, // ковырнуть в ухе rus_verbs:затеплиться{}, // затеплиться в глубине души rus_verbs:разгрести{}, // разгрести в задачах залежи rus_verbs:застопориться{}, // застопориться в начале списка rus_verbs:перечисляться{}, // перечисляться во введении rus_verbs:покататься{}, // покататься в парке аттракционов rus_verbs:изловить{}, // изловить в поле rus_verbs:прославлять{}, // прославлять в стихах rus_verbs:промочить{}, // промочить в луже rus_verbs:поделывать{}, // поделывать в отпуске rus_verbs:просуществовать{}, // просуществовать в первобытном состоянии rus_verbs:подстеречь{}, // подстеречь в подъезде rus_verbs:прикупить{}, // прикупить в магазине rus_verbs:перемешивать{}, // перемешивать в кастрюле rus_verbs:тискать{}, // тискать в углу rus_verbs:купать{}, // купать в теплой водичке rus_verbs:завариться{}, // завариться в стакане rus_verbs:притулиться{}, // притулиться в углу rus_verbs:пострелять{}, // пострелять в тире rus_verbs:навесить{}, // навесить в больнице инфинитив:изолировать{ вид:соверш }, инфинитив:изолировать{ вид:несоверш }, // изолировать в камере глагол:изолировать{ вид:соверш }, глагол:изолировать{ вид:несоверш }, rus_verbs:нежиться{}, // нежится в постельке rus_verbs:притомиться{}, // притомиться в школе rus_verbs:раздвоиться{}, // раздвоиться в глазах rus_verbs:навалить{}, // навалить в углу rus_verbs:замуровать{}, // замуровать в склепе rus_verbs:поселяться{}, // поселяться в кроне дуба rus_verbs:потягиваться{}, // потягиваться в кровати rus_verbs:укачать{}, // укачать в поезде rus_verbs:отлеживаться{}, // отлеживаться в гамаке rus_verbs:разменять{}, // разменять в кассе rus_verbs:прополоскать{}, // прополоскать в чистой теплой воде rus_verbs:ржаветь{}, // ржаветь в воде rus_verbs:уличить{}, // уличить в плагиате rus_verbs:мутиться{}, // мутиться в голове rus_verbs:растворять{}, // растворять в бензоле rus_verbs:двоиться{}, // двоиться в глазах rus_verbs:оговорить{}, // оговорить в договоре rus_verbs:подделать{}, // подделать в документе rus_verbs:зарегистрироваться{}, // зарегистрироваться в социальной сети rus_verbs:растолстеть{}, // растолстеть в талии rus_verbs:повоевать{}, // повоевать в городских условиях rus_verbs:прибраться{}, // гнушаться прибраться в хлеву rus_verbs:поглощаться{}, // поглощаться в металлической фольге rus_verbs:ухать{}, // ухать в лесу rus_verbs:подписываться{}, // подписываться в петиции rus_verbs:покатать{}, // покатать в машинке rus_verbs:излечиться{}, // излечиться в клинике rus_verbs:трепыхаться{}, // трепыхаться в мешке rus_verbs:кипятить{}, // кипятить в кастрюле rus_verbs:понастроить{}, // понастроить в прибрежной зоне rus_verbs:перебывать{}, // перебывать во всех европейских столицах rus_verbs:оглашать{}, // оглашать в итоговой части rus_verbs:преуспевать{}, // преуспевать в новом бизнесе rus_verbs:консультироваться{}, // консультироваться в техподдержке rus_verbs:накапливать{}, // накапливать в печени rus_verbs:перемешать{}, // перемешать в контейнере rus_verbs:наследить{}, // наследить в коридоре rus_verbs:выявиться{}, // выявиться в результе rus_verbs:забулькать{}, // забулькать в болоте rus_verbs:отваривать{}, // отваривать в молоке rus_verbs:запутываться{}, // запутываться в веревках rus_verbs:нагреться{}, // нагреться в микроволновой печке rus_verbs:рыбачить{}, // рыбачить в открытом море rus_verbs:укорениться{}, // укорениться в сознании широких народных масс rus_verbs:умывать{}, // умывать в тазике rus_verbs:защекотать{}, // защекотать в носу rus_verbs:заходиться{}, // заходиться в плаче инфинитив:искупать{ вид:соверш }, инфинитив:искупать{ вид:несоверш }, // искупать в прохладной водичке глагол:искупать{ вид:соверш }, глагол:искупать{ вид:несоверш }, деепричастие:искупав{}, деепричастие:искупая{}, rus_verbs:заморозить{}, // заморозить в холодильнике rus_verbs:закреплять{}, // закреплять в металлическом держателе rus_verbs:расхватать{}, // расхватать в магазине rus_verbs:истязать{}, // истязать в тюремном подвале rus_verbs:заржаветь{}, // заржаветь во влажной атмосфере rus_verbs:обжаривать{}, // обжаривать в подсолнечном масле rus_verbs:умереть{}, // Ты, подлый предатель, умрешь в нищете rus_verbs:подогреть{}, // подогрей в микроволновке rus_verbs:подогревать{}, rus_verbs:затянуть{}, // Кузнечики, сверчки, скрипачи и медведки затянули в траве свою трескучую музыку rus_verbs:проделать{}, // проделать в стене дыру инфинитив:жениться{ вид:соверш }, // жениться в Техасе инфинитив:жениться{ вид:несоверш }, глагол:жениться{ вид:соверш }, глагол:жениться{ вид:несоверш }, деепричастие:женившись{}, деепричастие:женясь{}, прилагательное:женатый{}, прилагательное:женившийся{вид:соверш}, прилагательное:женящийся{}, rus_verbs:всхрапнуть{}, // всхрапнуть во сне rus_verbs:всхрапывать{}, // всхрапывать во сне rus_verbs:ворочаться{}, // Собака ворочается во сне rus_verbs:воссоздаваться{}, // воссоздаваться в памяти rus_verbs:акклиматизироваться{}, // альпинисты готовятся акклиматизироваться в горах инфинитив:атаковать{ вид:несоверш }, // взвод был атакован в лесу инфинитив:атаковать{ вид:соверш }, глагол:атаковать{ вид:несоверш }, глагол:атаковать{ вид:соверш }, прилагательное:атакованный{}, прилагательное:атаковавший{}, прилагательное:атакующий{}, инфинитив:аккумулировать{вид:несоверш}, // энергия была аккумулирована в печени инфинитив:аккумулировать{вид:соверш}, глагол:аккумулировать{вид:несоверш}, глагол:аккумулировать{вид:соверш}, прилагательное:аккумулированный{}, прилагательное:аккумулирующий{}, //прилагательное:аккумулировавший{ вид:несоверш }, прилагательное:аккумулировавший{ вид:соверш }, rus_verbs:врисовывать{}, // врисовывать нового персонажа в анимацию rus_verbs:вырасти{}, // Он вырос в глазах коллег. rus_verbs:иметь{}, // Он всегда имел в резерве острое словцо. rus_verbs:убить{}, // убить в себе зверя инфинитив:абсорбироваться{ вид:соверш }, // жидкость абсорбируется в поглощающей ткани инфинитив:абсорбироваться{ вид:несоверш }, глагол:абсорбироваться{ вид:соверш }, глагол:абсорбироваться{ вид:несоверш }, rus_verbs:поставить{}, // поставить в углу rus_verbs:сжимать{}, // сжимать в кулаке rus_verbs:готовиться{}, // альпинисты готовятся акклиматизироваться в горах rus_verbs:аккумулироваться{}, // энергия аккумулируется в жировых отложениях инфинитив:активизироваться{ вид:несоверш }, // в горах активизировались повстанцы инфинитив:активизироваться{ вид:соверш }, глагол:активизироваться{ вид:несоверш }, глагол:активизироваться{ вид:соверш }, rus_verbs:апробировать{}, // пилот апробировал в ходе испытаний новый режим планера rus_verbs:арестовать{}, // наркодилер был арестован в помещении кафе rus_verbs:базировать{}, // установка будет базирована в лесу rus_verbs:барахтаться{}, // дети барахтались в воде rus_verbs:баррикадироваться{}, // преступники баррикадируются в помещении банка rus_verbs:барствовать{}, // Семен Семенович барствовал в своей деревне rus_verbs:бесчинствовать{}, // Боевики бесчинствовали в захваченном селе rus_verbs:блаженствовать{}, // Воробьи блаженствовали в кроне рябины rus_verbs:блуждать{}, // Туристы блуждали в лесу rus_verbs:брать{}, // Жена берет деньги в тумбочке rus_verbs:бродить{}, // парочки бродили в парке rus_verbs:обойти{}, // Бразилия обошла Россию в рейтинге rus_verbs:задержать{}, // Знаменитый советский фигурист задержан в США rus_verbs:бултыхаться{}, // Ноги бултыхаются в воде rus_verbs:вариться{}, // Курица варится в кастрюле rus_verbs:закончиться{}, // Эта рецессия закончилась в 2003 году rus_verbs:прокручиваться{}, // Ключ прокручивается в замке rus_verbs:прокрутиться{}, // Ключ трижды прокрутился в замке rus_verbs:храниться{}, // Настройки хранятся в текстовом файле rus_verbs:сохраняться{}, // Настройки сохраняются в текстовом файле rus_verbs:витать{}, // Мальчик витает в облаках rus_verbs:владычествовать{}, // Король владычествует в стране rus_verbs:властвовать{}, // Олигархи властвовали в стране rus_verbs:возбудить{}, // возбудить в сердце тоску rus_verbs:возбуждать{}, // возбуждать в сердце тоску rus_verbs:возвыситься{}, // возвыситься в глазах современников rus_verbs:возжечь{}, // возжечь в храме огонь rus_verbs:возжечься{}, // Огонь возжёгся в храме rus_verbs:возжигать{}, // возжигать в храме огонь rus_verbs:возжигаться{}, // Огонь возжигается в храме rus_verbs:вознамериваться{}, // вознамериваться уйти в монастырь rus_verbs:вознамериться{}, // вознамериться уйти в монастырь rus_verbs:возникать{}, // Новые идеи неожиданно возникают в колиной голове rus_verbs:возникнуть{}, // Новые идейки возникли в голове rus_verbs:возродиться{}, // возродиться в новом качестве rus_verbs:возрождать{}, // возрождать в новом качестве rus_verbs:возрождаться{}, // возрождаться в новом амплуа rus_verbs:ворошить{}, // ворошить в камине кочергой золу rus_verbs:воспевать{}, // Поэты воспевают героев в одах rus_verbs:воспеваться{}, // Герои воспеваются в одах поэтами rus_verbs:воспеть{}, // Поэты воспели в этой оде героев rus_verbs:воспретить{}, // воспретить в помещении азартные игры rus_verbs:восславить{}, // Поэты восславили в одах rus_verbs:восславлять{}, // Поэты восславляют в одах rus_verbs:восславляться{}, // Героя восславляются в одах rus_verbs:воссоздать{}, // воссоздает в памяти образ человека rus_verbs:воссоздавать{}, // воссоздать в памяти образ человека rus_verbs:воссоздаться{}, // воссоздаться в памяти rus_verbs:вскипятить{}, // вскипятить в чайнике воду rus_verbs:вскипятиться{}, // вскипятиться в чайнике rus_verbs:встретить{}, // встретить в классе старого приятеля rus_verbs:встретиться{}, // встретиться в классе rus_verbs:встречать{}, // встречать в лесу голодного медведя rus_verbs:встречаться{}, // встречаться в кафе rus_verbs:выбривать{}, // выбривать что-то в подмышках rus_verbs:выбрить{}, // выбрить что-то в паху rus_verbs:вывалять{}, // вывалять кого-то в грязи rus_verbs:вываляться{}, // вываляться в грязи rus_verbs:вываривать{}, // вываривать в молоке rus_verbs:вывариваться{}, // вывариваться в молоке rus_verbs:выварить{}, // выварить в молоке rus_verbs:вывариться{}, // вывариться в молоке rus_verbs:выгрызать{}, // выгрызать в сыре отверствие rus_verbs:выгрызть{}, // выгрызть в сыре отверстие rus_verbs:выгуливать{}, // выгуливать в парке собаку rus_verbs:выгулять{}, // выгулять в парке собаку rus_verbs:выдолбить{}, // выдолбить в стволе углубление rus_verbs:выжить{}, // выжить в пустыне rus_verbs:Выискать{}, // Выискать в программе ошибку rus_verbs:выискаться{}, // Ошибка выискалась в программе rus_verbs:выискивать{}, // выискивать в программе ошибку rus_verbs:выискиваться{}, // выискиваться в программе rus_verbs:выкраивать{}, // выкраивать в расписании время rus_verbs:выкраиваться{}, // выкраиваться в расписании инфинитив:выкупаться{aux stress="в^ыкупаться"}, // выкупаться в озере глагол:выкупаться{вид:соверш}, rus_verbs:выловить{}, // выловить в пруду rus_verbs:вымачивать{}, // вымачивать в молоке rus_verbs:вымачиваться{}, // вымачиваться в молоке rus_verbs:вынюхивать{}, // вынюхивать в траве следы rus_verbs:выпачкать{}, // выпачкать в смоле свою одежду rus_verbs:выпачкаться{}, // выпачкаться в грязи rus_verbs:вырастить{}, // вырастить в теплице ведро огурчиков rus_verbs:выращивать{}, // выращивать в теплице помидоры rus_verbs:выращиваться{}, // выращиваться в теплице rus_verbs:вырыть{}, // вырыть в земле глубокую яму rus_verbs:высадить{}, // высадить в пустынной местности rus_verbs:высадиться{}, // высадиться в пустынной местности rus_verbs:высаживать{}, // высаживать в пустыне rus_verbs:высверливать{}, // высверливать в доске отверствие rus_verbs:высверливаться{}, // высверливаться в стене rus_verbs:высверлить{}, // высверлить в стене отверствие rus_verbs:высверлиться{}, // высверлиться в стене rus_verbs:выскоблить{}, // выскоблить в столешнице канавку rus_verbs:высматривать{}, // высматривать в темноте rus_verbs:заметить{}, // заметить в помещении rus_verbs:оказаться{}, // оказаться в первых рядах rus_verbs:душить{}, // душить в объятиях rus_verbs:оставаться{}, // оставаться в классе rus_verbs:появиться{}, // впервые появиться в фильме rus_verbs:лежать{}, // лежать в футляре rus_verbs:раздаться{}, // раздаться в плечах rus_verbs:ждать{}, // ждать в здании вокзала rus_verbs:жить{}, // жить в трущобах rus_verbs:постелить{}, // постелить в прихожей rus_verbs:оказываться{}, // оказываться в неприятной ситуации rus_verbs:держать{}, // держать в голове rus_verbs:обнаружить{}, // обнаружить в себе способность rus_verbs:начинать{}, // начинать в лаборатории rus_verbs:рассказывать{}, // рассказывать в лицах rus_verbs:ожидать{}, // ожидать в помещении rus_verbs:продолжить{}, // продолжить в помещении rus_verbs:состоять{}, // состоять в группе rus_verbs:родиться{}, // родиться в рубашке rus_verbs:искать{}, // искать в кармане rus_verbs:иметься{}, // иметься в наличии rus_verbs:говориться{}, // говориться в среде панков rus_verbs:клясться{}, // клясться в верности rus_verbs:узнавать{}, // узнавать в нем своего сына rus_verbs:признаться{}, // признаться в ошибке rus_verbs:сомневаться{}, // сомневаться в искренности rus_verbs:толочь{}, // толочь в ступе rus_verbs:понадобиться{}, // понадобиться в суде rus_verbs:служить{}, // служить в пехоте rus_verbs:потолочь{}, // потолочь в ступе rus_verbs:появляться{}, // появляться в театре rus_verbs:сжать{}, // сжать в объятиях rus_verbs:действовать{}, // действовать в постановке rus_verbs:селить{}, // селить в гостинице rus_verbs:поймать{}, // поймать в лесу rus_verbs:увидать{}, // увидать в толпе rus_verbs:подождать{}, // подождать в кабинете rus_verbs:прочесть{}, // прочесть в глазах rus_verbs:тонуть{}, // тонуть в реке rus_verbs:ощущать{}, // ощущать в животе rus_verbs:ошибиться{}, // ошибиться в расчетах rus_verbs:отметить{}, // отметить в списке rus_verbs:показывать{}, // показывать в динамике rus_verbs:скрыться{}, // скрыться в траве rus_verbs:убедиться{}, // убедиться в корректности rus_verbs:прозвучать{}, // прозвучать в наушниках rus_verbs:разговаривать{}, // разговаривать в фойе rus_verbs:издать{}, // издать в России rus_verbs:прочитать{}, // прочитать в газете rus_verbs:попробовать{}, // попробовать в деле rus_verbs:замечать{}, // замечать в программе ошибку rus_verbs:нести{}, // нести в руках rus_verbs:пропасть{}, // пропасть в плену rus_verbs:носить{}, // носить в кармане rus_verbs:гореть{}, // гореть в аду rus_verbs:поправить{}, // поправить в программе rus_verbs:застыть{}, // застыть в неудобной позе rus_verbs:получать{}, // получать в кассе rus_verbs:потребоваться{}, // потребоваться в работе rus_verbs:спрятать{}, // спрятать в шкафу rus_verbs:учиться{}, // учиться в институте rus_verbs:развернуться{}, // развернуться в коридоре rus_verbs:подозревать{}, // подозревать в мошенничестве rus_verbs:играть{}, // играть в команде rus_verbs:сыграть{}, // сыграть в команде rus_verbs:строить{}, // строить в деревне rus_verbs:устроить{}, // устроить в доме вечеринку rus_verbs:находить{}, // находить в лесу rus_verbs:нуждаться{}, // нуждаться в деньгах rus_verbs:испытать{}, // испытать в рабочей обстановке rus_verbs:мелькнуть{}, // мелькнуть в прицеле rus_verbs:очутиться{}, // очутиться в закрытом помещении инфинитив:использовать{вид:соверш}, // использовать в работе инфинитив:использовать{вид:несоверш}, глагол:использовать{вид:несоверш}, глагол:использовать{вид:соверш}, rus_verbs:лететь{}, // лететь в самолете rus_verbs:смеяться{}, // смеяться в цирке rus_verbs:ездить{}, // ездить в лимузине rus_verbs:заснуть{}, // заснуть в неудобной позе rus_verbs:застать{}, // застать в неформальной обстановке rus_verbs:очнуться{}, // очнуться в незнакомой обстановке rus_verbs:твориться{}, // Что творится в закрытой зоне rus_verbs:разглядеть{}, // разглядеть в темноте rus_verbs:изучать{}, // изучать в естественных условиях rus_verbs:удержаться{}, // удержаться в седле rus_verbs:побывать{}, // побывать в зоопарке rus_verbs:уловить{}, // уловить в словах нотку отчаяния rus_verbs:приобрести{}, // приобрести в лавке rus_verbs:исчезать{}, // исчезать в тумане rus_verbs:уверять{}, // уверять в своей невиновности rus_verbs:продолжаться{}, // продолжаться в воздухе rus_verbs:открывать{}, // открывать в городе новый стадион rus_verbs:поддержать{}, // поддержать в парке порядок rus_verbs:солить{}, // солить в бочке rus_verbs:прожить{}, // прожить в деревне rus_verbs:создавать{}, // создавать в театре rus_verbs:обсуждать{}, // обсуждать в коллективе rus_verbs:заказать{}, // заказать в магазине rus_verbs:отыскать{}, // отыскать в гараже rus_verbs:уснуть{}, // уснуть в кресле rus_verbs:задержаться{}, // задержаться в театре rus_verbs:подобрать{}, // подобрать в коллекции rus_verbs:пробовать{}, // пробовать в работе rus_verbs:курить{}, // курить в закрытом помещении rus_verbs:устраивать{}, // устраивать в лесу засаду rus_verbs:установить{}, // установить в багажнике rus_verbs:запереть{}, // запереть в сарае rus_verbs:содержать{}, // содержать в достатке rus_verbs:синеть{}, // синеть в кислородной атмосфере rus_verbs:слышаться{}, // слышаться в голосе rus_verbs:закрыться{}, // закрыться в здании rus_verbs:скрываться{}, // скрываться в квартире rus_verbs:родить{}, // родить в больнице rus_verbs:описать{}, // описать в заметках rus_verbs:перехватить{}, // перехватить в коридоре rus_verbs:менять{}, // менять в магазине rus_verbs:скрывать{}, // скрывать в чужой квартире rus_verbs:стиснуть{}, // стиснуть в стальных объятиях rus_verbs:останавливаться{}, // останавливаться в гостинице rus_verbs:мелькать{}, // мелькать в телевизоре rus_verbs:присутствовать{}, // присутствовать в аудитории rus_verbs:украсть{}, // украсть в магазине rus_verbs:победить{}, // победить в войне rus_verbs:расположиться{}, // расположиться в гостинице rus_verbs:упомянуть{}, // упомянуть в своей книге rus_verbs:плыть{}, // плыть в старой бочке rus_verbs:нащупать{}, // нащупать в глубине rus_verbs:проявляться{}, // проявляться в работе rus_verbs:затихнуть{}, // затихнуть в норе rus_verbs:построить{}, // построить в гараже rus_verbs:поддерживать{}, // поддерживать в исправном состоянии rus_verbs:заработать{}, // заработать в стартапе rus_verbs:сломать{}, // сломать в суставе rus_verbs:снимать{}, // снимать в гардеробе rus_verbs:сохранить{}, // сохранить в коллекции rus_verbs:располагаться{}, // располагаться в отдельном кабинете rus_verbs:сражаться{}, // сражаться в честном бою rus_verbs:спускаться{}, // спускаться в батискафе rus_verbs:уничтожить{}, // уничтожить в схроне rus_verbs:изучить{}, // изучить в естественных условиях rus_verbs:рождаться{}, // рождаться в муках rus_verbs:пребывать{}, // пребывать в прострации rus_verbs:прилететь{}, // прилететь в аэробусе rus_verbs:догнать{}, // догнать в переулке rus_verbs:изобразить{}, // изобразить в танце rus_verbs:проехать{}, // проехать в легковушке rus_verbs:убедить{}, // убедить в разумности rus_verbs:приготовить{}, // приготовить в духовке rus_verbs:собирать{}, // собирать в лесу rus_verbs:поплыть{}, // поплыть в катере rus_verbs:доверять{}, // доверять в управлении rus_verbs:разобраться{}, // разобраться в законах rus_verbs:ловить{}, // ловить в озере rus_verbs:проесть{}, // проесть в куске металла отверстие rus_verbs:спрятаться{}, // спрятаться в подвале rus_verbs:провозгласить{}, // провозгласить в речи rus_verbs:изложить{}, // изложить в своём выступлении rus_verbs:замяться{}, // замяться в коридоре rus_verbs:раздаваться{}, // Крик ягуара раздается в джунглях rus_verbs:доказать{}, // Автор доказал в своей работе, что теорема верна rus_verbs:хранить{}, // хранить в шкатулке rus_verbs:шутить{}, // шутить в классе глагол:рассыпаться{ aux stress="рассып^аться" }, // рассыпаться в извинениях инфинитив:рассыпаться{ aux stress="рассып^аться" }, rus_verbs:чертить{}, // чертить в тетрадке rus_verbs:отразиться{}, // отразиться в аттестате rus_verbs:греть{}, // греть в микроволновке rus_verbs:зарычать{}, // Кто-то зарычал в глубине леса rus_verbs:рассуждать{}, // Автор рассуждает в своей статье rus_verbs:освободить{}, // Обвиняемые были освобождены в зале суда rus_verbs:окружать{}, // окружать в лесу rus_verbs:сопровождать{}, // сопровождать в операции rus_verbs:заканчиваться{}, // заканчиваться в дороге rus_verbs:поселиться{}, // поселиться в загородном доме rus_verbs:охватывать{}, // охватывать в хронологии rus_verbs:запеть{}, // запеть в кино инфинитив:провозить{вид:несоверш}, // провозить в багаже глагол:провозить{вид:несоверш}, rus_verbs:мочить{}, // мочить в сортире rus_verbs:перевернуться{}, // перевернуться в полёте rus_verbs:улететь{}, // улететь в теплые края rus_verbs:сдержать{}, // сдержать в руках rus_verbs:преследовать{}, // преследовать в любой другой стране rus_verbs:драться{}, // драться в баре rus_verbs:просидеть{}, // просидеть в классе rus_verbs:убираться{}, // убираться в квартире rus_verbs:содрогнуться{}, // содрогнуться в приступе отвращения rus_verbs:пугать{}, // пугать в прессе rus_verbs:отреагировать{}, // отреагировать в прессе rus_verbs:проверять{}, // проверять в аппарате rus_verbs:убеждать{}, // убеждать в отсутствии альтернатив rus_verbs:летать{}, // летать в комфортабельном частном самолёте rus_verbs:толпиться{}, // толпиться в фойе rus_verbs:плавать{}, // плавать в специальном костюме rus_verbs:пробыть{}, // пробыть в воде слишком долго rus_verbs:прикинуть{}, // прикинуть в уме rus_verbs:застрять{}, // застрять в лифте rus_verbs:метаться{}, // метаться в кровате rus_verbs:сжечь{}, // сжечь в печке rus_verbs:расслабиться{}, // расслабиться в ванной rus_verbs:услыхать{}, // услыхать в автобусе rus_verbs:удержать{}, // удержать в вертикальном положении rus_verbs:образоваться{}, // образоваться в верхних слоях атмосферы rus_verbs:рассмотреть{}, // рассмотреть в капле воды rus_verbs:просмотреть{}, // просмотреть в браузере rus_verbs:учесть{}, // учесть в планах rus_verbs:уезжать{}, // уезжать в чьей-то машине rus_verbs:похоронить{}, // похоронить в мерзлой земле rus_verbs:растянуться{}, // растянуться в расслабленной позе rus_verbs:обнаружиться{}, // обнаружиться в чужой сумке rus_verbs:гулять{}, // гулять в парке rus_verbs:утонуть{}, // утонуть в реке rus_verbs:зажать{}, // зажать в медвежьих объятиях rus_verbs:усомниться{}, // усомниться в объективности rus_verbs:танцевать{}, // танцевать в спортзале rus_verbs:проноситься{}, // проноситься в голове rus_verbs:трудиться{}, // трудиться в кооперативе глагол:засыпать{ aux stress="засып^ать" переходность:непереходный }, // засыпать в спальном мешке инфинитив:засыпать{ aux stress="засып^ать" переходность:непереходный }, rus_verbs:сушить{}, // сушить в сушильном шкафу rus_verbs:зашевелиться{}, // зашевелиться в траве rus_verbs:обдумывать{}, // обдумывать в спокойной обстановке rus_verbs:промелькнуть{}, // промелькнуть в окне rus_verbs:поучаствовать{}, // поучаствовать в обсуждении rus_verbs:закрыть{}, // закрыть в комнате rus_verbs:запирать{}, // запирать в комнате rus_verbs:закрывать{}, // закрывать в доме rus_verbs:заблокировать{}, // заблокировать в доме rus_verbs:зацвести{}, // В садах зацвела сирень rus_verbs:кричать{}, // Какое-то животное кричало в ночном лесу. rus_verbs:поглотить{}, // фотон, поглощенный в рецепторе rus_verbs:стоять{}, // войска, стоявшие в Риме rus_verbs:закалить{}, // ветераны, закаленные в боях rus_verbs:выступать{}, // пришлось выступать в тюрьме. rus_verbs:выступить{}, // пришлось выступить в тюрьме. rus_verbs:закопошиться{}, // Мыши закопошились в траве rus_verbs:воспламениться{}, // смесь, воспламенившаяся в цилиндре rus_verbs:воспламеняться{}, // смесь, воспламеняющаяся в цилиндре rus_verbs:закрываться{}, // закрываться в комнате rus_verbs:провалиться{}, // провалиться в прокате деепричастие:авторизируясь{ вид:несоверш }, глагол:авторизироваться{ вид:несоверш }, инфинитив:авторизироваться{ вид:несоверш }, // авторизироваться в системе rus_verbs:существовать{}, // существовать в вакууме деепричастие:находясь{}, прилагательное:находившийся{}, прилагательное:находящийся{}, глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, // находиться в вакууме rus_verbs:регистрировать{}, // регистрировать в инспекции глагол:перерегистрировать{ вид:несоверш }, глагол:перерегистрировать{ вид:соверш }, инфинитив:перерегистрировать{ вид:несоверш }, инфинитив:перерегистрировать{ вид:соверш }, // перерегистрировать в инспекции rus_verbs:поковыряться{}, // поковыряться в носу rus_verbs:оттаять{}, // оттаять в кипятке rus_verbs:распинаться{}, // распинаться в проклятиях rus_verbs:отменить{}, // Министерство связи предлагает отменить внутренний роуминг в России rus_verbs:столкнуться{}, // Американский эсминец и японский танкер столкнулись в Персидском заливе rus_verbs:ценить{}, // Он очень ценил в статьях краткость изложения. прилагательное:несчастный{}, // Он очень несчастен в семейной жизни. rus_verbs:объясниться{}, // Он объяснился в любви. прилагательное:нетвердый{}, // Он нетвёрд в истории. rus_verbs:заниматься{}, // Он занимается в читальном зале. rus_verbs:вращаться{}, // Он вращается в учёных кругах. прилагательное:спокойный{}, // Он был спокоен и уверен в завтрашнем дне. rus_verbs:бегать{}, // Он бегал по городу в поисках квартиры. rus_verbs:заключать{}, // Письмо заключало в себе очень важные сведения. rus_verbs:срабатывать{}, // Алгоритм срабатывает в половине случаев. rus_verbs:специализироваться{}, // мы специализируемся в создании ядерного оружия rus_verbs:сравниться{}, // Никто не может сравниться с ним в знаниях. rus_verbs:продолжать{}, // Продолжайте в том же духе. rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц. rus_verbs:болтать{}, // Не болтай в присутствии начальника! rus_verbs:проболтаться{}, // Не проболтайся в присутствии начальника! rus_verbs:повторить{}, // Он должен повторить свои показания в присутствии свидетелей rus_verbs:получить{}, // ректор поздравил студентов, получивших в этом семестре повышенную стипендию rus_verbs:приобретать{}, // Эту еду мы приобретаем в соседнем магазине. rus_verbs:расходиться{}, // Маша и Петя расходятся во взглядах rus_verbs:сходиться{}, // Все дороги сходятся в Москве rus_verbs:убирать{}, // убирать в комнате rus_verbs:удостоверяться{}, // он удостоверяется в личности специалиста rus_verbs:уединяться{}, // уединяться в пустыне rus_verbs:уживаться{}, // уживаться в одном коллективе rus_verbs:укорять{}, // укорять друга в забывчивости rus_verbs:читать{}, // он читал об этом в журнале rus_verbs:состояться{}, // В Израиле состоятся досрочные парламентские выборы rus_verbs:погибнуть{}, // Список погибших в авиакатастрофе под Ярославлем rus_verbs:работать{}, // Я работаю в театре. rus_verbs:признать{}, // Я признал в нём старого друга. rus_verbs:преподавать{}, // Я преподаю в университете. rus_verbs:понимать{}, // Я плохо понимаю в живописи. rus_verbs:водиться{}, // неизвестный науке зверь, который водится в жарких тропических лесах rus_verbs:разразиться{}, // В Москве разразилась эпидемия гриппа rus_verbs:замереть{}, // вся толпа замерла в восхищении rus_verbs:сидеть{}, // Я люблю сидеть в этом удобном кресле. rus_verbs:идти{}, // Я иду в неопределённом направлении. rus_verbs:заболеть{}, // Я заболел в дороге. rus_verbs:ехать{}, // Я еду в автобусе rus_verbs:взять{}, // Я взял книгу в библиотеке на неделю. rus_verbs:провести{}, // Юные годы он провёл в Италии. rus_verbs:вставать{}, // Этот случай живо встаёт в моей памяти. rus_verbs:возвысить{}, // Это событие возвысило его в общественном мнении. rus_verbs:произойти{}, // Это произошло в одном городе в Японии. rus_verbs:привидеться{}, // Это мне привиделось во сне. rus_verbs:держаться{}, // Это дело держится в большом секрете. rus_verbs:привиться{}, // Это выражение не привилось в русском языке. rus_verbs:восстановиться{}, // Эти писатели восстановились в правах. rus_verbs:быть{}, // Эта книга есть в любом книжном магазине. прилагательное:популярный{}, // Эта идея очень популярна в массах. rus_verbs:шуметь{}, // Шумит в голове. rus_verbs:остаться{}, // Шляпа осталась в поезде. rus_verbs:выражаться{}, // Характер писателя лучше всего выражается в его произведениях. rus_verbs:воспитать{}, // Учительница воспитала в детях любовь к природе. rus_verbs:пересохнуть{}, // У меня в горле пересохло. rus_verbs:щекотать{}, // У меня в горле щекочет. rus_verbs:колоть{}, // У меня в боку колет. прилагательное:свежий{}, // Событие ещё свежо в памяти. rus_verbs:собрать{}, // Соберите всех учеников во дворе. rus_verbs:белеть{}, // Снег белеет в горах. rus_verbs:сделать{}, // Сколько орфографических ошибок ты сделал в диктанте? rus_verbs:таять{}, // Сахар тает в кипятке. rus_verbs:жать{}, // Сапог жмёт в подъёме. rus_verbs:возиться{}, // Ребята возятся в углу. rus_verbs:распоряжаться{}, // Прошу не распоряжаться в чужом доме. rus_verbs:кружиться{}, // Они кружились в вальсе. rus_verbs:выставлять{}, // Они выставляют его в смешном виде. rus_verbs:бывать{}, // Она часто бывает в обществе. rus_verbs:петь{}, // Она поёт в опере. rus_verbs:сойтись{}, // Все свидетели сошлись в своих показаниях. rus_verbs:валяться{}, // Вещи валялись в беспорядке. rus_verbs:пройти{}, // Весь день прошёл в беготне. rus_verbs:продавать{}, // В этом магазине продают обувь. rus_verbs:заключаться{}, // В этом заключается вся сущность. rus_verbs:звенеть{}, // В ушах звенит. rus_verbs:проступить{}, // В тумане проступили очертания корабля. rus_verbs:бить{}, // В саду бьёт фонтан. rus_verbs:проскользнуть{}, // В речи проскользнул упрёк. rus_verbs:оставить{}, // Не оставь товарища в опасности. rus_verbs:прогулять{}, // Мы прогуляли час в парке. rus_verbs:перебить{}, // Мы перебили врагов в бою. rus_verbs:остановиться{}, // Мы остановились в первой попавшейся гостинице. rus_verbs:видеть{}, // Он многое видел в жизни. // глагол:проходить{ вид:несоверш }, // Беседа проходила в дружественной атмосфере. rus_verbs:подать{}, // Автор подал своих героев в реалистических тонах. rus_verbs:кинуть{}, // Он кинул меня в беде. rus_verbs:приходить{}, // Приходи в сентябре rus_verbs:воскрешать{}, // воскрешать в памяти rus_verbs:соединять{}, // соединять в себе rus_verbs:разбираться{}, // умение разбираться в вещах rus_verbs:делать{}, // В её комнате делали обыск. rus_verbs:воцариться{}, // В зале воцарилась глубокая тишина. rus_verbs:начаться{}, // В деревне начались полевые работы. rus_verbs:блеснуть{}, // В голове блеснула хорошая мысль. rus_verbs:вертеться{}, // В голове вертится вчерашний разговор. rus_verbs:веять{}, // В воздухе веет прохладой. rus_verbs:висеть{}, // В воздухе висит зной. rus_verbs:носиться{}, // В воздухе носятся комары. rus_verbs:грести{}, // Грести в спокойной воде будет немного легче, но скучнее rus_verbs:воскресить{}, // воскресить в памяти rus_verbs:поплавать{}, // поплавать в 100-метровом бассейне rus_verbs:пострадать{}, // В массовой драке пострадал 23-летний мужчина прилагательное:уверенный{ причастие }, // Она уверена в своих силах. прилагательное:постоянный{}, // Она постоянна во вкусах. прилагательное:сильный{}, // Он не силён в математике. прилагательное:повинный{}, // Он не повинен в этом. прилагательное:возможный{}, // Ураганы, сильные грозы и даже смерчи возможны в конце периода сильной жары rus_verbs:вывести{}, // способный летать над землей крокодил был выведен в секретной лаборатории прилагательное:нужный{}, // сковородка тоже нужна в хозяйстве. rus_verbs:сесть{}, // Она села в тени rus_verbs:заливаться{}, // в нашем парке заливаются соловьи rus_verbs:разнести{}, // В лесу огонь пожара мгновенно разнесло rus_verbs:чувствоваться{}, // В тёплом, но сыром воздухе остро чувствовалось дыхание осени // rus_verbs:расти{}, // дерево, растущее в лесу rus_verbs:происходить{}, // что происходит в поликлиннике rus_verbs:спать{}, // кто спит в моей кровати rus_verbs:мыть{}, // мыть машину в саду ГЛ_ИНФ(царить), // В воздухе царило безмолвие ГЛ_ИНФ(мести), // мести в прихожей пол ГЛ_ИНФ(прятать), // прятать в яме ГЛ_ИНФ(увидеть), прилагательное:увидевший{}, деепричастие:увидев{}, // увидел периодическую таблицу элементов во сне. // ГЛ_ИНФ(собраться), // собраться в порту ГЛ_ИНФ(случиться), // что-то случилось в больнице ГЛ_ИНФ(зажечься), // в небе зажглись звёзды ГЛ_ИНФ(купить), // купи молока в магазине прилагательное:пропагандировавшийся{} // группа студентов университета дружбы народов, активно пропагандировавшейся в СССР } // Чтобы разрешить связывание в паттернах типа: пообедать в macdonalds fact гл_предл { if context { Гл_В_Предл предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_В_Предл предлог:в{} *:*{ падеж:предл } } then return true } // С локативом: // собраться в порту fact гл_предл { if context { Гл_В_Предл предлог:в{} существительное:*{ падеж:мест } } then return true } #endregion Предложный #region Винительный // Для глаголов движения с выраженным направлением действия может присоединяться // предложный паттерн с винительным падежом. wordentry_set Гл_В_Вин = { rus_verbs:вдавиться{}, // Дуло больно вдавилось в позвонок. глагол:ввергнуть{}, // Двух прелестнейших дам он ввергнул в горе. глагол:ввергать{}, инфинитив:ввергнуть{}, инфинитив:ввергать{}, rus_verbs:двинуться{}, // Двинулись в путь и мы. rus_verbs:сплавать{}, // Сплавать в Россию! rus_verbs:уложиться{}, // Уложиться в воскресенье. rus_verbs:спешить{}, // Спешите в Лондон rus_verbs:кинуть{}, // Киньте в море. rus_verbs:проситься{}, // Просилась в Никарагуа. rus_verbs:притопать{}, // Притопал в Будапешт. rus_verbs:скататься{}, // Скатался в Красноярск. rus_verbs:соскользнуть{}, // Соскользнул в пике. rus_verbs:соскальзывать{}, rus_verbs:играть{}, // Играл в дутье. глагол:айда{}, // Айда в каморы. rus_verbs:отзывать{}, // Отзывали в Москву... rus_verbs:сообщаться{}, // Сообщается в Лондон. rus_verbs:вдуматься{}, // Вдумайтесь в них. rus_verbs:проехать{}, // Проехать в Лунево... rus_verbs:спрыгивать{}, // Спрыгиваем в него. rus_verbs:верить{}, // Верю в вас! rus_verbs:прибыть{}, // Прибыл в Подмосковье. rus_verbs:переходить{}, // Переходите в школу. rus_verbs:доложить{}, // Доложили в Москву. rus_verbs:подаваться{}, // Подаваться в Россию? rus_verbs:спрыгнуть{}, // Спрыгнул в него. rus_verbs:вывезти{}, // Вывезли в Китай. rus_verbs:пропихивать{}, // Я очень аккуратно пропихивал дуло в ноздрю. rus_verbs:пропихнуть{}, rus_verbs:транспортироваться{}, rus_verbs:закрадываться{}, // в голову начали закрадываться кое-какие сомнения и подозрения rus_verbs:дуть{}, rus_verbs:БОГАТЕТЬ{}, // rus_verbs:РАЗБОГАТЕТЬ{}, // rus_verbs:ВОЗРАСТАТЬ{}, // rus_verbs:ВОЗРАСТИ{}, // rus_verbs:ПОДНЯТЬ{}, // Он поднял половинку самолета в воздух и на всей скорости повел ее к горам. (ПОДНЯТЬ) rus_verbs:ОТКАТИТЬСЯ{}, // Услышав за спиной дыхание, он прыгнул вперед и откатился в сторону, рассчитывая ускользнуть от врага, нападавшего сзади (ОТКАТИТЬСЯ) rus_verbs:ВПЛЕТАТЬСЯ{}, // В общий смрад вплеталось зловонье пены, летевшей из пастей, и крови из легких (ВПЛЕТАТЬСЯ) rus_verbs:ЗАМАНИТЬ{}, // Они подумали, что Павел пытается заманить их в зону обстрела. (ЗАМАНИТЬ,ЗАМАНИВАТЬ) rus_verbs:ЗАМАНИВАТЬ{}, rus_verbs:ПРОТРУБИТЬ{}, // Эти врата откроются, когда он протрубит в рог, и пропустят его в другую вселенную. (ПРОТРУБИТЬ) rus_verbs:ВРУБИТЬСЯ{}, // Клинок сломался, не врубившись в металл. (ВРУБИТЬСЯ/ВРУБАТЬСЯ) rus_verbs:ВРУБАТЬСЯ{}, rus_verbs:ОТПРАВИТЬ{}, // Мы ищем благородного вельможу, который нанял бы нас или отправил в рыцарский поиск. (ОТПРАВИТЬ) rus_verbs:ОБЛАЧИТЬ{}, // Этот был облачен в сверкавшие красные доспехи с опущенным забралом и держал огромное копье, дожидаясь своей очереди. (ОБЛАЧИТЬ/ОБЛАЧАТЬ/ОБЛАЧИТЬСЯ/ОБЛАЧАТЬСЯ/НАРЯДИТЬСЯ/НАРЯЖАТЬСЯ) rus_verbs:ОБЛАЧАТЬ{}, rus_verbs:ОБЛАЧИТЬСЯ{}, rus_verbs:ОБЛАЧАТЬСЯ{}, rus_verbs:НАРЯДИТЬСЯ{}, rus_verbs:НАРЯЖАТЬСЯ{}, rus_verbs:ЗАХВАТИТЬ{}, // Кроме набранного рабского материала обычного типа, он захватил в плен группу очень странных созданий, а также женщину исключительной красоты (ЗАХВАТИТЬ/ЗАХВАТЫВАТЬ/ЗАХВАТ) rus_verbs:ЗАХВАТЫВАТЬ{}, rus_verbs:ПРОВЕСТИ{}, // Он провел их в маленькое святилище позади штурвала. (ПРОВЕСТИ) rus_verbs:ПОЙМАТЬ{}, // Их можно поймать в ловушку (ПОЙМАТЬ) rus_verbs:СТРОИТЬСЯ{}, // На вершине они остановились, строясь в круг. (СТРОИТЬСЯ,ПОСТРОИТЬСЯ,ВЫСТРОИТЬСЯ) rus_verbs:ПОСТРОИТЬСЯ{}, rus_verbs:ВЫСТРОИТЬСЯ{}, rus_verbs:ВЫПУСТИТЬ{}, // Несколько стрел, выпущенных в преследуемых, вонзились в траву (ВЫПУСТИТЬ/ВЫПУСКАТЬ) rus_verbs:ВЫПУСКАТЬ{}, rus_verbs:ВЦЕПЛЯТЬСЯ{}, // Они вцепляются тебе в горло. (ВЦЕПЛЯТЬСЯ/ВЦЕПИТЬСЯ) rus_verbs:ВЦЕПИТЬСЯ{}, rus_verbs:ПАЛЬНУТЬ{}, // Вольф вставил в тетиву новую стрелу и пальнул в белое брюхо (ПАЛЬНУТЬ) rus_verbs:ОТСТУПИТЬ{}, // Вольф отступил в щель. (ОТСТУПИТЬ/ОТСТУПАТЬ) rus_verbs:ОТСТУПАТЬ{}, rus_verbs:КРИКНУТЬ{}, // Вольф крикнул в ответ и медленно отступил от птицы. (КРИКНУТЬ) rus_verbs:ДЫХНУТЬ{}, // В лицо ему дыхнули винным перегаром. (ДЫХНУТЬ) rus_verbs:ПОТРУБИТЬ{}, // Я видел рог во время своих скитаний по дворцу и даже потрубил в него (ПОТРУБИТЬ) rus_verbs:ОТКРЫВАТЬСЯ{}, // Некоторые врата открывались в другие вселенные (ОТКРЫВАТЬСЯ) rus_verbs:ТРУБИТЬ{}, // А я трубил в рог (ТРУБИТЬ) rus_verbs:ПЫРНУТЬ{}, // Вольф пырнул его в бок. (ПЫРНУТЬ) rus_verbs:ПРОСКРЕЖЕТАТЬ{}, // Тот что-то проскрежетал в ответ, а затем наорал на него. (ПРОСКРЕЖЕТАТЬ В вин, НАОРАТЬ НА вин) rus_verbs:ИМПОРТИРОВАТЬ{}, // импортировать товары двойного применения только в Российскую Федерацию (ИМПОРТИРОВАТЬ) rus_verbs:ОТЪЕХАТЬ{}, // Легкий грохот катков заглушил рог, когда дверь отъехала в сторону. (ОТЪЕХАТЬ) rus_verbs:ПОПЛЕСТИСЬ{}, // Подобрав нижнее белье, носки и ботинки, он поплелся по песку обратно в джунгли. (ПОПЛЕЛСЯ) rus_verbs:СЖАТЬСЯ{}, // Желудок у него сжался в кулак. (СЖАТЬСЯ, СЖИМАТЬСЯ) rus_verbs:СЖИМАТЬСЯ{}, rus_verbs:проверять{}, // Школьников будут принудительно проверять на курение rus_verbs:ПОТЯНУТЬ{}, // Я потянул его в кино (ПОТЯНУТЬ) rus_verbs:ПЕРЕВЕСТИ{}, // Премьер-министр Казахстана поручил до конца года перевести все социально-значимые услуги в электронный вид (ПЕРЕВЕСТИ) rus_verbs:КРАСИТЬ{}, // Почему китайские партийные боссы красят волосы в черный цвет? (КРАСИТЬ/ПОКРАСИТЬ/ПЕРЕКРАСИТЬ/ОКРАСИТЬ/ЗАКРАСИТЬ) rus_verbs:ПОКРАСИТЬ{}, // rus_verbs:ПЕРЕКРАСИТЬ{}, // rus_verbs:ОКРАСИТЬ{}, // rus_verbs:ЗАКРАСИТЬ{}, // rus_verbs:СООБЩИТЬ{}, // Мужчина ранил человека в щеку и сам сообщил об этом в полицию (СООБЩИТЬ) rus_verbs:СТЯГИВАТЬ{}, // Но толщина пузыря постоянно меняется из-за гравитации, которая стягивает жидкость в нижнюю часть (СТЯГИВАТЬ/СТЯНУТЬ/ЗАТЯНУТЬ/ВТЯНУТЬ) rus_verbs:СТЯНУТЬ{}, // rus_verbs:ЗАТЯНУТЬ{}, // rus_verbs:ВТЯНУТЬ{}, // rus_verbs:СОХРАНИТЬ{}, // сохранить данные в файл (СОХРАНИТЬ) деепричастие:придя{}, // Немного придя в себя rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал rus_verbs:УЛЫБАТЬСЯ{}, // она улыбалась во весь рот (УЛЫБАТЬСЯ) rus_verbs:МЕТНУТЬСЯ{}, // она метнулась обратно во тьму (МЕТНУТЬСЯ) rus_verbs:ПОСЛЕДОВАТЬ{}, // большинство жителей города последовало за ним во дворец (ПОСЛЕДОВАТЬ) rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // экстремисты перемещаются из лесов в Сеть (ПЕРЕМЕЩАТЬСЯ) rus_verbs:ВЫТАЩИТЬ{}, // Алексей позволил вытащить себя через дверь во тьму (ВЫТАЩИТЬ) rus_verbs:СЫПАТЬСЯ{}, // внизу под ними камни градом сыпались во двор (СЫПАТЬСЯ) rus_verbs:выезжать{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку rus_verbs:КРИЧАТЬ{}, // ей хотелось кричать во весь голос (КРИЧАТЬ В вин) rus_verbs:ВЫПРЯМИТЬСЯ{}, // волк выпрямился во весь огромный рост (ВЫПРЯМИТЬСЯ В вин) rus_verbs:спрятать{}, // Джон спрятал очки во внутренний карман (спрятать в вин) rus_verbs:ЭКСТРАДИРОВАТЬ{}, // Украина экстрадирует в Таджикистан задержанного бывшего премьер-министра (ЭКСТРАДИРОВАТЬ В вин) rus_verbs:ВВОЗИТЬ{}, // лабораторный мониторинг ввозимой в Россию мясной продукции из США (ВВОЗИТЬ В вин) rus_verbs:УПАКОВАТЬ{}, // упакованных в несколько слоев полиэтилена (УПАКОВАТЬ В вин) rus_verbs:ОТТЯГИВАТЬ{}, // использовать естественную силу гравитации, оттягивая объекты в сторону и изменяя их орбиту (ОТТЯГИВАТЬ В вин) rus_verbs:ПОЗВОНИТЬ{}, // они позвонили в отдел экологии городской администрации (ПОЗВОНИТЬ В) rus_verbs:ПРИВЛЕЧЬ{}, // Открытость данных о лесе поможет привлечь инвестиции в отрасль (ПРИВЛЕЧЬ В) rus_verbs:ЗАПРОСИТЬСЯ{}, // набегавшись и наплясавшись, Стасик утомился и запросился в кроватку (ЗАПРОСИТЬСЯ В) rus_verbs:ОТСТАВИТЬ{}, // бутыль с ацетоном Витька отставил в сторонку (ОТСТАВИТЬ В) rus_verbs:ИСПОЛЬЗОВАТЬ{}, // ты использовал свою магию во зло. (ИСПОЛЬЗОВАТЬ В вин) rus_verbs:ВЫСЕВАТЬ{}, // В апреле редис возможно уже высевать в грунт (ВЫСЕВАТЬ В) rus_verbs:ЗАГНАТЬ{}, // Американский психолог загнал любовь в три угла (ЗАГНАТЬ В) rus_verbs:ЭВОЛЮЦИОНИРОВАТЬ{}, // Почему не все обезьяны эволюционировали в человека? (ЭВОЛЮЦИОНИРОВАТЬ В вин) rus_verbs:СФОТОГРАФИРОВАТЬСЯ{}, // Он сфотографировался во весь рост. (СФОТОГРАФИРОВАТЬСЯ В) rus_verbs:СТАВИТЬ{}, // Он ставит мне в упрёк свою ошибку. (СТАВИТЬ В) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) rus_verbs:ПЕРЕСЕЛЯТЬСЯ{}, // Греки переселяются в Германию (ПЕРЕСЕЛЯТЬСЯ В) rus_verbs:ФОРМИРОВАТЬСЯ{}, // Сахарная свекла относится к двулетним растениям, мясистый корнеплод формируется в первый год. (ФОРМИРОВАТЬСЯ В) rus_verbs:ПРОВОРЧАТЬ{}, // дедуля что-то проворчал в ответ (ПРОВОРЧАТЬ В) rus_verbs:БУРКНУТЬ{}, // нелюдимый парень что-то буркнул в ответ (БУРКНУТЬ В) rus_verbs:ВЕСТИ{}, // дверь вела во тьму. (ВЕСТИ В) rus_verbs:ВЫСКОЧИТЬ{}, // беглецы выскочили во двор. (ВЫСКОЧИТЬ В) rus_verbs:ДОСЫЛАТЬ{}, // Одним движением стрелок досылает патрон в ствол (ДОСЫЛАТЬ В) rus_verbs:СЪЕХАТЬСЯ{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В) rus_verbs:ВЫТЯНУТЬ{}, // Дым вытянуло в трубу. (ВЫТЯНУТЬ В) rus_verbs:торчать{}, // острые обломки бревен торчали во все стороны. rus_verbs:ОГЛЯДЫВАТЬ{}, // Она оглядывает себя в зеркало. (ОГЛЯДЫВАТЬ В) rus_verbs:ДЕЙСТВОВАТЬ{}, // Этот пакет законов действует в ущерб частным предпринимателям. rus_verbs:РАЗЛЕТЕТЬСЯ{}, // люди разлетелись во все стороны. (РАЗЛЕТЕТЬСЯ В) rus_verbs:брызнуть{}, // во все стороны брызнула кровь. (брызнуть в) rus_verbs:ТЯНУТЬСЯ{}, // провода тянулись во все углы. (ТЯНУТЬСЯ В) rus_verbs:валить{}, // валить все в одну кучу (валить в) rus_verbs:выдвинуть{}, // его выдвинули в палату представителей (выдвинуть в) rus_verbs:карабкаться{}, // карабкаться в гору (карабкаться в) rus_verbs:клониться{}, // он клонился в сторону (клониться в) rus_verbs:командировать{}, // мы командировали нашего представителя в Рим (командировать в) rus_verbs:запасть{}, // Эти слова запали мне в душу. rus_verbs:давать{}, // В этой лавке дают в долг? rus_verbs:ездить{}, // Каждый день грузовик ездит в город. rus_verbs:претвориться{}, // Замысел претворился в жизнь. rus_verbs:разойтись{}, // Они разошлись в разные стороны. rus_verbs:выйти{}, // Охотник вышел в поле с ружьём. rus_verbs:отозвать{}, // Отзовите его в сторону и скажите ему об этом. rus_verbs:расходиться{}, // Маша и Петя расходятся в разные стороны rus_verbs:переодеваться{}, // переодеваться в женское платье rus_verbs:перерастать{}, // перерастать в массовые беспорядки rus_verbs:завязываться{}, // завязываться в узел rus_verbs:похватать{}, // похватать в руки rus_verbs:увлечь{}, // увлечь в прогулку по парку rus_verbs:помещать{}, // помещать в изолятор rus_verbs:зыркнуть{}, // зыркнуть в окошко rus_verbs:закатать{}, // закатать в асфальт rus_verbs:усаживаться{}, // усаживаться в кресло rus_verbs:загонять{}, // загонять в сарай rus_verbs:подбрасывать{}, // подбрасывать в воздух rus_verbs:телеграфировать{}, // телеграфировать в центр rus_verbs:вязать{}, // вязать в стопы rus_verbs:подлить{}, // подлить в огонь rus_verbs:заполучить{}, // заполучить в распоряжение rus_verbs:подогнать{}, // подогнать в док rus_verbs:ломиться{}, // ломиться в открытую дверь rus_verbs:переправить{}, // переправить в деревню rus_verbs:затягиваться{}, // затягиваться в трубу rus_verbs:разлетаться{}, // разлетаться в стороны rus_verbs:кланяться{}, // кланяться в ножки rus_verbs:устремляться{}, // устремляться в открытое море rus_verbs:переместиться{}, // переместиться в другую аудиторию rus_verbs:ложить{}, // ложить в ящик rus_verbs:отвозить{}, // отвозить в аэропорт rus_verbs:напрашиваться{}, // напрашиваться в гости rus_verbs:напроситься{}, // напроситься в гости rus_verbs:нагрянуть{}, // нагрянуть в гости rus_verbs:заворачивать{}, // заворачивать в фольгу rus_verbs:заковать{}, // заковать в кандалы rus_verbs:свезти{}, // свезти в сарай rus_verbs:притащиться{}, // притащиться в дом rus_verbs:завербовать{}, // завербовать в разведку rus_verbs:рубиться{}, // рубиться в компьютерные игры rus_verbs:тыкаться{}, // тыкаться в материнскую грудь инфинитив:ссыпать{ вид:несоверш }, инфинитив:ссыпать{ вид:соверш }, // ссыпать в контейнер глагол:ссыпать{ вид:несоверш }, глагол:ссыпать{ вид:соверш }, деепричастие:ссыпав{}, деепричастие:ссыпая{}, rus_verbs:засасывать{}, // засасывать в себя rus_verbs:скакнуть{}, // скакнуть в будущее rus_verbs:подвозить{}, // подвозить в театр rus_verbs:переиграть{}, // переиграть в покер rus_verbs:мобилизовать{}, // мобилизовать в действующую армию rus_verbs:залетать{}, // залетать в закрытое воздушное пространство rus_verbs:подышать{}, // подышать в трубочку rus_verbs:смотаться{}, // смотаться в институт rus_verbs:рассовать{}, // рассовать в кармашки rus_verbs:захаживать{}, // захаживать в дом инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять в ломбард деепричастие:сгоняя{}, rus_verbs:посылаться{}, // посылаться в порт rus_verbs:отлить{}, // отлить в кастрюлю rus_verbs:преобразоваться{}, // преобразоваться в линейное уравнение rus_verbs:поплакать{}, // поплакать в платочек rus_verbs:обуться{}, // обуться в сапоги rus_verbs:закапать{}, // закапать в глаза инфинитив:свозить{ вид:несоверш }, инфинитив:свозить{ вид:соверш }, // свозить в центр утилизации глагол:свозить{ вид:несоверш }, глагол:свозить{ вид:соверш }, деепричастие:свозив{}, деепричастие:свозя{}, rus_verbs:преобразовать{}, // преобразовать в линейное уравнение rus_verbs:кутаться{}, // кутаться в плед rus_verbs:смещаться{}, // смещаться в сторону rus_verbs:зазывать{}, // зазывать в свой магазин инфинитив:трансформироваться{ вид:несоверш }, инфинитив:трансформироваться{ вид:соверш }, // трансформироваться в комбинезон глагол:трансформироваться{ вид:несоверш }, глагол:трансформироваться{ вид:соверш }, деепричастие:трансформируясь{}, деепричастие:трансформировавшись{}, rus_verbs:погружать{}, // погружать в кипящее масло rus_verbs:обыграть{}, // обыграть в теннис rus_verbs:закутать{}, // закутать в одеяло rus_verbs:изливаться{}, // изливаться в воду rus_verbs:закатывать{}, // закатывать в асфальт rus_verbs:мотнуться{}, // мотнуться в банк rus_verbs:избираться{}, // избираться в сенат rus_verbs:наниматься{}, // наниматься в услужение rus_verbs:настучать{}, // настучать в органы rus_verbs:запихивать{}, // запихивать в печку rus_verbs:закапывать{}, // закапывать в нос rus_verbs:засобираться{}, // засобираться в поход rus_verbs:копировать{}, // копировать в другую папку rus_verbs:замуровать{}, // замуровать в стену rus_verbs:упечь{}, // упечь в тюрьму rus_verbs:зрить{}, // зрить в корень rus_verbs:стягиваться{}, // стягиваться в одну точку rus_verbs:усаживать{}, // усаживать в тренажер rus_verbs:протолкнуть{}, // протолкнуть в отверстие rus_verbs:расшибиться{}, // расшибиться в лепешку rus_verbs:приглашаться{}, // приглашаться в кабинет rus_verbs:садить{}, // садить в телегу rus_verbs:уткнуть{}, // уткнуть в подушку rus_verbs:протечь{}, // протечь в подвал rus_verbs:перегнать{}, // перегнать в другую страну rus_verbs:переползти{}, // переползти в тень rus_verbs:зарываться{}, // зарываться в грунт rus_verbs:переодеть{}, // переодеть в сухую одежду rus_verbs:припуститься{}, // припуститься в пляс rus_verbs:лопотать{}, // лопотать в микрофон rus_verbs:прогнусавить{}, // прогнусавить в микрофон rus_verbs:мочиться{}, // мочиться в штаны rus_verbs:загружать{}, // загружать в патронник rus_verbs:радировать{}, // радировать в центр rus_verbs:промотать{}, // промотать в конец rus_verbs:помчать{}, // помчать в школу rus_verbs:съезжать{}, // съезжать в кювет rus_verbs:завозить{}, // завозить в магазин rus_verbs:заявляться{}, // заявляться в школу rus_verbs:наглядеться{}, // наглядеться в зеркало rus_verbs:сворачиваться{}, // сворачиваться в клубочек rus_verbs:устремлять{}, // устремлять взор в будущее rus_verbs:забредать{}, // забредать в глухие уголки rus_verbs:перемотать{}, // перемотать в самое начало диалога rus_verbs:сморкаться{}, // сморкаться в носовой платочек rus_verbs:перетекать{}, // перетекать в другой сосуд rus_verbs:закачать{}, // закачать в шарик rus_verbs:запрятать{}, // запрятать в сейф rus_verbs:пинать{}, // пинать в живот rus_verbs:затрубить{}, // затрубить в горн rus_verbs:подглядывать{}, // подглядывать в замочную скважину инфинитив:подсыпать{ вид:соверш }, инфинитив:подсыпать{ вид:несоверш }, // подсыпать в питье глагол:подсыпать{ вид:соверш }, глагол:подсыпать{ вид:несоверш }, деепричастие:подсыпав{}, деепричастие:подсыпая{}, rus_verbs:засовывать{}, // засовывать в пенал rus_verbs:отрядить{}, // отрядить в командировку rus_verbs:справлять{}, // справлять в кусты rus_verbs:поторапливаться{}, // поторапливаться в самолет rus_verbs:скопировать{}, // скопировать в кэш rus_verbs:подливать{}, // подливать в огонь rus_verbs:запрячь{}, // запрячь в повозку rus_verbs:окраситься{}, // окраситься в пурпур rus_verbs:уколоть{}, // уколоть в шею rus_verbs:слететься{}, // слететься в гнездо rus_verbs:резаться{}, // резаться в карты rus_verbs:затесаться{}, // затесаться в ряды оппозиционеров инфинитив:задвигать{ вид:несоверш }, глагол:задвигать{ вид:несоверш }, // задвигать в ячейку (несоверш) деепричастие:задвигая{}, rus_verbs:доставляться{}, // доставляться в ресторан rus_verbs:поплевать{}, // поплевать в чашку rus_verbs:попереться{}, // попереться в магазин rus_verbs:хаживать{}, // хаживать в церковь rus_verbs:преображаться{}, // преображаться в королеву rus_verbs:организоваться{}, // организоваться в группу rus_verbs:ужалить{}, // ужалить в руку rus_verbs:протискиваться{}, // протискиваться в аудиторию rus_verbs:препроводить{}, // препроводить в закуток rus_verbs:разъезжаться{}, // разъезжаться в разные стороны rus_verbs:пропыхтеть{}, // пропыхтеть в трубку rus_verbs:уволочь{}, // уволочь в нору rus_verbs:отодвигаться{}, // отодвигаться в сторону rus_verbs:разливать{}, // разливать в стаканы rus_verbs:сбегаться{}, // сбегаться в актовый зал rus_verbs:наведаться{}, // наведаться в кладовку rus_verbs:перекочевать{}, // перекочевать в горы rus_verbs:прощебетать{}, // прощебетать в трубку rus_verbs:перекладывать{}, // перекладывать в другой карман rus_verbs:углубляться{}, // углубляться в теорию rus_verbs:переименовать{}, // переименовать в город rus_verbs:переметнуться{}, // переметнуться в лагерь противника rus_verbs:разносить{}, // разносить в щепки rus_verbs:осыпаться{}, // осыпаться в холода rus_verbs:попроситься{}, // попроситься в туалет rus_verbs:уязвить{}, // уязвить в сердце rus_verbs:перетащить{}, // перетащить в дом rus_verbs:закутаться{}, // закутаться в плед // rus_verbs:упаковать{}, // упаковать в бумагу инфинитив:тикать{ aux stress="тик^ать" }, глагол:тикать{ aux stress="тик^ать" }, // тикать в крепость rus_verbs:хихикать{}, // хихикать в кулачок rus_verbs:объединить{}, // объединить в сеть инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать в Калифорнию деепричастие:слетав{}, rus_verbs:заползти{}, // заползти в норку rus_verbs:перерасти{}, // перерасти в крупную аферу rus_verbs:списать{}, // списать в утиль rus_verbs:просачиваться{}, // просачиваться в бункер rus_verbs:пускаться{}, // пускаться в погоню rus_verbs:согревать{}, // согревать в мороз rus_verbs:наливаться{}, // наливаться в емкость rus_verbs:унестись{}, // унестись в небо rus_verbs:зашвырнуть{}, // зашвырнуть в шкаф rus_verbs:сигануть{}, // сигануть в воду rus_verbs:окунуть{}, // окунуть в ледяную воду rus_verbs:просочиться{}, // просочиться в сапог rus_verbs:соваться{}, // соваться в толпу rus_verbs:протолкаться{}, // протолкаться в гардероб rus_verbs:заложить{}, // заложить в ломбард rus_verbs:перекатить{}, // перекатить в сарай rus_verbs:поставлять{}, // поставлять в Китай rus_verbs:залезать{}, // залезать в долги rus_verbs:отлучаться{}, // отлучаться в туалет rus_verbs:сбиваться{}, // сбиваться в кучу rus_verbs:зарыть{}, // зарыть в землю rus_verbs:засадить{}, // засадить в тело rus_verbs:прошмыгнуть{}, // прошмыгнуть в дверь rus_verbs:переставить{}, // переставить в шкаф rus_verbs:отчалить{}, // отчалить в плавание rus_verbs:набираться{}, // набираться в команду rus_verbs:лягнуть{}, // лягнуть в живот rus_verbs:притворить{}, // притворить в жизнь rus_verbs:проковылять{}, // проковылять в гардероб rus_verbs:прикатить{}, // прикатить в гараж rus_verbs:залететь{}, // залететь в окно rus_verbs:переделать{}, // переделать в мопед rus_verbs:протащить{}, // протащить в совет rus_verbs:обмакнуть{}, // обмакнуть в воду rus_verbs:отклоняться{}, // отклоняться в сторону rus_verbs:запихать{}, // запихать в пакет rus_verbs:избирать{}, // избирать в совет rus_verbs:загрузить{}, // загрузить в буфер rus_verbs:уплывать{}, // уплывать в Париж rus_verbs:забивать{}, // забивать в мерзлоту rus_verbs:потыкать{}, // потыкать в безжизненную тушу rus_verbs:съезжаться{}, // съезжаться в санаторий rus_verbs:залепить{}, // залепить в рыло rus_verbs:набиться{}, // набиться в карманы rus_verbs:уползти{}, // уползти в нору rus_verbs:упрятать{}, // упрятать в камеру rus_verbs:переместить{}, // переместить в камеру анабиоза rus_verbs:закрасться{}, // закрасться в душу rus_verbs:сместиться{}, // сместиться в инфракрасную область rus_verbs:запускать{}, // запускать в серию rus_verbs:потрусить{}, // потрусить в чащобу rus_verbs:забрасывать{}, // забрасывать в чистую воду rus_verbs:переселить{}, // переселить в отдаленную деревню rus_verbs:переезжать{}, // переезжать в новую квартиру rus_verbs:приподнимать{}, // приподнимать в воздух rus_verbs:добавиться{}, // добавиться в конец очереди rus_verbs:убыть{}, // убыть в часть rus_verbs:передвигать{}, // передвигать в соседнюю клетку rus_verbs:добавляться{}, // добавляться в очередь rus_verbs:дописать{}, // дописать в перечень rus_verbs:записываться{}, // записываться в кружок rus_verbs:продаться{}, // продаться в кредитное рабство rus_verbs:переписывать{}, // переписывать в тетрадку rus_verbs:заплыть{}, // заплыть в территориальные воды инфинитив:пописать{ aux stress="поп^исать" }, инфинитив:пописать{ aux stress="попис^ать" }, // пописать в горшок глагол:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="попис^ать" }, rus_verbs:отбирать{}, // отбирать в гвардию rus_verbs:нашептывать{}, // нашептывать в микрофон rus_verbs:ковылять{}, // ковылять в стойло rus_verbs:прилетать{}, // прилетать в Париж rus_verbs:пролиться{}, // пролиться в канализацию rus_verbs:запищать{}, // запищать в микрофон rus_verbs:подвезти{}, // подвезти в больницу rus_verbs:припереться{}, // припереться в театр rus_verbs:утечь{}, // утечь в сеть rus_verbs:прорываться{}, // прорываться в буфет rus_verbs:увозить{}, // увозить в ремонт rus_verbs:съедать{}, // съедать в обед rus_verbs:просунуться{}, // просунуться в дверь rus_verbs:перенестись{}, // перенестись в прошлое rus_verbs:завезти{}, // завезти в магазин rus_verbs:проложить{}, // проложить в деревню rus_verbs:объединяться{}, // объединяться в профсоюз rus_verbs:развиться{}, // развиться в бабочку rus_verbs:засеменить{}, // засеменить в кабинку rus_verbs:скатываться{}, // скатываться в яму rus_verbs:завозиться{}, // завозиться в магазин rus_verbs:нанимать{}, // нанимать в рейс rus_verbs:поспеть{}, // поспеть в класс rus_verbs:кидаться{}, // кинаться в крайности rus_verbs:поспевать{}, // поспевать в оперу rus_verbs:обернуть{}, // обернуть в фольгу rus_verbs:обратиться{}, // обратиться в прокуратуру rus_verbs:истолковать{}, // истолковать в свою пользу rus_verbs:таращиться{}, // таращиться в дисплей rus_verbs:прыснуть{}, // прыснуть в кулачок rus_verbs:загнуть{}, // загнуть в другую сторону rus_verbs:раздать{}, // раздать в разные руки rus_verbs:назначить{}, // назначить в приемную комиссию rus_verbs:кидать{}, // кидать в кусты rus_verbs:увлекать{}, // увлекать в лес rus_verbs:переселиться{}, // переселиться в чужое тело rus_verbs:присылать{}, // присылать в город rus_verbs:уплыть{}, // уплыть в Европу rus_verbs:запричитать{}, // запричитать в полный голос rus_verbs:утащить{}, // утащить в логово rus_verbs:завернуться{}, // завернуться в плед rus_verbs:заносить{}, // заносить в блокнот rus_verbs:пятиться{}, // пятиться в дом rus_verbs:наведываться{}, // наведываться в больницу rus_verbs:нырять{}, // нырять в прорубь rus_verbs:зачастить{}, // зачастить в бар rus_verbs:назначаться{}, // назначается в комиссию rus_verbs:мотаться{}, // мотаться в областной центр rus_verbs:разыграть{}, // разыграть в карты rus_verbs:пропищать{}, // пропищать в микрофон rus_verbs:пихнуть{}, // пихнуть в бок rus_verbs:эмигрировать{}, // эмигрировать в Канаду rus_verbs:подключить{}, // подключить в сеть rus_verbs:упереть{}, // упереть в фундамент rus_verbs:уплатить{}, // уплатить в кассу rus_verbs:потащиться{}, // потащиться в медпункт rus_verbs:пригнать{}, // пригнать в стойло rus_verbs:оттеснить{}, // оттеснить в фойе rus_verbs:стучаться{}, // стучаться в ворота rus_verbs:перечислить{}, // перечислить в фонд rus_verbs:сомкнуть{}, // сомкнуть в круг rus_verbs:закачаться{}, // закачаться в резервуар rus_verbs:кольнуть{}, // кольнуть в бок rus_verbs:накрениться{}, // накрениться в сторону берега rus_verbs:подвинуться{}, // подвинуться в другую сторону rus_verbs:разнести{}, // разнести в клочья rus_verbs:отливать{}, // отливать в форму rus_verbs:подкинуть{}, // подкинуть в карман rus_verbs:уводить{}, // уводить в кабинет rus_verbs:ускакать{}, // ускакать в школу rus_verbs:ударять{}, // ударять в барабаны rus_verbs:даться{}, // даться в руки rus_verbs:поцеловаться{}, // поцеловаться в губы rus_verbs:посветить{}, // посветить в подвал rus_verbs:тыкать{}, // тыкать в арбуз rus_verbs:соединяться{}, // соединяться в кольцо rus_verbs:растянуть{}, // растянуть в тонкую ниточку rus_verbs:побросать{}, // побросать в пыль rus_verbs:стукнуться{}, // стукнуться в закрытую дверь rus_verbs:проигрывать{}, // проигрывать в теннис rus_verbs:дунуть{}, // дунуть в трубочку rus_verbs:улетать{}, // улетать в Париж rus_verbs:переводиться{}, // переводиться в филиал rus_verbs:окунуться{}, // окунуться в водоворот событий rus_verbs:попрятаться{}, // попрятаться в норы rus_verbs:перевезти{}, // перевезти в соседнюю палату rus_verbs:топать{}, // топать в школу rus_verbs:относить{}, // относить в помещение rus_verbs:укладывать{}, // укладывать в стопку rus_verbs:укатить{}, // укатил в турне rus_verbs:убирать{}, // убирать в сумку rus_verbs:помалкивать{}, // помалкивать в тряпочку rus_verbs:ронять{}, // ронять в грязь rus_verbs:глазеть{}, // глазеть в бинокль rus_verbs:преобразиться{}, // преобразиться в другого человека rus_verbs:запрыгнуть{}, // запрыгнуть в поезд rus_verbs:сгодиться{}, // сгодиться в суп rus_verbs:проползти{}, // проползти в нору rus_verbs:забираться{}, // забираться в коляску rus_verbs:сбежаться{}, // сбежались в класс rus_verbs:закатиться{}, // закатиться в угол rus_verbs:плевать{}, // плевать в душу rus_verbs:поиграть{}, // поиграть в демократию rus_verbs:кануть{}, // кануть в небытие rus_verbs:опаздывать{}, // опаздывать в школу rus_verbs:отползти{}, // отползти в сторону rus_verbs:стекаться{}, // стекаться в отстойник rus_verbs:запихнуть{}, // запихнуть в пакет rus_verbs:вышвырнуть{}, // вышвырнуть в коридор rus_verbs:связываться{}, // связываться в плотный узел rus_verbs:затолкать{}, // затолкать в ухо rus_verbs:скрутить{}, // скрутить в трубочку rus_verbs:сворачивать{}, // сворачивать в трубочку rus_verbs:сплестись{}, // сплестись в узел rus_verbs:заскочить{}, // заскочить в кабинет rus_verbs:проваливаться{}, // проваливаться в сон rus_verbs:уверовать{}, // уверовать в свою безнаказанность rus_verbs:переписать{}, // переписать в тетрадку rus_verbs:переноситься{}, // переноситься в мир фантазий rus_verbs:заводить{}, // заводить в помещение rus_verbs:сунуться{}, // сунуться в аудиторию rus_verbs:устраиваться{}, // устраиваться в автомастерскую rus_verbs:пропускать{}, // пропускать в зал инфинитив:сбегать{ вид:несоверш }, инфинитив:сбегать{ вид:соверш }, // сбегать в кино глагол:сбегать{ вид:несоверш }, глагол:сбегать{ вид:соверш }, деепричастие:сбегая{}, деепричастие:сбегав{}, rus_verbs:прибегать{}, // прибегать в школу rus_verbs:съездить{}, // съездить в лес rus_verbs:захлопать{}, // захлопать в ладошки rus_verbs:опрокинуться{}, // опрокинуться в грязь инфинитив:насыпать{ вид:несоверш }, инфинитив:насыпать{ вид:соверш }, // насыпать в стакан глагол:насыпать{ вид:несоверш }, глагол:насыпать{ вид:соверш }, деепричастие:насыпая{}, деепричастие:насыпав{}, rus_verbs:употреблять{}, // употреблять в пищу rus_verbs:приводиться{}, // приводиться в действие rus_verbs:пристроить{}, // пристроить в надежные руки rus_verbs:юркнуть{}, // юркнуть в нору rus_verbs:объединиться{}, // объединиться в банду rus_verbs:сажать{}, // сажать в одиночку rus_verbs:соединить{}, // соединить в кольцо rus_verbs:забрести{}, // забрести в кафешку rus_verbs:свернуться{}, // свернуться в клубочек rus_verbs:пересесть{}, // пересесть в другой автобус rus_verbs:постучаться{}, // постучаться в дверцу rus_verbs:соединять{}, // соединять в кольцо rus_verbs:приволочь{}, // приволочь в коморку rus_verbs:смахивать{}, // смахивать в ящик стола rus_verbs:забежать{}, // забежать в помещение rus_verbs:целиться{}, // целиться в беглеца rus_verbs:прокрасться{}, // прокрасться в хранилище rus_verbs:заковылять{}, // заковылять в травтамологию rus_verbs:прискакать{}, // прискакать в стойло rus_verbs:колотить{}, // колотить в дверь rus_verbs:смотреться{}, // смотреться в зеркало rus_verbs:подложить{}, // подложить в салон rus_verbs:пущать{}, // пущать в королевские покои rus_verbs:согнуть{}, // согнуть в дугу rus_verbs:забарабанить{}, // забарабанить в дверь rus_verbs:отклонить{}, // отклонить в сторону посадочной полосы rus_verbs:убраться{}, // убраться в специальную нишу rus_verbs:насмотреться{}, // насмотреться в зеркало rus_verbs:чмокнуть{}, // чмокнуть в щечку rus_verbs:усмехаться{}, // усмехаться в бороду rus_verbs:передвинуть{}, // передвинуть в конец очереди rus_verbs:допускаться{}, // допускаться в опочивальню rus_verbs:задвинуть{}, // задвинуть в дальний угол rus_verbs:отправлять{}, // отправлять в центр rus_verbs:сбрасывать{}, // сбрасывать в жерло rus_verbs:расстреливать{}, // расстреливать в момент обнаружения rus_verbs:заволочь{}, // заволочь в закуток rus_verbs:пролить{}, // пролить в воду rus_verbs:зарыться{}, // зарыться в сено rus_verbs:переливаться{}, // переливаться в емкость rus_verbs:затащить{}, // затащить в клуб rus_verbs:перебежать{}, // перебежать в лагерь врагов rus_verbs:одеть{}, // одеть в новое платье инфинитив:задвигаться{ вид:несоверш }, глагол:задвигаться{ вид:несоверш }, // задвигаться в нишу деепричастие:задвигаясь{}, rus_verbs:клюнуть{}, // клюнуть в темечко rus_verbs:наливать{}, // наливать в кружку rus_verbs:пролезть{}, // пролезть в ушко rus_verbs:откладывать{}, // откладывать в ящик rus_verbs:протянуться{}, // протянуться в соседний дом rus_verbs:шлепнуться{}, // шлепнуться лицом в грязь rus_verbs:устанавливать{}, // устанавливать в машину rus_verbs:употребляться{}, // употребляться в пищу rus_verbs:переключиться{}, // переключиться в реверсный режим rus_verbs:пискнуть{}, // пискнуть в микрофон rus_verbs:заявиться{}, // заявиться в класс rus_verbs:налиться{}, // налиться в стакан rus_verbs:заливать{}, // заливать в бак rus_verbs:ставиться{}, // ставиться в очередь инфинитив:писаться{ aux stress="п^исаться" }, глагол:писаться{ aux stress="п^исаться" }, // писаться в штаны деепричастие:писаясь{}, rus_verbs:целоваться{}, // целоваться в губы rus_verbs:наносить{}, // наносить в область сердца rus_verbs:посмеяться{}, // посмеяться в кулачок rus_verbs:употребить{}, // употребить в пищу rus_verbs:прорваться{}, // прорваться в столовую rus_verbs:укладываться{}, // укладываться в ровные стопки rus_verbs:пробиться{}, // пробиться в финал rus_verbs:забить{}, // забить в землю rus_verbs:переложить{}, // переложить в другой карман rus_verbs:опускать{}, // опускать в свежевырытую могилу rus_verbs:поторопиться{}, // поторопиться в школу rus_verbs:сдвинуться{}, // сдвинуться в сторону rus_verbs:капать{}, // капать в смесь rus_verbs:погружаться{}, // погружаться во тьму rus_verbs:направлять{}, // направлять в кабинку rus_verbs:погрузить{}, // погрузить во тьму rus_verbs:примчаться{}, // примчаться в школу rus_verbs:упираться{}, // упираться в дверь rus_verbs:удаляться{}, // удаляться в комнату совещаний rus_verbs:ткнуться{}, // ткнуться в окошко rus_verbs:убегать{}, // убегать в чащу rus_verbs:соединиться{}, // соединиться в необычную пространственную фигуру rus_verbs:наговорить{}, // наговорить в микрофон rus_verbs:переносить{}, // переносить в дом rus_verbs:прилечь{}, // прилечь в кроватку rus_verbs:поворачивать{}, // поворачивать в обратную сторону rus_verbs:проскочить{}, // проскочить в щель rus_verbs:совать{}, // совать в духовку rus_verbs:переодеться{}, // переодеться в чистую одежду rus_verbs:порвать{}, // порвать в лоскуты rus_verbs:завязать{}, // завязать в бараний рог rus_verbs:съехать{}, // съехать в кювет rus_verbs:литься{}, // литься в канистру rus_verbs:уклониться{}, // уклониться в левую сторону rus_verbs:смахнуть{}, // смахнуть в мусорное ведро rus_verbs:спускать{}, // спускать в шахту rus_verbs:плеснуть{}, // плеснуть в воду rus_verbs:подуть{}, // подуть в угольки rus_verbs:набирать{}, // набирать в команду rus_verbs:хлопать{}, // хлопать в ладошки rus_verbs:ранить{}, // ранить в самое сердце rus_verbs:посматривать{}, // посматривать в иллюминатор rus_verbs:превращать{}, // превращать воду в вино rus_verbs:толкать{}, // толкать в пучину rus_verbs:отбыть{}, // отбыть в расположение части rus_verbs:сгрести{}, // сгрести в карман rus_verbs:удрать{}, // удрать в тайгу rus_verbs:пристроиться{}, // пристроиться в хорошую фирму rus_verbs:сбиться{}, // сбиться в плотную группу rus_verbs:заключать{}, // заключать в объятия rus_verbs:отпускать{}, // отпускать в поход rus_verbs:устремить{}, // устремить взгляд в будущее rus_verbs:обронить{}, // обронить в траву rus_verbs:сливаться{}, // сливаться в речку rus_verbs:стекать{}, // стекать в канаву rus_verbs:свалить{}, // свалить в кучу rus_verbs:подтянуть{}, // подтянуть в кабину rus_verbs:скатиться{}, // скатиться в канаву rus_verbs:проскользнуть{}, // проскользнуть в приоткрытую дверь rus_verbs:заторопиться{}, // заторопиться в буфет rus_verbs:протиснуться{}, // протиснуться в центр толпы rus_verbs:прятать{}, // прятать в укромненькое местечко rus_verbs:пропеть{}, // пропеть в микрофон rus_verbs:углубиться{}, // углубиться в джунгли rus_verbs:сползти{}, // сползти в яму rus_verbs:записывать{}, // записывать в память rus_verbs:расстрелять{}, // расстрелять в упор (наречный оборот В УПОР) rus_verbs:колотиться{}, // колотиться в дверь rus_verbs:просунуть{}, // просунуть в отверстие rus_verbs:провожать{}, // провожать в армию rus_verbs:катить{}, // катить в гараж rus_verbs:поражать{}, // поражать в самое сердце rus_verbs:отлететь{}, // отлететь в дальний угол rus_verbs:закинуть{}, // закинуть в речку rus_verbs:катиться{}, // катиться в пропасть rus_verbs:забросить{}, // забросить в дальний угол rus_verbs:отвезти{}, // отвезти в лагерь rus_verbs:втопить{}, // втопить педаль в пол rus_verbs:втапливать{}, // втапливать педать в пол rus_verbs:утопить{}, // утопить кнопку в панель rus_verbs:напасть{}, // В Пекине участники антияпонских протестов напали на машину посла США rus_verbs:нанять{}, // Босс нанял в службу поддержки еще несколько девушек rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму rus_verbs:баллотировать{}, // претендент был баллотирован в жюри (баллотирован?) rus_verbs:вбухать{}, // Власти вбухали в этой проект много денег rus_verbs:вбухивать{}, // Власти вбухивают в этот проект очень много денег rus_verbs:поскакать{}, // поскакать в атаку rus_verbs:прицелиться{}, // прицелиться в бегущего зайца rus_verbs:прыгать{}, // прыгать в кровать rus_verbs:приглашать{}, // приглашать в дом rus_verbs:понестись{}, // понестись в ворота rus_verbs:заехать{}, // заехать в гаражный бокс rus_verbs:опускаться{}, // опускаться в бездну rus_verbs:переехать{}, // переехать в коттедж rus_verbs:поместить{}, // поместить в карантин rus_verbs:ползти{}, // ползти в нору rus_verbs:добавлять{}, // добавлять в корзину rus_verbs:уткнуться{}, // уткнуться в подушку rus_verbs:продавать{}, // продавать в рабство rus_verbs:спрятаться{}, // Белка спрячется в дупло. rus_verbs:врисовывать{}, // врисовывать новый персонаж в анимацию rus_verbs:воткнуть{}, // воткни вилку в розетку rus_verbs:нести{}, // нести в больницу rus_verbs:воткнуться{}, // вилка воткнулась в сочную котлетку rus_verbs:впаивать{}, // впаивать деталь в плату rus_verbs:впаиваться{}, // деталь впаивается в плату rus_verbs:впархивать{}, // впархивать в помещение rus_verbs:впаять{}, // впаять деталь в плату rus_verbs:впендюривать{}, // впендюривать штукенцию в агрегат rus_verbs:впендюрить{}, // впендюрить штукенцию в агрегат rus_verbs:вперивать{}, // вперивать взгляд в экран rus_verbs:впериваться{}, // впериваться в экран rus_verbs:вперить{}, // вперить взгляд в экран rus_verbs:впериться{}, // впериться в экран rus_verbs:вперять{}, // вперять взгляд в экран rus_verbs:вперяться{}, // вперяться в экран rus_verbs:впечатать{}, // впечатать текст в первую главу rus_verbs:впечататься{}, // впечататься в стену rus_verbs:впечатывать{}, // впечатывать текст в первую главу rus_verbs:впечатываться{}, // впечатываться в стену rus_verbs:впиваться{}, // Хищник впивается в жертву мощными зубами rus_verbs:впитаться{}, // Жидкость впиталась в ткань rus_verbs:впитываться{}, // Жидкость впитывается в ткань rus_verbs:впихивать{}, // Мама впихивает в сумку кусок колбасы rus_verbs:впихиваться{}, // Кусок колбасы впихивается в сумку rus_verbs:впихнуть{}, // Мама впихнула кастрюлю в холодильник rus_verbs:впихнуться{}, // Кастрюля впихнулась в холодильник rus_verbs:вплавиться{}, // Провод вплавился в плату rus_verbs:вплеснуть{}, // вплеснуть краситель в бак rus_verbs:вплести{}, // вплести ленту в волосы rus_verbs:вплестись{}, // вплестись в волосы rus_verbs:вплетать{}, // вплетать ленты в волосы rus_verbs:вплывать{}, // корабль вплывает в порт rus_verbs:вплыть{}, // яхта вплыла в бухту rus_verbs:вползать{}, // дракон вползает в пещеру rus_verbs:вползти{}, // дракон вполз в свою пещеру rus_verbs:впорхнуть{}, // бабочка впорхнула в окно rus_verbs:впрессовать{}, // впрессовать деталь в плиту rus_verbs:впрессоваться{}, // впрессоваться в плиту rus_verbs:впрессовывать{}, // впрессовывать деталь в плиту rus_verbs:впрессовываться{}, // впрессовываться в плиту rus_verbs:впрыгивать{}, // Пассажир впрыгивает в вагон rus_verbs:впрыгнуть{}, // Пассажир впрыгнул в вагон rus_verbs:впрыскивать{}, // Форсунка впрыскивает топливо в цилиндр rus_verbs:впрыскиваться{}, // Топливо впрыскивается форсункой в цилиндр rus_verbs:впрыснуть{}, // Форсунка впрыснула топливную смесь в камеру сгорания rus_verbs:впрягать{}, // впрягать лошадь в телегу rus_verbs:впрягаться{}, // впрягаться в работу rus_verbs:впрячь{}, // впрячь лошадь в телегу rus_verbs:впрячься{}, // впрячься в работу rus_verbs:впускать{}, // впускать посетителей в музей rus_verbs:впускаться{}, // впускаться в помещение rus_verbs:впустить{}, // впустить посетителей в музей rus_verbs:впутать{}, // впутать кого-то во что-то rus_verbs:впутаться{}, // впутаться во что-то rus_verbs:впутывать{}, // впутывать кого-то во что-то rus_verbs:впутываться{}, // впутываться во что-то rus_verbs:врабатываться{}, // врабатываться в режим rus_verbs:вработаться{}, // вработаться в режим rus_verbs:врастать{}, // врастать в кожу rus_verbs:врасти{}, // врасти в кожу инфинитив:врезать{ вид:несоверш }, // врезать замок в дверь инфинитив:врезать{ вид:соверш }, глагол:врезать{ вид:несоверш }, глагол:врезать{ вид:соверш }, деепричастие:врезая{}, деепричастие:врезав{}, прилагательное:врезанный{}, инфинитив:врезаться{ вид:несоверш }, // врезаться в стену инфинитив:врезаться{ вид:соверш }, глагол:врезаться{ вид:несоверш }, деепричастие:врезаясь{}, деепричастие:врезавшись{}, rus_verbs:врубить{}, // врубить в нагрузку rus_verbs:врываться{}, // врываться в здание rus_verbs:закачивать{}, // Насос закачивает топливо в бак rus_verbs:ввезти{}, // Предприятие ввезло товар в страну rus_verbs:вверстать{}, // Дизайнер вверстал блок в страницу rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу rus_verbs:вверстываться{}, // Блок тяжело вверстывается в эту страницу rus_verbs:ввивать{}, // Женщина ввивает полоску в косу rus_verbs:вволакиваться{}, // Пойманная мышь вволакивается котиком в дом rus_verbs:вволочь{}, // Кот вволок в дом пойманную крысу rus_verbs:вдергивать{}, // приспособление вдергивает нитку в игольное ушко rus_verbs:вдернуть{}, // приспособление вдернуло нитку в игольное ушко rus_verbs:вдувать{}, // Челоек вдувает воздух в легкие второго человека rus_verbs:вдуваться{}, // Воздух вдувается в легкие человека rus_verbs:вламываться{}, // Полиция вламывается в квартиру rus_verbs:вовлекаться{}, // трудные подростки вовлекаются в занятие спортом rus_verbs:вовлечь{}, // вовлечь трудных подростков в занятие спортом rus_verbs:вовлечься{}, // вовлечься в занятие спортом rus_verbs:спуститься{}, // спуститься в подвал rus_verbs:спускаться{}, // спускаться в подвал rus_verbs:отправляться{}, // отправляться в дальнее плавание инфинитив:эмитировать{ вид:соверш }, // Поверхность эмитирует электроны в пространство инфинитив:эмитировать{ вид:несоверш }, глагол:эмитировать{ вид:соверш }, глагол:эмитировать{ вид:несоверш }, деепричастие:эмитируя{}, деепричастие:эмитировав{}, прилагательное:эмитировавший{ вид:несоверш }, // прилагательное:эмитировавший{ вид:соверш }, прилагательное:эмитирующий{}, прилагательное:эмитируемый{}, прилагательное:эмитированный{}, инфинитив:этапировать{вид:несоверш}, // Преступника этапировали в колонию инфинитив:этапировать{вид:соверш}, глагол:этапировать{вид:несоверш}, глагол:этапировать{вид:соверш}, деепричастие:этапируя{}, прилагательное:этапируемый{}, прилагательное:этапированный{}, rus_verbs:этапироваться{}, // Преступники этапируются в колонию rus_verbs:баллотироваться{}, // они баллотировались в жюри rus_verbs:бежать{}, // Олигарх с семьей любовницы бежал в другую страну rus_verbs:бросать{}, // Они бросали в фонтан медные монетки rus_verbs:бросаться{}, // Дети бросались в воду с моста rus_verbs:бросить{}, // Он бросил в фонтан медную монетку rus_verbs:броситься{}, // самоубийца бросился с моста в воду rus_verbs:превратить{}, // Найден белок, который превратит человека в супергероя rus_verbs:буксировать{}, // Буксир буксирует танкер в порт rus_verbs:буксироваться{}, // Сухогруз буксируется в порт rus_verbs:вбегать{}, // Курьер вбегает в дверь rus_verbs:вбежать{}, // Курьер вбежал в дверь rus_verbs:вбетонировать{}, // Опора была вбетонирована в пол rus_verbs:вбивать{}, // Мастер вбивает штырь в плиту rus_verbs:вбиваться{}, // Штырь вбивается в плиту rus_verbs:вбирать{}, // Вата вбирает в себя влагу rus_verbs:вбить{}, // Ученик вбил в доску маленький гвоздь rus_verbs:вбрасывать{}, // Арбитр вбрасывает мяч в игру rus_verbs:вбрасываться{}, // Мяч вбрасывается в игру rus_verbs:вбросить{}, // Судья вбросил мяч в игру rus_verbs:вбуравиться{}, // Сверло вбуравилось в бетон rus_verbs:вбуравливаться{}, // Сверло вбуравливается в бетон rus_verbs:вбухиваться{}, // Много денег вбухиваются в этот проект rus_verbs:вваливаться{}, // Человек вваливается в кабинет врача rus_verbs:ввалить{}, // Грузчики ввалили мешок в квартиру rus_verbs:ввалиться{}, // Человек ввалился в кабинет терапевта rus_verbs:вваривать{}, // Робот вваривает арматурину в плиту rus_verbs:ввариваться{}, // Арматура вваривается в плиту rus_verbs:вварить{}, // Робот вварил арматурину в плиту rus_verbs:влезть{}, // Предприятие ввезло товар в страну rus_verbs:ввернуть{}, // Вверни новую лампочку в люстру rus_verbs:ввернуться{}, // Лампочка легко ввернулась в патрон rus_verbs:ввертывать{}, // Электрик ввертывает лампочку в патрон rus_verbs:ввертываться{}, // Лампочка легко ввертывается в патрон rus_verbs:вверять{}, // Пациент вверяет свою жизнь в руки врача rus_verbs:вверяться{}, // Пациент вверяется в руки врача rus_verbs:ввести{}, // Агенство ввело своего представителя в совет директоров rus_verbs:ввиваться{}, // полоска ввивается в косу rus_verbs:ввинтить{}, // Отвертка ввинтила шуруп в дерево rus_verbs:ввинтиться{}, // Шуруп ввинтился в дерево rus_verbs:ввинчивать{}, // Рука ввинчивает саморез в стену rus_verbs:ввинчиваться{}, // Саморез ввинчивается в стену rus_verbs:вводить{}, // Агенство вводит своего представителя в совет директоров rus_verbs:вводиться{}, // Представитель агенства вводится в совет директоров // rus_verbs:ввозить{}, // Фирма ввозит в страну станки и сырье rus_verbs:ввозиться{}, // Станки и сырье ввозятся в страну rus_verbs:вволакивать{}, // Пойманная мышь вволакивается котиком в дом rus_verbs:вворачивать{}, // Электрик вворачивает новую лампочку в патрон rus_verbs:вворачиваться{}, // Новая лампочка легко вворачивается в патрон rus_verbs:ввязаться{}, // Разведрота ввязалась в бой rus_verbs:ввязываться{}, // Передовые части ввязываются в бой rus_verbs:вглядеться{}, // Охранник вгляделся в темный коридор rus_verbs:вглядываться{}, // Охранник внимательно вглядывается в монитор rus_verbs:вгонять{}, // Эта музыка вгоняет меня в депрессию rus_verbs:вгрызаться{}, // Зонд вгрызается в поверхность астероида rus_verbs:вгрызться{}, // Зонд вгрызся в поверхность астероида rus_verbs:вдаваться{}, // Вы не должны вдаваться в юридические детали rus_verbs:вдвигать{}, // Робот вдвигает контейнер в ячейку rus_verbs:вдвигаться{}, // Контейнер вдвигается в ячейку rus_verbs:вдвинуть{}, // манипулятор вдвинул деталь в печь rus_verbs:вдвинуться{}, // деталь вдвинулась в печь rus_verbs:вдевать{}, // портниха быстро вдевает нитку в иголку rus_verbs:вдеваться{}, // нитка быстро вдевается в игольное ушко rus_verbs:вдеть{}, // портниха быстро вдела нитку в игольное ушко rus_verbs:вдеться{}, // нитка быстро вделась в игольное ушко rus_verbs:вделать{}, // мастер вделал розетку в стену rus_verbs:вделывать{}, // мастер вделывает выключатель в стену rus_verbs:вделываться{}, // кронштейн вделывается в стену rus_verbs:вдергиваться{}, // нитка легко вдергивается в игольное ушко rus_verbs:вдернуться{}, // нитка легко вдернулась в игольное ушко rus_verbs:вдолбить{}, // Американцы обещали вдолбить страну в каменный век rus_verbs:вдумываться{}, // Мальчик обычно не вдумывался в сюжет фильмов rus_verbs:вдыхать{}, // мы вдыхаем в себя весь этот смог rus_verbs:вдыхаться{}, // Весь этот смог вдыхается в легкие rus_verbs:вернуть{}, // Книгу надо вернуть в библиотеку rus_verbs:вернуться{}, // Дети вернулись в библиотеку rus_verbs:вжаться{}, // Водитель вжался в кресло rus_verbs:вживаться{}, // Актер вживается в новую роль rus_verbs:вживить{}, // Врачи вживили стимулятор в тело пациента rus_verbs:вживиться{}, // Стимулятор вживился в тело пациента rus_verbs:вживлять{}, // Врачи вживляют стимулятор в тело пациента rus_verbs:вживляться{}, // Стимулятор вживляется в тело rus_verbs:вжиматься{}, // Видитель инстинктивно вжимается в кресло rus_verbs:вжиться{}, // Актер вжился в свою новую роль rus_verbs:взвиваться{}, // Воздушный шарик взвивается в небо rus_verbs:взвинтить{}, // Кризис взвинтил цены в небо rus_verbs:взвинтиться{}, // Цены взвинтились в небо rus_verbs:взвинчивать{}, // Кризис взвинчивает цены в небо rus_verbs:взвинчиваться{}, // Цены взвинчиваются в небо rus_verbs:взвиться{}, // Шарики взвились в небо rus_verbs:взлетать{}, // Экспериментальный аппарат взлетает в воздух rus_verbs:взлететь{}, // Экспериментальный аппарат взлетел в небо rus_verbs:взмывать{}, // шарики взмывают в небо rus_verbs:взмыть{}, // Шарики взмыли в небо rus_verbs:вильнуть{}, // Машина вильнула в левую сторону rus_verbs:вкалывать{}, // Медсестра вкалывает иглу в вену rus_verbs:вкалываться{}, // Игла вкалываться прямо в вену rus_verbs:вкапывать{}, // рабочий вкапывает сваю в землю rus_verbs:вкапываться{}, // Свая вкапывается в землю rus_verbs:вкатить{}, // рабочие вкатили бочку в гараж rus_verbs:вкатиться{}, // машина вкатилась в гараж rus_verbs:вкатывать{}, // рабочик вкатывают бочку в гараж rus_verbs:вкатываться{}, // машина вкатывается в гараж rus_verbs:вкачать{}, // Механики вкачали в бак много топлива rus_verbs:вкачивать{}, // Насос вкачивает топливо в бак rus_verbs:вкачиваться{}, // Топливо вкачивается в бак rus_verbs:вкидать{}, // Манипулятор вкидал груз в контейнер rus_verbs:вкидывать{}, // Манипулятор вкидывает груз в контейнер rus_verbs:вкидываться{}, // Груз вкидывается в контейнер rus_verbs:вкладывать{}, // Инвестор вкладывает деньги в акции rus_verbs:вкладываться{}, // Инвестор вкладывается в акции rus_verbs:вклеивать{}, // Мальчик вклеивает картинку в тетрадь rus_verbs:вклеиваться{}, // Картинка вклеивается в тетрадь rus_verbs:вклеить{}, // Мальчик вклеил картинку в тетрадь rus_verbs:вклеиться{}, // Картинка вклеилась в тетрадь rus_verbs:вклепать{}, // Молоток вклепал заклепку в лист rus_verbs:вклепывать{}, // Молоток вклепывает заклепку в лист rus_verbs:вклиниваться{}, // Машина вклинивается в поток rus_verbs:вклиниться{}, // машина вклинилась в поток rus_verbs:включать{}, // Команда включает компьютер в сеть rus_verbs:включаться{}, // Машина включается в глобальную сеть rus_verbs:включить{}, // Команда включила компьютер в сеть rus_verbs:включиться{}, // Компьютер включился в сеть rus_verbs:вколачивать{}, // Столяр вколачивает гвоздь в доску rus_verbs:вколачиваться{}, // Гвоздь вколачивается в доску rus_verbs:вколотить{}, // Столяр вколотил гвоздь в доску rus_verbs:вколоть{}, // Медсестра вколола в мышцу лекарство rus_verbs:вкопать{}, // Рабочие вкопали сваю в землю rus_verbs:вкрадываться{}, // Ошибка вкрадывается в расчеты rus_verbs:вкраивать{}, // Портниха вкраивает вставку в юбку rus_verbs:вкраиваться{}, // Вставка вкраивается в юбку rus_verbs:вкрасться{}, // Ошибка вкралась в расчеты rus_verbs:вкрутить{}, // Электрик вкрутил лампочку в патрон rus_verbs:вкрутиться{}, // лампочка легко вкрутилась в патрон rus_verbs:вкручивать{}, // Электрик вкручивает лампочку в патрон rus_verbs:вкручиваться{}, // Лампочка легко вкручивается в патрон rus_verbs:влазить{}, // Разъем влазит в отверствие rus_verbs:вламывать{}, // Полиция вламывается в квартиру rus_verbs:влетать{}, // Самолет влетает в грозовой фронт rus_verbs:влететь{}, // Самолет влетел в грозовой фронт rus_verbs:вливать{}, // Механик вливает масло в картер rus_verbs:вливаться{}, // Масло вливается в картер rus_verbs:влипать{}, // Эти неудачники постоянно влипают в разные происшествия rus_verbs:влипнуть{}, // Эти неудачники опять влипли в неприятности rus_verbs:влить{}, // Механик влил свежее масло в картер rus_verbs:влиться{}, // Свежее масло влилось в бак rus_verbs:вложить{}, // Инвесторы вложили в эти акции большие средства rus_verbs:вложиться{}, // Инвесторы вложились в эти акции rus_verbs:влюбиться{}, // Коля влюбился в Олю rus_verbs:влюблять{}, // Оля постоянно влюбляла в себя мальчиков rus_verbs:влюбляться{}, // Оля влюбляется в спортсменов rus_verbs:вляпаться{}, // Коля вляпался в неприятность rus_verbs:вляпываться{}, // Коля постоянно вляпывается в неприятности rus_verbs:вменить{}, // вменить в вину rus_verbs:вменять{}, // вменять в обязанность rus_verbs:вмерзать{}, // Колеса вмерзают в лед rus_verbs:вмерзнуть{}, // Колеса вмерзли в лед rus_verbs:вмести{}, // вмести в дом rus_verbs:вместить{}, // вместить в ёмкость rus_verbs:вместиться{}, // Прибор не вместился в зонд rus_verbs:вмешаться{}, // Начальник вмешался в конфликт rus_verbs:вмешивать{}, // Не вмешивай меня в это дело rus_verbs:вмешиваться{}, // Начальник вмешивается в переговоры rus_verbs:вмещаться{}, // Приборы не вмещаются в корпус rus_verbs:вминать{}, // вминать в корпус rus_verbs:вминаться{}, // кронштейн вминается в корпус rus_verbs:вмонтировать{}, // Конструкторы вмонтировали в корпус зонда новые приборы rus_verbs:вмонтироваться{}, // Новые приборы легко вмонтировались в корпус зонда rus_verbs:вмораживать{}, // Установка вмораживает сваи в грунт rus_verbs:вмораживаться{}, // Сваи вмораживаются в грунт rus_verbs:вморозить{}, // Установка вморозила сваи в грунт rus_verbs:вмуровать{}, // Сейф был вмурован в стену rus_verbs:вмуровывать{}, // вмуровывать сейф в стену rus_verbs:вмуровываться{}, // сейф вмуровывается в бетонную стену rus_verbs:внедрить{}, // внедрить инновацию в производство rus_verbs:внедриться{}, // Шпион внедрился в руководство rus_verbs:внедрять{}, // внедрять инновации в производство rus_verbs:внедряться{}, // Шпионы внедряются в руководство rus_verbs:внести{}, // внести коробку в дом rus_verbs:внестись{}, // внестись в список приглашенных гостей rus_verbs:вникать{}, // Разработчик вникает в детали задачи rus_verbs:вникнуть{}, // Дизайнер вник в детали задачи rus_verbs:вносить{}, // вносить новое действующее лицо в список главных героев rus_verbs:вноситься{}, // вноситься в список главных персонажей rus_verbs:внюхаться{}, // Пёс внюхался в ароматы леса rus_verbs:внюхиваться{}, // Пёс внюхивается в ароматы леса rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями rus_verbs:вовлекать{}, // вовлекать трудных подростков в занятие спортом rus_verbs:вогнать{}, // вогнал человека в тоску rus_verbs:водворить{}, // водворить преступника в тюрьму rus_verbs:возвернуть{}, // возвернуть в родную стихию rus_verbs:возвернуться{}, // возвернуться в родную стихию rus_verbs:возвести{}, // возвести число в четную степень rus_verbs:возводить{}, // возводить число в четную степень rus_verbs:возводиться{}, // число возводится в четную степень rus_verbs:возвратить{}, // возвратить коров в стойло rus_verbs:возвратиться{}, // возвратиться в родной дом rus_verbs:возвращать{}, // возвращать коров в стойло rus_verbs:возвращаться{}, // возвращаться в родной дом rus_verbs:войти{}, // войти в галерею славы rus_verbs:вонзать{}, // Коля вонзает вилку в котлету rus_verbs:вонзаться{}, // Вилка вонзается в котлету rus_verbs:вонзить{}, // Коля вонзил вилку в котлету rus_verbs:вонзиться{}, // Вилка вонзилась в сочную котлету rus_verbs:воплотить{}, // Коля воплотил свои мечты в реальность rus_verbs:воплотиться{}, // Мечты воплотились в реальность rus_verbs:воплощать{}, // Коля воплощает мечты в реальность rus_verbs:воплощаться{}, // Мечты иногда воплощаются в реальность rus_verbs:ворваться{}, // Перемены неожиданно ворвались в размеренную жизнь rus_verbs:воспарить{}, // Душа воспарила в небо rus_verbs:воспарять{}, // Душа воспаряет в небо rus_verbs:врыть{}, // врыть опору в землю rus_verbs:врыться{}, // врыться в землю rus_verbs:всадить{}, // всадить пулю в сердце rus_verbs:всаживать{}, // всаживать нож в бок rus_verbs:всасывать{}, // всасывать воду в себя rus_verbs:всасываться{}, // всасываться в ёмкость rus_verbs:вселить{}, // вселить надежду в кого-либо rus_verbs:вселиться{}, // вселиться в пустующее здание rus_verbs:вселять{}, // вселять надежду в кого-то rus_verbs:вселяться{}, // вселяться в пустующее здание rus_verbs:вскидывать{}, // вскидывать руку в небо rus_verbs:вскинуть{}, // вскинуть руку в небо rus_verbs:вслушаться{}, // вслушаться в звуки rus_verbs:вслушиваться{}, // вслушиваться в шорох rus_verbs:всматриваться{}, // всматриваться в темноту rus_verbs:всмотреться{}, // всмотреться в темень rus_verbs:всовывать{}, // всовывать палец в отверстие rus_verbs:всовываться{}, // всовываться в форточку rus_verbs:всосать{}, // всосать жидкость в себя rus_verbs:всосаться{}, // всосаться в кожу rus_verbs:вставить{}, // вставить ключ в замок rus_verbs:вставлять{}, // вставлять ключ в замок rus_verbs:встраивать{}, // встраивать черный ход в систему защиты rus_verbs:встраиваться{}, // встраиваться в систему безопасности rus_verbs:встревать{}, // встревать в разговор rus_verbs:встроить{}, // встроить секретный модуль в систему безопасности rus_verbs:встроиться{}, // встроиться в систему безопасности rus_verbs:встрять{}, // встрять в разговор rus_verbs:вступать{}, // вступать в действующую армию rus_verbs:вступить{}, // вступить в действующую армию rus_verbs:всунуть{}, // всунуть палец в отверстие rus_verbs:всунуться{}, // всунуться в форточку инфинитив:всыпать{вид:соверш}, // всыпать порошок в контейнер инфинитив:всыпать{вид:несоверш}, глагол:всыпать{вид:соверш}, глагол:всыпать{вид:несоверш}, деепричастие:всыпав{}, деепричастие:всыпая{}, прилагательное:всыпавший{ вид:соверш }, // прилагательное:всыпавший{ вид:несоверш }, прилагательное:всыпанный{}, // прилагательное:всыпающий{}, инфинитив:всыпаться{ вид:несоверш}, // всыпаться в контейнер // инфинитив:всыпаться{ вид:соверш}, // глагол:всыпаться{ вид:соверш}, глагол:всыпаться{ вид:несоверш}, // деепричастие:всыпавшись{}, деепричастие:всыпаясь{}, // прилагательное:всыпавшийся{ вид:соверш }, // прилагательное:всыпавшийся{ вид:несоверш }, // прилагательное:всыпающийся{}, rus_verbs:вталкивать{}, // вталкивать деталь в ячейку rus_verbs:вталкиваться{}, // вталкиваться в ячейку rus_verbs:втаптывать{}, // втаптывать в грязь rus_verbs:втаптываться{}, // втаптываться в грязь rus_verbs:втаскивать{}, // втаскивать мешок в комнату rus_verbs:втаскиваться{}, // втаскиваться в комнату rus_verbs:втащить{}, // втащить мешок в комнату rus_verbs:втащиться{}, // втащиться в комнату rus_verbs:втекать{}, // втекать в бутылку rus_verbs:втемяшивать{}, // втемяшивать в голову rus_verbs:втемяшиваться{}, // втемяшиваться в голову rus_verbs:втемяшить{}, // втемяшить в голову rus_verbs:втемяшиться{}, // втемяшиться в голову rus_verbs:втереть{}, // втереть крем в кожу rus_verbs:втереться{}, // втереться в кожу rus_verbs:втесаться{}, // втесаться в группу rus_verbs:втесывать{}, // втесывать в группу rus_verbs:втесываться{}, // втесываться в группу rus_verbs:втечь{}, // втечь в бак rus_verbs:втирать{}, // втирать крем в кожу rus_verbs:втираться{}, // втираться в кожу rus_verbs:втискивать{}, // втискивать сумку в вагон rus_verbs:втискиваться{}, // втискиваться в переполненный вагон rus_verbs:втиснуть{}, // втиснуть сумку в вагон rus_verbs:втиснуться{}, // втиснуться в переполненный вагон метро rus_verbs:втолкать{}, // втолкать коляску в лифт rus_verbs:втолкаться{}, // втолкаться в вагон метро rus_verbs:втолкнуть{}, // втолкнуть коляску в лифт rus_verbs:втолкнуться{}, // втолкнуться в вагон метро rus_verbs:втолочь{}, // втолочь в смесь rus_verbs:втоптать{}, // втоптать цветы в землю rus_verbs:вторгаться{}, // вторгаться в чужую зону rus_verbs:вторгнуться{}, // вторгнуться в частную жизнь rus_verbs:втравить{}, // втравить кого-то в неприятности rus_verbs:втравливать{}, // втравливать кого-то в неприятности rus_verbs:втрамбовать{}, // втрамбовать камни в землю rus_verbs:втрамбовывать{}, // втрамбовывать камни в землю rus_verbs:втрамбовываться{}, // втрамбовываться в землю rus_verbs:втрескаться{}, // втрескаться в кого-то rus_verbs:втрескиваться{}, // втрескиваться в кого-либо rus_verbs:втыкать{}, // втыкать вилку в котлетку rus_verbs:втыкаться{}, // втыкаться в розетку rus_verbs:втюриваться{}, // втюриваться в кого-либо rus_verbs:втюриться{}, // втюриться в кого-либо rus_verbs:втягивать{}, // втягивать что-то в себя rus_verbs:втягиваться{}, // втягиваться в себя rus_verbs:втянуться{}, // втянуться в себя rus_verbs:вцементировать{}, // вцементировать сваю в фундамент rus_verbs:вчеканить{}, // вчеканить надпись в лист rus_verbs:вчитаться{}, // вчитаться внимательнее в текст rus_verbs:вчитываться{}, // вчитываться внимательнее в текст rus_verbs:вчувствоваться{}, // вчувствоваться в роль rus_verbs:вшагивать{}, // вшагивать в новую жизнь rus_verbs:вшагнуть{}, // вшагнуть в новую жизнь rus_verbs:вшивать{}, // вшивать заплату в рубашку rus_verbs:вшиваться{}, // вшиваться в ткань rus_verbs:вшить{}, // вшить заплату в ткань rus_verbs:въедаться{}, // въедаться в мякоть rus_verbs:въезжать{}, // въезжать в гараж rus_verbs:въехать{}, // въехать в гараж rus_verbs:выиграть{}, // Коля выиграл в шахматы rus_verbs:выигрывать{}, // Коля часто выигрывает у меня в шахматы rus_verbs:выкладывать{}, // выкладывать в общий доступ rus_verbs:выкладываться{}, // выкладываться в общий доступ rus_verbs:выкрасить{}, // выкрасить машину в розовый цвет rus_verbs:выкраситься{}, // выкраситься в дерзкий розовый цвет rus_verbs:выкрашивать{}, // выкрашивать волосы в красный цвет rus_verbs:выкрашиваться{}, // выкрашиваться в красный цвет rus_verbs:вылезать{}, // вылезать в открытое пространство rus_verbs:вылезти{}, // вылезти в открытое пространство rus_verbs:выливать{}, // выливать в бутылку rus_verbs:выливаться{}, // выливаться в ёмкость rus_verbs:вылить{}, // вылить отходы в канализацию rus_verbs:вылиться{}, // Топливо вылилось в воду rus_verbs:выложить{}, // выложить в общий доступ rus_verbs:выпадать{}, // выпадать в осадок rus_verbs:выпрыгивать{}, // выпрыгивать в окно rus_verbs:выпрыгнуть{}, // выпрыгнуть в окно rus_verbs:выродиться{}, // выродиться в жалкое подобие rus_verbs:вырождаться{}, // вырождаться в жалкое подобие славных предков rus_verbs:высеваться{}, // высеваться в землю rus_verbs:высеять{}, // высеять в землю rus_verbs:выслать{}, // выслать в страну постоянного пребывания rus_verbs:высморкаться{}, // высморкаться в платок rus_verbs:высморкнуться{}, // высморкнуться в платок rus_verbs:выстреливать{}, // выстреливать в цель rus_verbs:выстреливаться{}, // выстреливаться в цель rus_verbs:выстрелить{}, // выстрелить в цель rus_verbs:вытекать{}, // вытекать в озеро rus_verbs:вытечь{}, // вытечь в воду rus_verbs:смотреть{}, // смотреть в будущее rus_verbs:подняться{}, // подняться в лабораторию rus_verbs:послать{}, // послать в магазин rus_verbs:слать{}, // слать в неизвестность rus_verbs:добавить{}, // добавить в суп rus_verbs:пройти{}, // пройти в лабораторию rus_verbs:положить{}, // положить в ящик rus_verbs:прислать{}, // прислать в полицию rus_verbs:упасть{}, // упасть в пропасть инфинитив:писать{ aux stress="пис^ать" }, // писать в газету инфинитив:писать{ aux stress="п^исать" }, // писать в штанишки глагол:писать{ aux stress="п^исать" }, глагол:писать{ aux stress="пис^ать" }, деепричастие:писая{}, прилагательное:писавший{ aux stress="п^исавший" }, // писавший в штанишки прилагательное:писавший{ aux stress="пис^авший" }, // писавший в газету rus_verbs:собираться{}, // собираться в поход rus_verbs:звать{}, // звать в ресторан rus_verbs:направиться{}, // направиться в ресторан rus_verbs:отправиться{}, // отправиться в ресторан rus_verbs:поставить{}, // поставить в угол rus_verbs:целить{}, // целить в мишень rus_verbs:попасть{}, // попасть в переплет rus_verbs:ударить{}, // ударить в больное место rus_verbs:закричать{}, // закричать в микрофон rus_verbs:опустить{}, // опустить в воду rus_verbs:принести{}, // принести в дом бездомного щенка rus_verbs:отдать{}, // отдать в хорошие руки rus_verbs:ходить{}, // ходить в школу rus_verbs:уставиться{}, // уставиться в экран rus_verbs:приходить{}, // приходить в бешенство rus_verbs:махнуть{}, // махнуть в Италию rus_verbs:сунуть{}, // сунуть в замочную скважину rus_verbs:явиться{}, // явиться в расположение части rus_verbs:уехать{}, // уехать в город rus_verbs:целовать{}, // целовать в лобик rus_verbs:повести{}, // повести в бой rus_verbs:опуститься{}, // опуститься в кресло rus_verbs:передать{}, // передать в архив rus_verbs:побежать{}, // побежать в школу rus_verbs:стечь{}, // стечь в воду rus_verbs:уходить{}, // уходить добровольцем в армию rus_verbs:привести{}, // привести в дом rus_verbs:шагнуть{}, // шагнуть в неизвестность rus_verbs:собраться{}, // собраться в поход rus_verbs:заглянуть{}, // заглянуть в основу rus_verbs:поспешить{}, // поспешить в церковь rus_verbs:поцеловать{}, // поцеловать в лоб rus_verbs:перейти{}, // перейти в высшую лигу rus_verbs:поверить{}, // поверить в искренность rus_verbs:глянуть{}, // глянуть в оглавление rus_verbs:зайти{}, // зайти в кафетерий rus_verbs:подобрать{}, // подобрать в лесу rus_verbs:проходить{}, // проходить в помещение rus_verbs:глядеть{}, // глядеть в глаза rus_verbs:пригласить{}, // пригласить в театр rus_verbs:позвать{}, // позвать в класс rus_verbs:усесться{}, // усесться в кресло rus_verbs:поступить{}, // поступить в институт rus_verbs:лечь{}, // лечь в постель rus_verbs:поклониться{}, // поклониться в пояс rus_verbs:потянуться{}, // потянуться в лес rus_verbs:колоть{}, // колоть в ягодицу rus_verbs:присесть{}, // присесть в кресло rus_verbs:оглядеться{}, // оглядеться в зеркало rus_verbs:поглядеть{}, // поглядеть в зеркало rus_verbs:превратиться{}, // превратиться в лягушку rus_verbs:принимать{}, // принимать во внимание rus_verbs:звонить{}, // звонить в колокола rus_verbs:привезти{}, // привезти в гостиницу rus_verbs:рухнуть{}, // рухнуть в пропасть rus_verbs:пускать{}, // пускать в дело rus_verbs:отвести{}, // отвести в больницу rus_verbs:сойти{}, // сойти в ад rus_verbs:набрать{}, // набрать в команду rus_verbs:собрать{}, // собрать в кулак rus_verbs:двигаться{}, // двигаться в каюту rus_verbs:падать{}, // падать в область нуля rus_verbs:полезть{}, // полезть в драку rus_verbs:направить{}, // направить в стационар rus_verbs:приводить{}, // приводить в чувство rus_verbs:толкнуть{}, // толкнуть в бок rus_verbs:кинуться{}, // кинуться в драку rus_verbs:ткнуть{}, // ткнуть в глаз rus_verbs:заключить{}, // заключить в объятия rus_verbs:подниматься{}, // подниматься в небо rus_verbs:расти{}, // расти в глубину rus_verbs:налить{}, // налить в кружку rus_verbs:швырнуть{}, // швырнуть в бездну rus_verbs:прыгнуть{}, // прыгнуть в дверь rus_verbs:промолчать{}, // промолчать в тряпочку rus_verbs:садиться{}, // садиться в кресло rus_verbs:лить{}, // лить в кувшин rus_verbs:дослать{}, // дослать деталь в держатель rus_verbs:переслать{}, // переслать в обработчик rus_verbs:удалиться{}, // удалиться в совещательную комнату rus_verbs:разглядывать{}, // разглядывать в бинокль rus_verbs:повесить{}, // повесить в шкаф инфинитив:походить{ вид:соверш }, // походить в институт глагол:походить{ вид:соверш }, деепричастие:походив{}, // прилагательное:походивший{вид:соверш}, rus_verbs:помчаться{}, // помчаться в класс rus_verbs:свалиться{}, // свалиться в яму rus_verbs:сбежать{}, // сбежать в Англию rus_verbs:стрелять{}, // стрелять в цель rus_verbs:обращать{}, // обращать в свою веру rus_verbs:завести{}, // завести в дом rus_verbs:приобрести{}, // приобрести в рассрочку rus_verbs:сбросить{}, // сбросить в яму rus_verbs:устроиться{}, // устроиться в крупную корпорацию rus_verbs:погрузиться{}, // погрузиться в пучину rus_verbs:течь{}, // течь в канаву rus_verbs:произвести{}, // произвести в звание майора rus_verbs:метать{}, // метать в цель rus_verbs:пустить{}, // пустить в дело rus_verbs:полететь{}, // полететь в Европу rus_verbs:пропустить{}, // пропустить в здание rus_verbs:рвануть{}, // рвануть в отпуск rus_verbs:заходить{}, // заходить в каморку rus_verbs:нырнуть{}, // нырнуть в прорубь rus_verbs:рвануться{}, // рвануться в атаку rus_verbs:приподняться{}, // приподняться в воздух rus_verbs:превращаться{}, // превращаться в крупную величину rus_verbs:прокричать{}, // прокричать в ухо rus_verbs:записать{}, // записать в блокнот rus_verbs:забраться{}, // забраться в шкаф rus_verbs:приезжать{}, // приезжать в деревню rus_verbs:продать{}, // продать в рабство rus_verbs:проникнуть{}, // проникнуть в центр rus_verbs:устремиться{}, // устремиться в открытое море rus_verbs:посадить{}, // посадить в кресло rus_verbs:упереться{}, // упереться в пол rus_verbs:ринуться{}, // ринуться в буфет rus_verbs:отдавать{}, // отдавать в кадетское училище rus_verbs:отложить{}, // отложить в долгий ящик rus_verbs:убежать{}, // убежать в приют rus_verbs:оценить{}, // оценить в миллион долларов rus_verbs:поднимать{}, // поднимать в стратосферу rus_verbs:отослать{}, // отослать в квалификационную комиссию rus_verbs:отодвинуть{}, // отодвинуть в дальний угол rus_verbs:торопиться{}, // торопиться в школу rus_verbs:попадаться{}, // попадаться в руки rus_verbs:поразить{}, // поразить в самое сердце rus_verbs:доставить{}, // доставить в квартиру rus_verbs:заслать{}, // заслать в тыл rus_verbs:сослать{}, // сослать в изгнание rus_verbs:запустить{}, // запустить в космос rus_verbs:удариться{}, // удариться в запой rus_verbs:ударяться{}, // ударяться в крайность rus_verbs:шептать{}, // шептать в лицо rus_verbs:уронить{}, // уронить в унитаз rus_verbs:прорычать{}, // прорычать в микрофон rus_verbs:засунуть{}, // засунуть в глотку rus_verbs:плыть{}, // плыть в открытое море rus_verbs:перенести{}, // перенести в духовку rus_verbs:светить{}, // светить в лицо rus_verbs:мчаться{}, // мчаться в ремонт rus_verbs:стукнуть{}, // стукнуть в лоб rus_verbs:обрушиться{}, // обрушиться в котлован rus_verbs:поглядывать{}, // поглядывать в экран rus_verbs:уложить{}, // уложить в кроватку инфинитив:попадать{ вид:несоверш }, // попадать в черный список глагол:попадать{ вид:несоверш }, прилагательное:попадающий{ вид:несоверш }, прилагательное:попадавший{ вид:несоверш }, деепричастие:попадая{}, rus_verbs:провалиться{}, // провалиться в яму rus_verbs:жаловаться{}, // жаловаться в комиссию rus_verbs:опоздать{}, // опоздать в школу rus_verbs:посылать{}, // посылать в парикмахерскую rus_verbs:погнать{}, // погнать в хлев rus_verbs:поступать{}, // поступать в институт rus_verbs:усадить{}, // усадить в кресло rus_verbs:проиграть{}, // проиграть в рулетку rus_verbs:прилететь{}, // прилететь в страну rus_verbs:повалиться{}, // повалиться в траву rus_verbs:огрызнуться{}, // Собака огрызнулась в ответ rus_verbs:лезть{}, // лезть в чужие дела rus_verbs:потащить{}, // потащить в суд rus_verbs:направляться{}, // направляться в порт rus_verbs:поползти{}, // поползти в другую сторону rus_verbs:пуститься{}, // пуститься в пляс rus_verbs:забиться{}, // забиться в нору rus_verbs:залезть{}, // залезть в конуру rus_verbs:сдать{}, // сдать в утиль rus_verbs:тронуться{}, // тронуться в путь rus_verbs:сыграть{}, // сыграть в шахматы rus_verbs:перевернуть{}, // перевернуть в более удобную позу rus_verbs:сжимать{}, // сжимать пальцы в кулак rus_verbs:подтолкнуть{}, // подтолкнуть в бок rus_verbs:отнести{}, // отнести животное в лечебницу rus_verbs:одеться{}, // одеться в зимнюю одежду rus_verbs:плюнуть{}, // плюнуть в колодец rus_verbs:передавать{}, // передавать в прокуратуру rus_verbs:отскочить{}, // отскочить в лоб rus_verbs:призвать{}, // призвать в армию rus_verbs:увезти{}, // увезти в деревню rus_verbs:улечься{}, // улечься в кроватку rus_verbs:отшатнуться{}, // отшатнуться в сторону rus_verbs:ложиться{}, // ложиться в постель rus_verbs:пролететь{}, // пролететь в конец rus_verbs:класть{}, // класть в сейф rus_verbs:доставлять{}, // доставлять в кабинет rus_verbs:приобретать{}, // приобретать в кредит rus_verbs:сводить{}, // сводить в театр rus_verbs:унести{}, // унести в могилу rus_verbs:покатиться{}, // покатиться в яму rus_verbs:сходить{}, // сходить в магазинчик rus_verbs:спустить{}, // спустить в канализацию rus_verbs:проникать{}, // проникать в сердцевину rus_verbs:метнуть{}, // метнуть в болвана гневный взгляд rus_verbs:пожаловаться{}, // пожаловаться в администрацию rus_verbs:стучать{}, // стучать в металлическую дверь rus_verbs:тащить{}, // тащить в ремонт rus_verbs:заглядывать{}, // заглядывать в ответы rus_verbs:плюхнуться{}, // плюхнуться в стол ароматного сена rus_verbs:увести{}, // увести в следующий кабинет rus_verbs:успевать{}, // успевать в школу rus_verbs:пробраться{}, // пробраться в собачью конуру rus_verbs:подавать{}, // подавать в суд rus_verbs:прибежать{}, // прибежать в конюшню rus_verbs:рассмотреть{}, // рассмотреть в микроскоп rus_verbs:пнуть{}, // пнуть в живот rus_verbs:завернуть{}, // завернуть в декоративную пленку rus_verbs:уезжать{}, // уезжать в деревню rus_verbs:привлекать{}, // привлекать в свои ряды rus_verbs:перебраться{}, // перебраться в прибрежный город rus_verbs:долить{}, // долить в коктейль rus_verbs:палить{}, // палить в нападающих rus_verbs:отобрать{}, // отобрать в коллекцию rus_verbs:улететь{}, // улететь в неизвестность rus_verbs:выглянуть{}, // выглянуть в окно rus_verbs:выглядывать{}, // выглядывать в окно rus_verbs:пробираться{}, // грабитель, пробирающийся в дом инфинитив:написать{ aux stress="напис^ать"}, // читатель, написавший в блог глагол:написать{ aux stress="напис^ать"}, прилагательное:написавший{ aux stress="напис^авший"}, rus_verbs:свернуть{}, // свернуть в колечко инфинитив:сползать{ вид:несоверш }, // сползать в овраг глагол:сползать{ вид:несоверш }, прилагательное:сползающий{ вид:несоверш }, прилагательное:сползавший{ вид:несоверш }, rus_verbs:барабанить{}, // барабанить в дверь rus_verbs:дописывать{}, // дописывать в конец rus_verbs:меняться{}, // меняться в лучшую сторону rus_verbs:измениться{}, // измениться в лучшую сторону rus_verbs:изменяться{}, // изменяться в лучшую сторону rus_verbs:вписаться{}, // вписаться в поворот rus_verbs:вписываться{}, // вписываться в повороты rus_verbs:переработать{}, // переработать в удобрение rus_verbs:перерабатывать{}, // перерабатывать в удобрение rus_verbs:уползать{}, // уползать в тень rus_verbs:заползать{}, // заползать в нору rus_verbs:перепрятать{}, // перепрятать в укромное место rus_verbs:заталкивать{}, // заталкивать в вагон rus_verbs:преобразовывать{}, // преобразовывать в список инфинитив:конвертировать{ вид:несоверш }, // конвертировать в список глагол:конвертировать{ вид:несоверш }, инфинитив:конвертировать{ вид:соверш }, глагол:конвертировать{ вид:соверш }, деепричастие:конвертировав{}, деепричастие:конвертируя{}, rus_verbs:изорвать{}, // Он изорвал газету в клочки. rus_verbs:выходить{}, // Окна выходят в сад. rus_verbs:говорить{}, // Он говорил в защиту своего отца. rus_verbs:вырастать{}, // Он вырастает в большого художника. rus_verbs:вывести{}, // Он вывел детей в сад. // инфинитив:всыпать{ вид:соверш }, инфинитив:всыпать{ вид:несоверш }, // глагол:всыпать{ вид:соверш }, глагол:всыпать{ вид:несоверш }, // Он всыпал в воду две ложки соли. // прилагательное:раненый{}, // Он был ранен в левую руку. // прилагательное:одетый{}, // Он был одет в толстое осеннее пальто. rus_verbs:бухнуться{}, // Он бухнулся в воду. rus_verbs:склонять{}, // склонять защиту в свою пользу rus_verbs:впиться{}, // Пиявка впилась в тело. rus_verbs:сходиться{}, // Интеллигенты начала века часто сходились в разные союзы rus_verbs:сохранять{}, // сохранить данные в файл rus_verbs:собирать{}, // собирать игрушки в ящик rus_verbs:упаковывать{}, // упаковывать вещи в чемодан rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время rus_verbs:стрельнуть{}, // стрельни в толпу! rus_verbs:пулять{}, // пуляй в толпу rus_verbs:пульнуть{}, // пульни в толпу rus_verbs:становиться{}, // Становитесь в очередь. rus_verbs:вписать{}, // Юля вписала свое имя в список. rus_verbs:вписывать{}, // Мы вписывали свои имена в список прилагательное:видный{}, // Планета Марс видна в обычный бинокль rus_verbs:пойти{}, // Девочка рано пошла в школу rus_verbs:отойти{}, // Эти обычаи отошли в историю. rus_verbs:бить{}, // Холодный ветер бил ему в лицо. rus_verbs:входить{}, // Это входит в его обязанности. rus_verbs:принять{}, // меня приняли в пионеры rus_verbs:уйти{}, // Правительство РФ ушло в отставку rus_verbs:допустить{}, // Япония была допущена в Организацию Объединённых Наций в 1956 году. rus_verbs:посвятить{}, // Я посвятил друга в свою тайну. инфинитив:экспортировать{ вид:несоверш }, глагол:экспортировать{ вид:несоверш }, // экспортировать нефть в страны Востока rus_verbs:взглянуть{}, // Я не смел взглянуть ему в глаза. rus_verbs:идти{}, // Я иду гулять в парк. rus_verbs:вскочить{}, // Я вскочил в трамвай и помчался в институт. rus_verbs:получить{}, // Эту мебель мы получили в наследство от родителей. rus_verbs:везти{}, // Учитель везёт детей в лагерь. rus_verbs:качать{}, // Судно качает во все стороны. rus_verbs:заезжать{}, // Сегодня вечером я заезжал в магазин за книгами. rus_verbs:связать{}, // Свяжите свои вещи в узелок. rus_verbs:пронести{}, // Пронесите стол в дверь. rus_verbs:вынести{}, // Надо вынести примечания в конец. rus_verbs:устроить{}, // Она устроила сына в школу. rus_verbs:угодить{}, // Она угодила головой в дверь. rus_verbs:отвернуться{}, // Она резко отвернулась в сторону. rus_verbs:рассматривать{}, // Она рассматривала сцену в бинокль. rus_verbs:обратить{}, // Война обратила город в развалины. rus_verbs:сойтись{}, // Мы сошлись в школьные годы. rus_verbs:приехать{}, // Мы приехали в положенный час. rus_verbs:встать{}, // Дети встали в круг. rus_verbs:впасть{}, // Из-за болезни он впал в нужду. rus_verbs:придти{}, // придти в упадок rus_verbs:заявить{}, // Надо заявить в милицию о краже. rus_verbs:заявлять{}, // заявлять в полицию rus_verbs:ехать{}, // Мы будем ехать в Орёл rus_verbs:окрашиваться{}, // окрашиваться в красный цвет rus_verbs:решить{}, // Дело решено в пользу истца. rus_verbs:сесть{}, // Она села в кресло rus_verbs:посмотреть{}, // Она посмотрела на себя в зеркало. rus_verbs:влезать{}, // он влезает в мою квартирку rus_verbs:попасться{}, // в мою ловушку попалась мышь rus_verbs:лететь{}, // Мы летим в Орёл ГЛ_ИНФ(брать), // он берет в свою правую руку очень тяжелый шершавый камень ГЛ_ИНФ(взять), // Коля взял в руку камень ГЛ_ИНФ(поехать), // поехать в круиз ГЛ_ИНФ(подать), // подать в отставку инфинитив:засыпать{ вид:соверш }, глагол:засыпать{ вид:соверш }, // засыпать песок в ящик инфинитив:засыпать{ вид:несоверш переходность:переходный }, глагол:засыпать{ вид:несоверш переходность:переходный }, // засыпать песок в ящик ГЛ_ИНФ(впадать), прилагательное:впадающий{}, прилагательное:впадавший{}, деепричастие:впадая{}, // впадать в море ГЛ_ИНФ(постучать) // постучать в дверь } // Чтобы разрешить связывание в паттернах типа: уйти в BEA Systems fact гл_предл { if context { Гл_В_Вин предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_В_Вин предлог:в{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { глагол:подвывать{} предлог:в{} существительное:такт{ падеж:вин } } then return true } #endregion Винительный // Все остальные варианты по умолчанию запрещаем. fact гл_предл { if context { * предлог:в{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:в{} *:*{ падеж:мест } } then return false,-3 } fact гл_предл { if context { * предлог:в{} *:*{ падеж:вин } } then return false,-4 } fact гл_предл { if context { * предлог:в{} * } then return false,-5 } #endregion Предлог_В #region Предлог_НА // ------------------- С ПРЕДЛОГОМ 'НА' --------------------------- #region ПРЕДЛОЖНЫЙ // НА+предложный падеж: // ЛЕЖАТЬ НА СТОЛЕ #region VerbList wordentry_set Гл_НА_Предл= { rus_verbs:заслушать{}, // Вопрос заслушали на сессии облсовета rus_verbs:ПРОСТУПАТЬ{}, // На лбу, носу и щеке проступало черное пятно кровоподтека. (ПРОСТУПАТЬ/ПРОСТУПИТЬ) rus_verbs:ПРОСТУПИТЬ{}, // rus_verbs:ВИДНЕТЬСЯ{}, // На другой стороне Океана виднелась полоска суши, окружавшая нижний ярус планеты. (ВИДНЕТЬСЯ) rus_verbs:ЗАВИСАТЬ{}, // Машина умела зависать в воздухе на любой высоте (ЗАВИСАТЬ) rus_verbs:ЗАМЕРЕТЬ{}, // Скользнув по траве, он замер на боку (ЗАМЕРЕТЬ, локатив) rus_verbs:ЗАМИРАТЬ{}, // rus_verbs:ЗАКРЕПИТЬ{}, // Он вручил ей лишний кинжал, который она воткнула в рубаху и закрепила на подоле. (ЗАКРЕПИТЬ) rus_verbs:УПОЛЗТИ{}, // Зверь завизжал и попытался уползти на двух невредимых передних ногах. (УПОЛЗТИ/УПОЛЗАТЬ) rus_verbs:УПОЛЗАТЬ{}, // rus_verbs:БОЛТАТЬСЯ{}, // Тело его будет болтаться на пространственных ветрах, пока не сгниет веревка. (БОЛТАТЬСЯ) rus_verbs:РАЗВЕРНУТЬ{}, // Филиппины разрешат США развернуть военные базы на своей территории (РАЗВЕРНУТЬ) rus_verbs:ПОЛУЧИТЬ{}, // Я пытался узнать секреты и получить советы на официальном русскоязычном форуме (ПОЛУЧИТЬ) rus_verbs:ЗАСИЯТЬ{}, // Он активировал управление, и на экране снова засияло изображение полумесяца. (ЗАСИЯТЬ) rus_verbs:ВЗОРВАТЬСЯ{}, // Смертник взорвался на предвыборном митинге в Пакистане (ВЗОРВАТЬСЯ) rus_verbs:искриться{}, rus_verbs:ОДЕРЖИВАТЬ{}, // На выборах в иранский парламент победу одерживают противники действующего президента (ОДЕРЖИВАТЬ) rus_verbs:ПРЕСЕЧЬ{}, // На Украине пресекли дерзкий побег заключенных на вертолете (ПРЕСЕЧЬ) rus_verbs:УЛЕТЕТЬ{}, // Голый норвежец улетел на лыжах с трамплина на 60 метров (УЛЕТЕТЬ) rus_verbs:ПРОХОДИТЬ{}, // укрывающийся в лесу американский подросток проходил инициацию на охоте, выпив кружку крови первого убитого им оленя (ПРОХОДИТЬ) rus_verbs:СУЩЕСТВОВАТЬ{}, // На Марсе существовали условия для жизни (СУЩЕСТВОВАТЬ) rus_verbs:УКАЗАТЬ{}, // Победу в Лиге чемпионов укажут на часах (УКАЗАТЬ) rus_verbs:отвести{}, // отвести душу на людях rus_verbs:сходиться{}, // Оба профессора сходились на том, что в черепной коробке динозавра rus_verbs:сойтись{}, rus_verbs:ОБНАРУЖИТЬ{}, // Доказательство наличия подповерхностного океана на Европе обнаружено на её поверхности (ОБНАРУЖИТЬ) rus_verbs:НАБЛЮДАТЬСЯ{}, // Редкий зодиакальный свет вскоре будет наблюдаться на ночном небе (НАБЛЮДАТЬСЯ) rus_verbs:ДОСТИГНУТЬ{}, // На всех аварийных реакторах достигнуто состояние так называемой холодной остановки (ДОСТИГНУТЬ/ДОСТИЧЬ) глагол:ДОСТИЧЬ{}, инфинитив:ДОСТИЧЬ{}, rus_verbs:завершить{}, // Российские биатлонисты завершили чемпионат мира на мажорной ноте rus_verbs:РАСКЛАДЫВАТЬ{}, rus_verbs:ФОКУСИРОВАТЬСЯ{}, // Инвесторы предпочитают фокусироваться на среднесрочных ожиданиях (ФОКУСИРОВАТЬСЯ) rus_verbs:ВОСПРИНИМАТЬ{}, // как несерьезно воспринимали его на выборах мэра (ВОСПРИНИМАТЬ) rus_verbs:БУШЕВАТЬ{}, // на территории Тверской области бушевала гроза , в результате которой произошло отключение электроснабжения в ряде муниципальных образований региона (БУШЕВАТЬ) rus_verbs:УЧАСТИТЬСЯ{}, // В последние месяцы в зоне ответственности бундесвера на севере Афганистана участились случаи обстрелов полевых лагерей немецких миротворцев (УЧАСТИТЬСЯ) rus_verbs:ВЫИГРАТЬ{}, // Почему женская сборная России не может выиграть медаль на чемпионате мира (ВЫИГРАТЬ) rus_verbs:ПРОПАСТЬ{}, // Пропавшим на прогулке актером заинтересовались следователи (ПРОПАСТЬ) rus_verbs:УБИТЬ{}, // Силовики убили двух боевиков на административной границе Ингушетии и Чечни (УБИТЬ) rus_verbs:подпрыгнуть{}, // кобель нелепо подпрыгнул на трех ногах , а его хозяин отправил струю пива мимо рта rus_verbs:подпрыгивать{}, rus_verbs:высветиться{}, // на компьютере высветится твоя подпись rus_verbs:фигурировать{}, // его портрет фигурирует на страницах печати и телеэкранах rus_verbs:действовать{}, // выявленный контрабандный канал действовал на постоянной основе rus_verbs:СОХРАНИТЬСЯ{}, // На рынке международных сделок IPO сохранится высокая активность (СОХРАНИТЬСЯ НА) rus_verbs:ПРОЙТИ{}, // Необычный конкурс прошёл на севере Швеции (ПРОЙТИ НА предл) rus_verbs:НАЧАТЬСЯ{}, // На северо-востоке США началась сильная снежная буря. (НАЧАТЬСЯ НА предл) rus_verbs:ВОЗНИКНУТЬ{}, // Конфликт возник на почве совместной коммерческой деятельности по выращиванию овощей и зелени (ВОЗНИКНУТЬ НА) rus_verbs:СВЕТИТЬСЯ{}, // она по-прежнему светится на лицах людей (СВЕТИТЬСЯ НА предл) rus_verbs:ОРГАНИЗОВАТЬ{}, // Власти Москвы намерены организовать масленичные гуляния на 100 площадках (ОРГАНИЗОВАТЬ НА предл) rus_verbs:ИМЕТЬ{}, // Имея власть на низовом уровне, оказывать самое непосредственное и определяющее влияние на верховную власть (ИМЕТЬ НА предл) rus_verbs:ОПРОБОВАТЬ{}, // Опробовать и отточить этот инструмент на местных и региональных выборах (ОПРОБОВАТЬ, ОТТОЧИТЬ НА предл) rus_verbs:ОТТОЧИТЬ{}, rus_verbs:ДОЛОЖИТЬ{}, // Участникам совещания предложено подготовить по этому вопросу свои предложения и доложить на повторной встрече (ДОЛОЖИТЬ НА предл) rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Солевые и пылевые бури , образующиеся на поверхности обнаженной площади моря , уничтожают урожаи и растительность (ОБРАЗОВЫВАТЬСЯ НА) rus_verbs:СОБРАТЬ{}, // использует собранные на местном рынке депозиты (СОБРАТЬ НА предл) инфинитив:НАХОДИТЬСЯ{ вид:несоверш}, // находившихся на борту самолета (НАХОДИТЬСЯ НА предл) глагол:НАХОДИТЬСЯ{ вид:несоверш }, прилагательное:находившийся{ вид:несоверш }, прилагательное:находящийся{ вид:несоверш }, деепричастие:находясь{}, rus_verbs:ГОТОВИТЬ{}, // пищу готовят сами на примусах (ГОТОВИТЬ НА предл) rus_verbs:РАЗДАТЬСЯ{}, // Они сообщили о сильном хлопке , который раздался на территории нефтебазы (РАЗДАТЬСЯ НА) rus_verbs:ПОДСКАЛЬЗЫВАТЬСЯ{}, // подскальзываться на той же апельсиновой корке (ПОДСКАЛЬЗЫВАТЬСЯ НА) rus_verbs:СКРЫТЬСЯ{}, // Германия: латвиец ограбил магазин и попытался скрыться на такси (СКРЫТЬСЯ НА предл) rus_verbs:ВЫРАСТИТЬ{}, // Пациенту вырастили новый нос на руке (ВЫРАСТИТЬ НА) rus_verbs:ПРОДЕМОНСТРИРОВАТЬ{}, // Они хотят подчеркнуть эмоциональную тонкость оппозиционера и на этом фоне продемонстрировать бездушность российской власти (ПРОДЕМОНСТРИРОВАТЬ НА предл) rus_verbs:ОСУЩЕСТВЛЯТЬСЯ{}, // первичный анализ смеси запахов может осуществляться уже на уровне рецепторных нейронов благодаря механизму латерального торможения (ОСУЩЕСТВЛЯТЬСЯ НА) rus_verbs:ВЫДЕЛЯТЬСЯ{}, // Ягоды брусники, резко выделяющиеся своим красным цветом на фоне зелёной листвы, поедаются животными и птицами (ВЫДЕЛЯТЬСЯ НА) rus_verbs:РАСКРЫТЬ{}, // На Украине раскрыто крупное мошенничество в сфере туризма (РАСКРЫТЬ НА) rus_verbs:ОБЖАРИВАТЬСЯ{}, // Омлет обжаривается на сливочном масле с одной стороны, пока он почти полностью не загустеет (ОБЖАРИВАТЬСЯ НА) rus_verbs:ПРИГОТОВЛЯТЬ{}, // Яичница — блюдо европейской кухни, приготовляемое на сковороде из разбитых яиц (ПРИГОТОВЛЯТЬ НА) rus_verbs:РАССАДИТЬ{}, // Женька рассадил игрушки на скамеечке (РАССАДИТЬ НА) rus_verbs:ОБОЖДАТЬ{}, // обожди Анжелу на остановке троллейбуса (ОБОЖДАТЬ НА) rus_verbs:УЧИТЬСЯ{}, // Марина учится на факультете журналистики (УЧИТЬСЯ НА предл) rus_verbs:раскладываться{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА) rus_verbs:ПОСЛУШАТЬ{}, // Послушайте друзей и врагов на расстоянии! (ПОСЛУШАТЬ НА) rus_verbs:ВЕСТИСЬ{}, // На стороне противника всю ночь велась перегруппировка сил. (ВЕСТИСЬ НА) rus_verbs:ПОИНТЕРЕСОВАТЬСЯ{}, // корреспондент поинтересовался у людей на улице (ПОИНТЕРЕСОВАТЬСЯ НА) rus_verbs:ОТКРЫВАТЬСЯ{}, // Российские биржи открываются на негативном фоне (ОТКРЫВАТЬСЯ НА) rus_verbs:СХОДИТЬ{}, // Вы сходите на следующей остановке? (СХОДИТЬ НА) rus_verbs:ПОГИБНУТЬ{}, // Её отец погиб на войне. (ПОГИБНУТЬ НА) rus_verbs:ВЫЙТИ{}, // Книга выйдет на будущей неделе. (ВЫЙТИ НА предл) rus_verbs:НЕСТИСЬ{}, // Корабль несётся на всех парусах. (НЕСТИСЬ НА предл) rus_verbs:вкалывать{}, // Папа вкалывает на работе, чтобы прокормить семью (вкалывать на) rus_verbs:доказать{}, // разработчики доказали на практике применимость данного подхода к обсчету сцен (доказать на, применимость к) rus_verbs:хулиганить{}, // дозволять кому-то хулиганить на кладбище (хулиганить на) глагол:вычитать{вид:соверш}, инфинитив:вычитать{вид:соверш}, // вычитать на сайте (вычитать на сайте) деепричастие:вычитав{}, rus_verbs:аккомпанировать{}, // он аккомпанировал певцу на губной гармошке (аккомпанировать на) rus_verbs:набрать{}, // статья с заголовком, набранным на компьютере rus_verbs:сделать{}, // книга с иллюстрацией, сделанной на компьютере rus_verbs:развалиться{}, // Антонио развалился на диване rus_verbs:улечься{}, // Антонио улегся на полу rus_verbs:зарубить{}, // Заруби себе на носу. rus_verbs:ценить{}, // Его ценят на заводе. rus_verbs:вернуться{}, // Отец вернулся на закате. rus_verbs:шить{}, // Вы умеете шить на машинке? rus_verbs:бить{}, // Скот бьют на бойне. rus_verbs:выехать{}, // Мы выехали на рассвете. rus_verbs:валяться{}, // На полу валяется бумага. rus_verbs:разложить{}, // она разложила полотенце на песке rus_verbs:заниматься{}, // я занимаюсь на тренажере rus_verbs:позаниматься{}, rus_verbs:порхать{}, // порхать на лугу rus_verbs:пресекать{}, // пресекать на корню rus_verbs:изъясняться{}, // изъясняться на непонятном языке rus_verbs:развесить{}, // развесить на столбах rus_verbs:обрасти{}, // обрасти на южной части rus_verbs:откладываться{}, // откладываться на стенках артерий rus_verbs:уносить{}, // уносить на носилках rus_verbs:проплыть{}, // проплыть на плоту rus_verbs:подъезжать{}, // подъезжать на повозках rus_verbs:пульсировать{}, // пульсировать на лбу rus_verbs:рассесться{}, // птицы расселись на ветках rus_verbs:застопориться{}, // застопориться на первом пункте rus_verbs:изловить{}, // изловить на окраинах rus_verbs:покататься{}, // покататься на машинках rus_verbs:залопотать{}, // залопотать на неизвестном языке rus_verbs:растягивать{}, // растягивать на станке rus_verbs:поделывать{}, // поделывать на пляже rus_verbs:подстеречь{}, // подстеречь на площадке rus_verbs:проектировать{}, // проектировать на компьютере rus_verbs:притулиться{}, // притулиться на кушетке rus_verbs:дозволять{}, // дозволять кому-то хулиганить на кладбище rus_verbs:пострелять{}, // пострелять на испытательном полигоне rus_verbs:засиживаться{}, // засиживаться на работе rus_verbs:нежиться{}, // нежиться на солнышке rus_verbs:притомиться{}, // притомиться на рабочем месте rus_verbs:поселяться{}, // поселяться на чердаке rus_verbs:потягиваться{}, // потягиваться на земле rus_verbs:отлеживаться{}, // отлеживаться на койке rus_verbs:протаранить{}, // протаранить на танке rus_verbs:гарцевать{}, // гарцевать на коне rus_verbs:облупиться{}, // облупиться на носу rus_verbs:оговорить{}, // оговорить на собеседовании rus_verbs:зарегистрироваться{}, // зарегистрироваться на сайте rus_verbs:отпечатать{}, // отпечатать на картоне rus_verbs:сэкономить{}, // сэкономить на мелочах rus_verbs:покатать{}, // покатать на пони rus_verbs:колесить{}, // колесить на старой машине rus_verbs:понастроить{}, // понастроить на участках rus_verbs:поджарить{}, // поджарить на костре rus_verbs:узнаваться{}, // узнаваться на фотографии rus_verbs:отощать{}, // отощать на казенных харчах rus_verbs:редеть{}, // редеть на макушке rus_verbs:оглашать{}, // оглашать на общем собрании rus_verbs:лопотать{}, // лопотать на иврите rus_verbs:пригреть{}, // пригреть на груди rus_verbs:консультироваться{}, // консультироваться на форуме rus_verbs:приноситься{}, // приноситься на одежде rus_verbs:сушиться{}, // сушиться на балконе rus_verbs:наследить{}, // наследить на полу rus_verbs:нагреться{}, // нагреться на солнце rus_verbs:рыбачить{}, // рыбачить на озере rus_verbs:прокатить{}, // прокатить на выборах rus_verbs:запинаться{}, // запинаться на ровном месте rus_verbs:отрубиться{}, // отрубиться на мягкой подушке rus_verbs:заморозить{}, // заморозить на улице rus_verbs:промерзнуть{}, // промерзнуть на открытом воздухе rus_verbs:просохнуть{}, // просохнуть на батарее rus_verbs:развозить{}, // развозить на велосипеде rus_verbs:прикорнуть{}, // прикорнуть на диванчике rus_verbs:отпечататься{}, // отпечататься на коже rus_verbs:выявлять{}, // выявлять на таможне rus_verbs:расставлять{}, // расставлять на башнях rus_verbs:прокрутить{}, // прокрутить на пальце rus_verbs:умываться{}, // умываться на улице rus_verbs:пересказывать{}, // пересказывать на страницах романа rus_verbs:удалять{}, // удалять на пуховике rus_verbs:хозяйничать{}, // хозяйничать на складе rus_verbs:оперировать{}, // оперировать на поле боя rus_verbs:поносить{}, // поносить на голове rus_verbs:замурлыкать{}, // замурлыкать на коленях rus_verbs:передвигать{}, // передвигать на тележке rus_verbs:прочертить{}, // прочертить на земле rus_verbs:колдовать{}, // колдовать на кухне rus_verbs:отвозить{}, // отвозить на казенном транспорте rus_verbs:трахать{}, // трахать на природе rus_verbs:мастерить{}, // мастерить на кухне rus_verbs:ремонтировать{}, // ремонтировать на коленке rus_verbs:развезти{}, // развезти на велосипеде rus_verbs:робеть{}, // робеть на сцене инфинитив:реализовать{ вид:несоверш }, инфинитив:реализовать{ вид:соверш }, // реализовать на сайте глагол:реализовать{ вид:несоверш }, глагол:реализовать{ вид:соверш }, деепричастие:реализовав{}, деепричастие:реализуя{}, rus_verbs:покаяться{}, // покаяться на смертном одре rus_verbs:специализироваться{}, // специализироваться на тестировании rus_verbs:попрыгать{}, // попрыгать на батуте rus_verbs:переписывать{}, // переписывать на столе rus_verbs:расписывать{}, // расписывать на доске rus_verbs:зажимать{}, // зажимать на запястье rus_verbs:практиковаться{}, // практиковаться на мышах rus_verbs:уединиться{}, // уединиться на чердаке rus_verbs:подохнуть{}, // подохнуть на чужбине rus_verbs:приподниматься{}, // приподниматься на руках rus_verbs:уродиться{}, // уродиться на полях rus_verbs:продолжиться{}, // продолжиться на улице rus_verbs:посапывать{}, // посапывать на диване rus_verbs:ободрать{}, // ободрать на спине rus_verbs:скрючиться{}, // скрючиться на песке rus_verbs:тормознуть{}, // тормознуть на перекрестке rus_verbs:лютовать{}, // лютовать на хуторе rus_verbs:зарегистрировать{}, // зарегистрировать на сайте rus_verbs:переждать{}, // переждать на вершине холма rus_verbs:доминировать{}, // доминировать на территории rus_verbs:публиковать{}, // публиковать на сайте rus_verbs:морщить{}, // морщить на лбу rus_verbs:сконцентрироваться{}, // сконцентрироваться на главном rus_verbs:подрабатывать{}, // подрабатывать на рынке rus_verbs:репетировать{}, // репетировать на заднем дворе rus_verbs:подвернуть{}, // подвернуть на брусчатке rus_verbs:зашелестеть{}, // зашелестеть на ветру rus_verbs:расчесывать{}, // расчесывать на спине rus_verbs:одевать{}, // одевать на рынке rus_verbs:испечь{}, // испечь на углях rus_verbs:сбрить{}, // сбрить на затылке rus_verbs:согреться{}, // согреться на печке rus_verbs:замаячить{}, // замаячить на горизонте rus_verbs:пересчитывать{}, // пересчитывать на пальцах rus_verbs:галдеть{}, // галдеть на крыльце rus_verbs:переплыть{}, // переплыть на плоту rus_verbs:передохнуть{}, // передохнуть на скамейке rus_verbs:прижиться{}, // прижиться на ферме rus_verbs:переправляться{}, // переправляться на плотах rus_verbs:накупить{}, // накупить на блошином рынке rus_verbs:проторчать{}, // проторчать на виду rus_verbs:мокнуть{}, // мокнуть на улице rus_verbs:застукать{}, // застукать на камбузе rus_verbs:завязывать{}, // завязывать на ботинках rus_verbs:повисать{}, // повисать на ветке rus_verbs:подвизаться{}, // подвизаться на государственной службе rus_verbs:кормиться{}, // кормиться на болоте rus_verbs:покурить{}, // покурить на улице rus_verbs:зимовать{}, // зимовать на болотах rus_verbs:застегивать{}, // застегивать на гимнастерке rus_verbs:поигрывать{}, // поигрывать на гитаре rus_verbs:погореть{}, // погореть на махинациях с землей rus_verbs:кувыркаться{}, // кувыркаться на батуте rus_verbs:похрапывать{}, // похрапывать на диване rus_verbs:пригревать{}, // пригревать на груди rus_verbs:завязнуть{}, // завязнуть на болоте rus_verbs:шастать{}, // шастать на втором этаже rus_verbs:заночевать{}, // заночевать на сеновале rus_verbs:отсиживаться{}, // отсиживаться на чердаке rus_verbs:мчать{}, // мчать на байке rus_verbs:сгнить{}, // сгнить на урановых рудниках rus_verbs:тренировать{}, // тренировать на манекенах rus_verbs:повеселиться{}, // повеселиться на празднике rus_verbs:измучиться{}, // измучиться на болоте rus_verbs:увянуть{}, // увянуть на подоконнике rus_verbs:раскрутить{}, // раскрутить на оси rus_verbs:выцвести{}, // выцвести на солнечном свету rus_verbs:изготовлять{}, // изготовлять на коленке rus_verbs:гнездиться{}, // гнездиться на вершине дерева rus_verbs:разогнаться{}, // разогнаться на мотоцикле rus_verbs:излагаться{}, // излагаться на страницах доклада rus_verbs:сконцентрировать{}, // сконцентрировать на левом фланге rus_verbs:расчесать{}, // расчесать на макушке rus_verbs:плавиться{}, // плавиться на солнце rus_verbs:редактировать{}, // редактировать на ноутбуке rus_verbs:подскакивать{}, // подскакивать на месте rus_verbs:покупаться{}, // покупаться на рынке rus_verbs:промышлять{}, // промышлять на мелководье rus_verbs:приобретаться{}, // приобретаться на распродажах rus_verbs:наигрывать{}, // наигрывать на банджо rus_verbs:маневрировать{}, // маневрировать на флангах rus_verbs:запечатлеться{}, // запечатлеться на записях камер rus_verbs:укрывать{}, // укрывать на чердаке rus_verbs:подорваться{}, // подорваться на фугасе rus_verbs:закрепиться{}, // закрепиться на занятых позициях rus_verbs:громыхать{}, // громыхать на кухне инфинитив:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:соверш }, // подвигаться на полу деепричастие:подвигавшись{}, rus_verbs:добываться{}, // добываться на территории Анголы rus_verbs:приплясывать{}, // приплясывать на сцене rus_verbs:доживать{}, // доживать на больничной койке rus_verbs:отпраздновать{}, // отпраздновать на работе rus_verbs:сгубить{}, // сгубить на корню rus_verbs:схоронить{}, // схоронить на кладбище rus_verbs:тускнеть{}, // тускнеть на солнце rus_verbs:скопить{}, // скопить на счету rus_verbs:помыть{}, // помыть на своем этаже rus_verbs:пороть{}, // пороть на конюшне rus_verbs:наличествовать{}, // наличествовать на складе rus_verbs:нащупывать{}, // нащупывать на полке rus_verbs:змеиться{}, // змеиться на дне rus_verbs:пожелтеть{}, // пожелтеть на солнце rus_verbs:заостриться{}, // заостриться на конце rus_verbs:свезти{}, // свезти на поле rus_verbs:прочувствовать{}, // прочувствовать на своей шкуре rus_verbs:подкрутить{}, // подкрутить на приборной панели rus_verbs:рубиться{}, // рубиться на мечах rus_verbs:сиживать{}, // сиживать на крыльце rus_verbs:тараторить{}, // тараторить на иностранном языке rus_verbs:теплеть{}, // теплеть на сердце rus_verbs:покачаться{}, // покачаться на ветке rus_verbs:сосредоточиваться{}, // сосредоточиваться на главной задаче rus_verbs:развязывать{}, // развязывать на ботинках rus_verbs:подвозить{}, // подвозить на мотороллере rus_verbs:вышивать{}, // вышивать на рубашке rus_verbs:скупать{}, // скупать на открытом рынке rus_verbs:оформлять{}, // оформлять на встрече rus_verbs:распускаться{}, // распускаться на клумбах rus_verbs:прогореть{}, // прогореть на спекуляциях rus_verbs:приползти{}, // приползти на коленях rus_verbs:загореть{}, // загореть на пляже rus_verbs:остудить{}, // остудить на балконе rus_verbs:нарвать{}, // нарвать на поляне rus_verbs:издохнуть{}, // издохнуть на болоте rus_verbs:разгружать{}, // разгружать на дороге rus_verbs:произрастать{}, // произрастать на болотах rus_verbs:разуться{}, // разуться на коврике rus_verbs:сооружать{}, // сооружать на площади rus_verbs:зачитывать{}, // зачитывать на митинге rus_verbs:уместиться{}, // уместиться на ладони rus_verbs:закупить{}, // закупить на рынке rus_verbs:горланить{}, // горланить на улице rus_verbs:экономить{}, // экономить на спичках rus_verbs:исправлять{}, // исправлять на доске rus_verbs:расслабляться{}, // расслабляться на лежаке rus_verbs:скапливаться{}, // скапливаться на крыше rus_verbs:сплетничать{}, // сплетничать на скамеечке rus_verbs:отъезжать{}, // отъезжать на лимузине rus_verbs:отчитывать{}, // отчитывать на собрании rus_verbs:сфокусировать{}, // сфокусировать на удаленной точке rus_verbs:потчевать{}, // потчевать на лаврах rus_verbs:окопаться{}, // окопаться на окраине rus_verbs:загорать{}, // загорать на пляже rus_verbs:обгореть{}, // обгореть на солнце rus_verbs:распознавать{}, // распознавать на фотографии rus_verbs:заплетаться{}, // заплетаться на макушке rus_verbs:перегреться{}, // перегреться на жаре rus_verbs:подметать{}, // подметать на крыльце rus_verbs:нарисоваться{}, // нарисоваться на горизонте rus_verbs:проскакивать{}, // проскакивать на экране rus_verbs:попивать{}, // попивать на балконе чай rus_verbs:отплывать{}, // отплывать на лодке rus_verbs:чирикать{}, // чирикать на ветках rus_verbs:скупить{}, // скупить на оптовых базах rus_verbs:наколоть{}, // наколоть на коже картинку rus_verbs:созревать{}, // созревать на ветке rus_verbs:проколоться{}, // проколоться на мелочи rus_verbs:крутнуться{}, // крутнуться на заднем колесе rus_verbs:переночевать{}, // переночевать на постоялом дворе rus_verbs:концентрироваться{}, // концентрироваться на фильтре rus_verbs:одичать{}, // одичать на хуторе rus_verbs:спасаться{}, // спасаются на лодке rus_verbs:доказываться{}, // доказываться на страницах книги rus_verbs:познаваться{}, // познаваться на ринге rus_verbs:замыкаться{}, // замыкаться на металлическом предмете rus_verbs:заприметить{}, // заприметить на пригорке rus_verbs:продержать{}, // продержать на морозе rus_verbs:форсировать{}, // форсировать на плотах rus_verbs:сохнуть{}, // сохнуть на солнце rus_verbs:выявить{}, // выявить на поверхности rus_verbs:заседать{}, // заседать на кафедре rus_verbs:расплачиваться{}, // расплачиваться на выходе rus_verbs:светлеть{}, // светлеть на горизонте rus_verbs:залепетать{}, // залепетать на незнакомом языке rus_verbs:подсчитывать{}, // подсчитывать на пальцах rus_verbs:зарыть{}, // зарыть на пустыре rus_verbs:сформироваться{}, // сформироваться на месте rus_verbs:развертываться{}, // развертываться на площадке rus_verbs:набивать{}, // набивать на манекенах rus_verbs:замерзать{}, // замерзать на ветру rus_verbs:схватывать{}, // схватывать на лету rus_verbs:перевестись{}, // перевестись на Руси rus_verbs:смешивать{}, // смешивать на блюдце rus_verbs:прождать{}, // прождать на входе rus_verbs:мерзнуть{}, // мерзнуть на ветру rus_verbs:растирать{}, // растирать на коже rus_verbs:переспать{}, // переспал на сеновале rus_verbs:рассекать{}, // рассекать на скутере rus_verbs:опровергнуть{}, // опровергнуть на высшем уровне rus_verbs:дрыхнуть{}, // дрыхнуть на диване rus_verbs:распять{}, // распять на кресте rus_verbs:запечься{}, // запечься на костре rus_verbs:застилать{}, // застилать на балконе rus_verbs:сыскаться{}, // сыскаться на огороде rus_verbs:разориться{}, // разориться на продаже спичек rus_verbs:переделать{}, // переделать на станке rus_verbs:разъяснять{}, // разъяснять на страницах газеты rus_verbs:поседеть{}, // поседеть на висках rus_verbs:протащить{}, // протащить на спине rus_verbs:осуществиться{}, // осуществиться на деле rus_verbs:селиться{}, // селиться на окраине rus_verbs:оплачивать{}, // оплачивать на первой кассе rus_verbs:переворачивать{}, // переворачивать на сковородке rus_verbs:упражняться{}, // упражняться на батуте rus_verbs:испробовать{}, // испробовать на себе rus_verbs:разгладиться{}, // разгладиться на спине rus_verbs:рисоваться{}, // рисоваться на стекле rus_verbs:продрогнуть{}, // продрогнуть на морозе rus_verbs:пометить{}, // пометить на доске rus_verbs:приютить{}, // приютить на чердаке rus_verbs:избирать{}, // избирать на первых свободных выборах rus_verbs:затеваться{}, // затеваться на матче rus_verbs:уплывать{}, // уплывать на катере rus_verbs:замерцать{}, // замерцать на рекламном щите rus_verbs:фиксироваться{}, // фиксироваться на достигнутом уровне rus_verbs:запираться{}, // запираться на чердаке rus_verbs:загубить{}, // загубить на корню rus_verbs:развеяться{}, // развеяться на природе rus_verbs:съезжаться{}, // съезжаться на лимузинах rus_verbs:потанцевать{}, // потанцевать на могиле rus_verbs:дохнуть{}, // дохнуть на солнце rus_verbs:припарковаться{}, // припарковаться на газоне rus_verbs:отхватить{}, // отхватить на распродаже rus_verbs:остывать{}, // остывать на улице rus_verbs:переваривать{}, // переваривать на высокой ветке rus_verbs:подвесить{}, // подвесить на веревке rus_verbs:хвастать{}, // хвастать на работе rus_verbs:отрабатывать{}, // отрабатывать на уборке урожая rus_verbs:разлечься{}, // разлечься на полу rus_verbs:очертить{}, // очертить на полу rus_verbs:председательствовать{}, // председательствовать на собрании rus_verbs:сконфузиться{}, // сконфузиться на сцене rus_verbs:выявляться{}, // выявляться на ринге rus_verbs:крутануться{}, // крутануться на заднем колесе rus_verbs:караулить{}, // караулить на входе rus_verbs:перечислять{}, // перечислять на пальцах rus_verbs:обрабатывать{}, // обрабатывать на станке rus_verbs:настигать{}, // настигать на берегу rus_verbs:разгуливать{}, // разгуливать на берегу rus_verbs:насиловать{}, // насиловать на пляже rus_verbs:поредеть{}, // поредеть на макушке rus_verbs:учитывать{}, // учитывать на балансе rus_verbs:зарождаться{}, // зарождаться на большой глубине rus_verbs:распространять{}, // распространять на сайтах rus_verbs:пировать{}, // пировать на вершине холма rus_verbs:начертать{}, // начертать на стене rus_verbs:расцветать{}, // расцветать на подоконнике rus_verbs:умнеть{}, // умнеть на глазах rus_verbs:царствовать{}, // царствовать на окраине rus_verbs:закрутиться{}, // закрутиться на работе rus_verbs:отработать{}, // отработать на шахте rus_verbs:полечь{}, // полечь на поле брани rus_verbs:щебетать{}, // щебетать на ветке rus_verbs:подчеркиваться{}, // подчеркиваться на сайте rus_verbs:посеять{}, // посеять на другом поле rus_verbs:замечаться{}, // замечаться на пастбище rus_verbs:просчитать{}, // просчитать на пальцах rus_verbs:голосовать{}, // голосовать на трассе rus_verbs:маяться{}, // маяться на пляже rus_verbs:сколотить{}, // сколотить на службе rus_verbs:обретаться{}, // обретаться на чужбине rus_verbs:обливаться{}, // обливаться на улице rus_verbs:катать{}, // катать на лошадке rus_verbs:припрятать{}, // припрятать на теле rus_verbs:запаниковать{}, // запаниковать на экзамене инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать на частном самолете деепричастие:слетав{}, rus_verbs:срубить{}, // срубить денег на спекуляциях rus_verbs:зажигаться{}, // зажигаться на улице rus_verbs:жарить{}, // жарить на углях rus_verbs:накапливаться{}, // накапливаться на счету rus_verbs:распуститься{}, // распуститься на грядке rus_verbs:рассаживаться{}, // рассаживаться на местах rus_verbs:странствовать{}, // странствовать на лошади rus_verbs:осматриваться{}, // осматриваться на месте rus_verbs:разворачивать{}, // разворачивать на завоеванной территории rus_verbs:согревать{}, // согревать на вершине горы rus_verbs:заскучать{}, // заскучать на вахте rus_verbs:перекусить{}, // перекусить на бегу rus_verbs:приплыть{}, // приплыть на тримаране rus_verbs:зажигать{}, // зажигать на танцах rus_verbs:закопать{}, // закопать на поляне rus_verbs:стирать{}, // стирать на берегу rus_verbs:подстерегать{}, // подстерегать на подходе rus_verbs:погулять{}, // погулять на свадьбе rus_verbs:огласить{}, // огласить на митинге rus_verbs:разбогатеть{}, // разбогатеть на прииске rus_verbs:грохотать{}, // грохотать на чердаке rus_verbs:расположить{}, // расположить на границе rus_verbs:реализоваться{}, // реализоваться на новой работе rus_verbs:застывать{}, // застывать на морозе rus_verbs:запечатлеть{}, // запечатлеть на пленке rus_verbs:тренироваться{}, // тренироваться на манекене rus_verbs:поспорить{}, // поспорить на совещании rus_verbs:затягивать{}, // затягивать на поясе rus_verbs:зиждиться{}, // зиждиться на твердой основе rus_verbs:построиться{}, // построиться на песке rus_verbs:надрываться{}, // надрываться на работе rus_verbs:закипать{}, // закипать на плите rus_verbs:затонуть{}, // затонуть на мелководье rus_verbs:побыть{}, // побыть на фазенде rus_verbs:сгорать{}, // сгорать на солнце инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на улице деепричастие:пописав{ aux stress="поп^исав" }, rus_verbs:подраться{}, // подраться на сцене rus_verbs:заправить{}, // заправить на последней заправке rus_verbs:обозначаться{}, // обозначаться на карте rus_verbs:просиживать{}, // просиживать на берегу rus_verbs:начертить{}, // начертить на листке rus_verbs:тормозить{}, // тормозить на льду rus_verbs:затевать{}, // затевать на космической базе rus_verbs:задерживать{}, // задерживать на таможне rus_verbs:прилетать{}, // прилетать на частном самолете rus_verbs:полулежать{}, // полулежать на травке rus_verbs:ерзать{}, // ерзать на табуретке rus_verbs:покопаться{}, // покопаться на складе rus_verbs:подвезти{}, // подвезти на машине rus_verbs:полежать{}, // полежать на водном матрасе rus_verbs:стыть{}, // стыть на улице rus_verbs:стынуть{}, // стынуть на улице rus_verbs:скреститься{}, // скреститься на груди rus_verbs:припарковать{}, // припарковать на стоянке rus_verbs:здороваться{}, // здороваться на кафедре rus_verbs:нацарапать{}, // нацарапать на парте rus_verbs:откопать{}, // откопать на поляне rus_verbs:смастерить{}, // смастерить на коленках rus_verbs:довезти{}, // довезти на машине rus_verbs:избивать{}, // избивать на крыше rus_verbs:сварить{}, // сварить на костре rus_verbs:истребить{}, // истребить на корню rus_verbs:раскопать{}, // раскопать на болоте rus_verbs:попить{}, // попить на кухне rus_verbs:заправлять{}, // заправлять на базе rus_verbs:кушать{}, // кушать на кухне rus_verbs:замолкать{}, // замолкать на половине фразы rus_verbs:измеряться{}, // измеряться на весах rus_verbs:сбываться{}, // сбываться на самом деле rus_verbs:изображаться{}, // изображается на сцене rus_verbs:фиксировать{}, // фиксировать на данной высоте rus_verbs:ослаблять{}, // ослаблять на шее rus_verbs:зреть{}, // зреть на грядке rus_verbs:зеленеть{}, // зеленеть на грядке rus_verbs:критиковать{}, // критиковать на страницах газеты rus_verbs:облететь{}, // облететь на самолете rus_verbs:заразиться{}, // заразиться на работе rus_verbs:рассеять{}, // рассеять на территории rus_verbs:печься{}, // печься на костре rus_verbs:поспать{}, // поспать на земле rus_verbs:сплетаться{}, // сплетаться на макушке rus_verbs:удерживаться{}, // удерживаться на расстоянии rus_verbs:помешаться{}, // помешаться на чистоте rus_verbs:ликвидировать{}, // ликвидировать на полигоне rus_verbs:проваляться{}, // проваляться на диване rus_verbs:лечиться{}, // лечиться на дому rus_verbs:обработать{}, // обработать на станке rus_verbs:защелкнуть{}, // защелкнуть на руках rus_verbs:разносить{}, // разносить на одежде rus_verbs:чесать{}, // чесать на груди rus_verbs:наладить{}, // наладить на конвейере выпуск rus_verbs:отряхнуться{}, // отряхнуться на улице rus_verbs:разыгрываться{}, // разыгрываться на скачках rus_verbs:обеспечиваться{}, // обеспечиваться на выгодных условиях rus_verbs:греться{}, // греться на вокзале rus_verbs:засидеться{}, // засидеться на одном месте rus_verbs:материализоваться{}, // материализоваться на границе rus_verbs:рассеиваться{}, // рассеиваться на высоте вершин rus_verbs:перевозить{}, // перевозить на платформе rus_verbs:поиграть{}, // поиграть на скрипке rus_verbs:потоптаться{}, // потоптаться на одном месте rus_verbs:переправиться{}, // переправиться на плоту rus_verbs:забрезжить{}, // забрезжить на горизонте rus_verbs:завывать{}, // завывать на опушке rus_verbs:заваривать{}, // заваривать на кухоньке rus_verbs:перемещаться{}, // перемещаться на спасательном плоту инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться на бланке rus_verbs:праздновать{}, // праздновать на улицах rus_verbs:обучить{}, // обучить на корте rus_verbs:орудовать{}, // орудовать на складе rus_verbs:подрасти{}, // подрасти на глядке rus_verbs:шелестеть{}, // шелестеть на ветру rus_verbs:раздеваться{}, // раздеваться на публике rus_verbs:пообедать{}, // пообедать на газоне rus_verbs:жрать{}, // жрать на помойке rus_verbs:исполняться{}, // исполняться на флейте rus_verbs:похолодать{}, // похолодать на улице rus_verbs:гнить{}, // гнить на каторге rus_verbs:прослушать{}, // прослушать на концерте rus_verbs:совещаться{}, // совещаться на заседании rus_verbs:покачивать{}, // покачивать на волнах rus_verbs:отсидеть{}, // отсидеть на гаупвахте rus_verbs:формировать{}, // формировать на секретной базе rus_verbs:захрапеть{}, // захрапеть на кровати rus_verbs:объехать{}, // объехать на попутке rus_verbs:поселить{}, // поселить на верхних этажах rus_verbs:заворочаться{}, // заворочаться на сене rus_verbs:напрятать{}, // напрятать на теле rus_verbs:очухаться{}, // очухаться на земле rus_verbs:полистать{}, // полистать на досуге rus_verbs:завертеть{}, // завертеть на шесте rus_verbs:печатать{}, // печатать на ноуте rus_verbs:отыскаться{}, // отыскаться на складе rus_verbs:зафиксировать{}, // зафиксировать на пленке rus_verbs:расстилаться{}, // расстилаться на столе rus_verbs:заместить{}, // заместить на посту rus_verbs:угасать{}, // угасать на неуправляемом корабле rus_verbs:сразить{}, // сразить на ринге rus_verbs:расплываться{}, // расплываться на жаре rus_verbs:сосчитать{}, // сосчитать на пальцах rus_verbs:сгуститься{}, // сгуститься на небольшой высоте rus_verbs:цитировать{}, // цитировать на плите rus_verbs:ориентироваться{}, // ориентироваться на местности rus_verbs:расширить{}, // расширить на другом конце rus_verbs:обтереть{}, // обтереть на стоянке rus_verbs:подстрелить{}, // подстрелить на охоте rus_verbs:растереть{}, // растереть на твердой поверхности rus_verbs:подавлять{}, // подавлять на первом этапе rus_verbs:смешиваться{}, // смешиваться на поверхности // инфинитив:вычитать{ aux stress="в^ычитать" }, глагол:вычитать{ aux stress="в^ычитать" }, // вычитать на сайте // деепричастие:вычитав{}, rus_verbs:сократиться{}, // сократиться на втором этапе rus_verbs:занервничать{}, // занервничать на экзамене rus_verbs:соприкоснуться{}, // соприкоснуться на трассе rus_verbs:обозначить{}, // обозначить на плане rus_verbs:обучаться{}, // обучаться на производстве rus_verbs:снизиться{}, // снизиться на большой высоте rus_verbs:простудиться{}, // простудиться на ветру rus_verbs:поддерживаться{}, // поддерживается на встрече rus_verbs:уплыть{}, // уплыть на лодочке rus_verbs:резвиться{}, // резвиться на песочке rus_verbs:поерзать{}, // поерзать на скамеечке rus_verbs:похвастаться{}, // похвастаться на встрече rus_verbs:знакомиться{}, // знакомиться на уроке rus_verbs:проплывать{}, // проплывать на катере rus_verbs:засесть{}, // засесть на чердаке rus_verbs:подцепить{}, // подцепить на дискотеке rus_verbs:обыскать{}, // обыскать на входе rus_verbs:оправдаться{}, // оправдаться на суде rus_verbs:раскрываться{}, // раскрываться на сцене rus_verbs:одеваться{}, // одеваться на вещевом рынке rus_verbs:засветиться{}, // засветиться на фотографиях rus_verbs:употребляться{}, // употребляться на птицефабриках rus_verbs:грабить{}, // грабить на пустыре rus_verbs:гонять{}, // гонять на повышенных оборотах rus_verbs:развеваться{}, // развеваться на древке rus_verbs:основываться{}, // основываться на безусловных фактах rus_verbs:допрашивать{}, // допрашивать на базе rus_verbs:проработать{}, // проработать на стройке rus_verbs:сосредоточить{}, // сосредоточить на месте rus_verbs:сочинять{}, // сочинять на ходу rus_verbs:ползать{}, // ползать на камне rus_verbs:раскинуться{}, // раскинуться на пустыре rus_verbs:уставать{}, // уставать на работе rus_verbs:укрепить{}, // укрепить на конце rus_verbs:образовывать{}, // образовывать на открытом воздухе взрывоопасную смесь rus_verbs:одобрять{}, // одобрять на словах rus_verbs:приговорить{}, // приговорить на заседании тройки rus_verbs:чернеть{}, // чернеть на свету rus_verbs:гнуть{}, // гнуть на станке rus_verbs:размещаться{}, // размещаться на бирже rus_verbs:соорудить{}, // соорудить на даче rus_verbs:пастись{}, // пастись на лугу rus_verbs:формироваться{}, // формироваться на дне rus_verbs:таить{}, // таить на дне rus_verbs:приостановиться{}, // приостановиться на середине rus_verbs:топтаться{}, // топтаться на месте rus_verbs:громить{}, // громить на подступах rus_verbs:вычислить{}, // вычислить на бумажке rus_verbs:заказывать{}, // заказывать на сайте rus_verbs:осуществить{}, // осуществить на практике rus_verbs:обосноваться{}, // обосноваться на верхушке rus_verbs:пытать{}, // пытать на электрическом стуле rus_verbs:совершиться{}, // совершиться на заседании rus_verbs:свернуться{}, // свернуться на медленном огне rus_verbs:пролетать{}, // пролетать на дельтаплане rus_verbs:сбыться{}, // сбыться на самом деле rus_verbs:разговориться{}, // разговориться на уроке rus_verbs:разворачиваться{}, // разворачиваться на перекрестке rus_verbs:преподнести{}, // преподнести на блюдечке rus_verbs:напечатать{}, // напечатать на лазернике rus_verbs:прорвать{}, // прорвать на периферии rus_verbs:раскачиваться{}, // раскачиваться на доске rus_verbs:задерживаться{}, // задерживаться на старте rus_verbs:угощать{}, // угощать на вечеринке rus_verbs:шарить{}, // шарить на столе rus_verbs:увеличивать{}, // увеличивать на первом этапе rus_verbs:рехнуться{}, // рехнуться на старости лет rus_verbs:расцвести{}, // расцвести на грядке rus_verbs:закипеть{}, // закипеть на плите rus_verbs:подлететь{}, // подлететь на параплане rus_verbs:рыться{}, // рыться на свалке rus_verbs:добираться{}, // добираться на попутках rus_verbs:продержаться{}, // продержаться на вершине rus_verbs:разыскивать{}, // разыскивать на выставках rus_verbs:освобождать{}, // освобождать на заседании rus_verbs:передвигаться{}, // передвигаться на самокате rus_verbs:проявиться{}, // проявиться на свету rus_verbs:заскользить{}, // заскользить на льду rus_verbs:пересказать{}, // пересказать на сцене студенческого театра rus_verbs:протестовать{}, // протестовать на улице rus_verbs:указываться{}, // указываться на табличках rus_verbs:прискакать{}, // прискакать на лошадке rus_verbs:копошиться{}, // копошиться на свежем воздухе rus_verbs:подсчитать{}, // подсчитать на бумажке rus_verbs:разволноваться{}, // разволноваться на экзамене rus_verbs:завертеться{}, // завертеться на полу rus_verbs:ознакомиться{}, // ознакомиться на ходу rus_verbs:ржать{}, // ржать на уроке rus_verbs:раскинуть{}, // раскинуть на грядках rus_verbs:разгромить{}, // разгромить на ринге rus_verbs:подслушать{}, // подслушать на совещании rus_verbs:описываться{}, // описываться на страницах книги rus_verbs:качаться{}, // качаться на стуле rus_verbs:усилить{}, // усилить на флангах rus_verbs:набросать{}, // набросать на клочке картона rus_verbs:расстреливать{}, // расстреливать на подходе rus_verbs:запрыгать{}, // запрыгать на одной ноге rus_verbs:сыскать{}, // сыскать на чужбине rus_verbs:подтвердиться{}, // подтвердиться на практике rus_verbs:плескаться{}, // плескаться на мелководье rus_verbs:расширяться{}, // расширяться на конце rus_verbs:подержать{}, // подержать на солнце rus_verbs:планироваться{}, // планироваться на общем собрании rus_verbs:сгинуть{}, // сгинуть на чужбине rus_verbs:замкнуться{}, // замкнуться на точке rus_verbs:закачаться{}, // закачаться на ветру rus_verbs:перечитывать{}, // перечитывать на ходу rus_verbs:перелететь{}, // перелететь на дельтаплане rus_verbs:оживать{}, // оживать на солнце rus_verbs:женить{}, // женить на богатой невесте rus_verbs:заглохнуть{}, // заглохнуть на старте rus_verbs:копаться{}, // копаться на полу rus_verbs:развлекаться{}, // развлекаться на дискотеке rus_verbs:печататься{}, // печататься на струйном принтере rus_verbs:обрываться{}, // обрываться на полуслове rus_verbs:ускакать{}, // ускакать на лошадке rus_verbs:подписывать{}, // подписывать на столе rus_verbs:добывать{}, // добывать на выработке rus_verbs:скопиться{}, // скопиться на выходе rus_verbs:повстречать{}, // повстречать на пути rus_verbs:поцеловаться{}, // поцеловаться на площади rus_verbs:растянуть{}, // растянуть на столе rus_verbs:подаваться{}, // подаваться на благотворительном обеде rus_verbs:повстречаться{}, // повстречаться на митинге rus_verbs:примоститься{}, // примоститься на ступеньках rus_verbs:отразить{}, // отразить на страницах доклада rus_verbs:пояснять{}, // пояснять на страницах приложения rus_verbs:накормить{}, // накормить на кухне rus_verbs:поужинать{}, // поужинать на веранде инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть на митинге деепричастие:спев{}, инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш }, rus_verbs:топить{}, // топить на мелководье rus_verbs:освоить{}, // освоить на практике rus_verbs:распластаться{}, // распластаться на травке rus_verbs:отплыть{}, // отплыть на старом каяке rus_verbs:улетать{}, // улетать на любом самолете rus_verbs:отстаивать{}, // отстаивать на корте rus_verbs:осуждать{}, // осуждать на словах rus_verbs:переговорить{}, // переговорить на обеде rus_verbs:укрыть{}, // укрыть на чердаке rus_verbs:томиться{}, // томиться на привязи rus_verbs:сжигать{}, // сжигать на полигоне rus_verbs:позавтракать{}, // позавтракать на лоне природы rus_verbs:функционировать{}, // функционирует на солнечной энергии rus_verbs:разместить{}, // разместить на сайте rus_verbs:пронести{}, // пронести на теле rus_verbs:нашарить{}, // нашарить на столе rus_verbs:корчиться{}, // корчиться на полу rus_verbs:распознать{}, // распознать на снимке rus_verbs:повеситься{}, // повеситься на шнуре rus_verbs:обозначиться{}, // обозначиться на картах rus_verbs:оступиться{}, // оступиться на скользком льду rus_verbs:подносить{}, // подносить на блюдечке rus_verbs:расстелить{}, // расстелить на газоне rus_verbs:обсуждаться{}, // обсуждаться на собрании rus_verbs:расписаться{}, // расписаться на бланке rus_verbs:плестись{}, // плестись на привязи rus_verbs:объявиться{}, // объявиться на сцене rus_verbs:повышаться{}, // повышаться на первом датчике rus_verbs:разрабатывать{}, // разрабатывать на заводе rus_verbs:прерывать{}, // прерывать на середине rus_verbs:каяться{}, // каяться на публике rus_verbs:освоиться{}, // освоиться на лошади rus_verbs:подплыть{}, // подплыть на плоту rus_verbs:оскорбить{}, // оскорбить на митинге rus_verbs:торжествовать{}, // торжествовать на пьедестале rus_verbs:поправлять{}, // поправлять на одежде rus_verbs:отражать{}, // отражать на картине rus_verbs:дремать{}, // дремать на кушетке rus_verbs:применяться{}, // применяться на производстве стали rus_verbs:поражать{}, // поражать на большой дистанции rus_verbs:расстрелять{}, // расстрелять на окраине хутора rus_verbs:рассчитать{}, // рассчитать на калькуляторе rus_verbs:записывать{}, // записывать на ленте rus_verbs:перебирать{}, // перебирать на ладони rus_verbs:разбиться{}, // разбиться на катере rus_verbs:поискать{}, // поискать на ферме rus_verbs:прятать{}, // прятать на заброшенном складе rus_verbs:пропеть{}, // пропеть на эстраде rus_verbs:замелькать{}, // замелькать на экране rus_verbs:грустить{}, // грустить на веранде rus_verbs:крутить{}, // крутить на оси rus_verbs:подготовить{}, // подготовить на конспиративной квартире rus_verbs:различать{}, // различать на картинке rus_verbs:киснуть{}, // киснуть на чужбине rus_verbs:оборваться{}, // оборваться на полуслове rus_verbs:запутаться{}, // запутаться на простейшем тесте rus_verbs:общаться{}, // общаться на уроке rus_verbs:производиться{}, // производиться на фабрике rus_verbs:сочинить{}, // сочинить на досуге rus_verbs:давить{}, // давить на лице rus_verbs:разработать{}, // разработать на секретном предприятии rus_verbs:качать{}, // качать на качелях rus_verbs:тушить{}, // тушить на крыше пожар rus_verbs:охранять{}, // охранять на территории базы rus_verbs:приметить{}, // приметить на взгорке rus_verbs:скрыть{}, // скрыть на теле rus_verbs:удерживать{}, // удерживать на руке rus_verbs:усвоить{}, // усвоить на уроке rus_verbs:растаять{}, // растаять на солнечной стороне rus_verbs:красоваться{}, // красоваться на виду rus_verbs:сохраняться{}, // сохраняться на холоде rus_verbs:лечить{}, // лечить на дому rus_verbs:прокатиться{}, // прокатиться на уницикле rus_verbs:договариваться{}, // договариваться на нейтральной территории rus_verbs:качнуться{}, // качнуться на одной ноге rus_verbs:опубликовать{}, // опубликовать на сайте rus_verbs:отражаться{}, // отражаться на поверхности воды rus_verbs:обедать{}, // обедать на веранде rus_verbs:посидеть{}, // посидеть на лавочке rus_verbs:сообщаться{}, // сообщаться на официальном сайте rus_verbs:свершиться{}, // свершиться на заседании rus_verbs:ночевать{}, // ночевать на даче rus_verbs:темнеть{}, // темнеть на свету rus_verbs:гибнуть{}, // гибнуть на территории полигона rus_verbs:усиливаться{}, // усиливаться на территории округа rus_verbs:проживать{}, // проживать на даче rus_verbs:исследовать{}, // исследовать на большой глубине rus_verbs:обитать{}, // обитать на громадной глубине rus_verbs:сталкиваться{}, // сталкиваться на большой высоте rus_verbs:таиться{}, // таиться на большой глубине rus_verbs:спасать{}, // спасать на пожаре rus_verbs:сказываться{}, // сказываться на общем результате rus_verbs:заблудиться{}, // заблудиться на стройке rus_verbs:пошарить{}, // пошарить на полках rus_verbs:планировать{}, // планировать на бумаге rus_verbs:ранить{}, // ранить на полигоне rus_verbs:хлопать{}, // хлопать на сцене rus_verbs:основать{}, // основать на горе новый монастырь rus_verbs:отбить{}, // отбить на столе rus_verbs:отрицать{}, // отрицать на заседании комиссии rus_verbs:устоять{}, // устоять на ногах rus_verbs:отзываться{}, // отзываться на страницах отчёта rus_verbs:притормозить{}, // притормозить на обочине rus_verbs:читаться{}, // читаться на лице rus_verbs:заиграть{}, // заиграть на саксофоне rus_verbs:зависнуть{}, // зависнуть на игровой площадке rus_verbs:сознаться{}, // сознаться на допросе rus_verbs:выясняться{}, // выясняться на очной ставке rus_verbs:наводить{}, // наводить на столе порядок rus_verbs:покоиться{}, // покоиться на кладбище rus_verbs:значиться{}, // значиться на бейджике rus_verbs:съехать{}, // съехать на санках rus_verbs:познакомить{}, // познакомить на свадьбе rus_verbs:завязать{}, // завязать на спине rus_verbs:грохнуть{}, // грохнуть на площади rus_verbs:разъехаться{}, // разъехаться на узкой дороге rus_verbs:столпиться{}, // столпиться на крыльце rus_verbs:порыться{}, // порыться на полках rus_verbs:ослабить{}, // ослабить на шее rus_verbs:оправдывать{}, // оправдывать на суде rus_verbs:обнаруживаться{}, // обнаруживаться на складе rus_verbs:спастись{}, // спастись на дереве rus_verbs:прерваться{}, // прерваться на полуслове rus_verbs:строиться{}, // строиться на пустыре rus_verbs:познать{}, // познать на практике rus_verbs:путешествовать{}, // путешествовать на поезде rus_verbs:побеждать{}, // побеждать на ринге rus_verbs:рассматриваться{}, // рассматриваться на заседании rus_verbs:продаваться{}, // продаваться на открытом рынке rus_verbs:разместиться{}, // разместиться на базе rus_verbs:завыть{}, // завыть на холме rus_verbs:настигнуть{}, // настигнуть на окраине rus_verbs:укрыться{}, // укрыться на чердаке rus_verbs:расплакаться{}, // расплакаться на заседании комиссии rus_verbs:заканчивать{}, // заканчивать на последнем задании rus_verbs:пролежать{}, // пролежать на столе rus_verbs:громоздиться{}, // громоздиться на полу rus_verbs:замерзнуть{}, // замерзнуть на открытом воздухе rus_verbs:поскользнуться{}, // поскользнуться на льду rus_verbs:таскать{}, // таскать на спине rus_verbs:просматривать{}, // просматривать на сайте rus_verbs:обдумать{}, // обдумать на досуге rus_verbs:гадать{}, // гадать на кофейной гуще rus_verbs:останавливать{}, // останавливать на выходе rus_verbs:обозначать{}, // обозначать на странице rus_verbs:долететь{}, // долететь на спортивном байке rus_verbs:тесниться{}, // тесниться на чердачке rus_verbs:хоронить{}, // хоронить на частном кладбище rus_verbs:установиться{}, // установиться на юге rus_verbs:прикидывать{}, // прикидывать на клочке бумаги rus_verbs:затаиться{}, // затаиться на дереве rus_verbs:раздобыть{}, // раздобыть на складе rus_verbs:перебросить{}, // перебросить на вертолетах rus_verbs:захватывать{}, // захватывать на базе rus_verbs:сказаться{}, // сказаться на итоговых оценках rus_verbs:покачиваться{}, // покачиваться на волнах rus_verbs:крутиться{}, // крутиться на кухне rus_verbs:помещаться{}, // помещаться на полке rus_verbs:питаться{}, // питаться на помойке rus_verbs:отдохнуть{}, // отдохнуть на загородной вилле rus_verbs:кататься{}, // кататься на велике rus_verbs:поработать{}, // поработать на стройке rus_verbs:ограбить{}, // ограбить на пустыре rus_verbs:зарабатывать{}, // зарабатывать на бирже rus_verbs:преуспеть{}, // преуспеть на ниве искусства rus_verbs:заерзать{}, // заерзать на стуле rus_verbs:разъяснить{}, // разъяснить на полях rus_verbs:отчеканить{}, // отчеканить на медной пластине rus_verbs:торговать{}, // торговать на рынке rus_verbs:поколебаться{}, // поколебаться на пороге rus_verbs:прикинуть{}, // прикинуть на бумажке rus_verbs:рассечь{}, // рассечь на тупом конце rus_verbs:посмеяться{}, // посмеяться на переменке rus_verbs:остыть{}, // остыть на морозном воздухе rus_verbs:запереться{}, // запереться на чердаке rus_verbs:обогнать{}, // обогнать на повороте rus_verbs:подтянуться{}, // подтянуться на турнике rus_verbs:привозить{}, // привозить на машине rus_verbs:подбирать{}, // подбирать на полу rus_verbs:уничтожать{}, // уничтожать на подходе rus_verbs:притаиться{}, // притаиться на вершине rus_verbs:плясать{}, // плясать на костях rus_verbs:поджидать{}, // поджидать на вокзале rus_verbs:закончить{}, // Мы закончили игру на самом интересном месте (САМ не может быть первым прилагательным в цепочке!) rus_verbs:смениться{}, // смениться на посту rus_verbs:посчитать{}, // посчитать на пальцах rus_verbs:прицелиться{}, // прицелиться на бегу rus_verbs:нарисовать{}, // нарисовать на стене rus_verbs:прыгать{}, // прыгать на сцене rus_verbs:повертеть{}, // повертеть на пальце rus_verbs:попрощаться{}, // попрощаться на панихиде инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на диване rus_verbs:разобрать{}, // разобрать на столе rus_verbs:помереть{}, // помереть на чужбине rus_verbs:различить{}, // различить на нечеткой фотографии rus_verbs:рисовать{}, // рисовать на доске rus_verbs:проследить{}, // проследить на экране rus_verbs:задремать{}, // задремать на диване rus_verbs:ругаться{}, // ругаться на людях rus_verbs:сгореть{}, // сгореть на работе rus_verbs:зазвучать{}, // зазвучать на коротких волнах rus_verbs:задохнуться{}, // задохнуться на вершине горы rus_verbs:порождать{}, // порождать на поверхности небольшую рябь rus_verbs:отдыхать{}, // отдыхать на курорте rus_verbs:образовать{}, // образовать на дне толстый слой rus_verbs:поправиться{}, // поправиться на дармовых харчах rus_verbs:отмечать{}, // отмечать на календаре rus_verbs:реять{}, // реять на флагштоке rus_verbs:ползти{}, // ползти на коленях rus_verbs:продавать{}, // продавать на аукционе rus_verbs:сосредоточиться{}, // сосредоточиться на основной задаче rus_verbs:рыскать{}, // мышки рыскали на кухне rus_verbs:расстегнуть{}, // расстегнуть на куртке все пуговицы rus_verbs:напасть{}, // напасть на территории другого государства rus_verbs:издать{}, // издать на западе rus_verbs:оставаться{}, // оставаться на страже порядка rus_verbs:появиться{}, // наконец появиться на экране rus_verbs:лежать{}, // лежать на столе rus_verbs:ждать{}, // ждать на берегу инфинитив:писать{aux stress="пис^ать"}, // писать на бумаге глагол:писать{aux stress="пис^ать"}, rus_verbs:оказываться{}, // оказываться на полу rus_verbs:поставить{}, // поставить на столе rus_verbs:держать{}, // держать на крючке rus_verbs:выходить{}, // выходить на остановке rus_verbs:заговорить{}, // заговорить на китайском языке rus_verbs:ожидать{}, // ожидать на стоянке rus_verbs:закричать{}, // закричал на минарете муэдзин rus_verbs:простоять{}, // простоять на посту rus_verbs:продолжить{}, // продолжить на первом этаже rus_verbs:ощутить{}, // ощутить на себе влияние кризиса rus_verbs:состоять{}, // состоять на учете rus_verbs:готовиться{}, инфинитив:акклиматизироваться{вид:несоверш}, // альпинисты готовятся акклиматизироваться на новой высоте глагол:акклиматизироваться{вид:несоверш}, rus_verbs:арестовать{}, // грабители были арестованы на месте преступления rus_verbs:схватить{}, // грабители были схвачены на месте преступления инфинитив:атаковать{ вид:соверш }, // взвод был атакован на границе глагол:атаковать{ вид:соверш }, прилагательное:атакованный{ вид:соверш }, прилагательное:атаковавший{ вид:соверш }, rus_verbs:базировать{}, // установка будет базирована на границе rus_verbs:базироваться{}, // установка базируется на границе rus_verbs:барахтаться{}, // дети барахтались на мелководье rus_verbs:браконьерить{}, // Охотники браконьерили ночью на реке rus_verbs:браконьерствовать{}, // Охотники ночью браконьерствовали на реке rus_verbs:бренчать{}, // парень что-то бренчал на гитаре rus_verbs:бренькать{}, // парень что-то бренькает на гитаре rus_verbs:начать{}, // Рынок акций РФ начал торги на отрицательной территории. rus_verbs:буксовать{}, // Колеса буксуют на льду rus_verbs:вертеться{}, // Непоседливый ученик много вертится на стуле rus_verbs:взвести{}, // Боец взвел на оружии предохранитель rus_verbs:вилять{}, // Машина сильно виляла на дороге rus_verbs:висеть{}, // Яблоко висит на ветке rus_verbs:возлежать{}, // возлежать на лежанке rus_verbs:подниматься{}, // Мы поднимаемся на лифте rus_verbs:подняться{}, // Мы поднимемся на лифте rus_verbs:восседать{}, // Коля восседает на лошади rus_verbs:воссиять{}, // Луна воссияла на небе rus_verbs:воцариться{}, // Мир воцарился на всей земле rus_verbs:воцаряться{}, // Мир воцаряется на всей земле rus_verbs:вращать{}, // вращать на поясе rus_verbs:вращаться{}, // вращаться на поясе rus_verbs:встретить{}, // встретить друга на улице rus_verbs:встретиться{}, // встретиться на занятиях rus_verbs:встречать{}, // встречать на занятиях rus_verbs:въебывать{}, // въебывать на работе rus_verbs:въезжать{}, // въезжать на автомобиле rus_verbs:въехать{}, // въехать на автомобиле rus_verbs:выгорать{}, // ткань выгорает на солнце rus_verbs:выгореть{}, // ткань выгорела на солнце rus_verbs:выгравировать{}, // выгравировать на табличке надпись rus_verbs:выжить{}, // выжить на необитаемом острове rus_verbs:вылежаться{}, // помидоры вылежались на солнце rus_verbs:вылеживаться{}, // вылеживаться на солнце rus_verbs:выместить{}, // выместить на ком-то злобу rus_verbs:вымещать{}, // вымещать на ком-то свое раздражение rus_verbs:вымещаться{}, // вымещаться на ком-то rus_verbs:выращивать{}, // выращивать на грядке помидоры rus_verbs:выращиваться{}, // выращиваться на грядке инфинитив:вырезать{вид:соверш}, // вырезать на доске надпись глагол:вырезать{вид:соверш}, инфинитив:вырезать{вид:несоверш}, глагол:вырезать{вид:несоверш}, rus_verbs:вырисоваться{}, // вырисоваться на графике rus_verbs:вырисовываться{}, // вырисовываться на графике rus_verbs:высаживать{}, // высаживать на необитаемом острове rus_verbs:высаживаться{}, // высаживаться на острове rus_verbs:высвечивать{}, // высвечивать на дисплее температуру rus_verbs:высвечиваться{}, // высвечиваться на дисплее rus_verbs:выстроить{}, // выстроить на фундаменте rus_verbs:выстроиться{}, // выстроиться на плацу rus_verbs:выстудить{}, // выстудить на морозе rus_verbs:выстудиться{}, // выстудиться на морозе rus_verbs:выстужать{}, // выстужать на морозе rus_verbs:выстуживать{}, // выстуживать на морозе rus_verbs:выстуживаться{}, // выстуживаться на морозе rus_verbs:выстукать{}, // выстукать на клавиатуре rus_verbs:выстукивать{}, // выстукивать на клавиатуре rus_verbs:выстукиваться{}, // выстукиваться на клавиатуре rus_verbs:выступать{}, // выступать на сцене rus_verbs:выступить{}, // выступить на сцене rus_verbs:выстучать{}, // выстучать на клавиатуре rus_verbs:выстывать{}, // выстывать на морозе rus_verbs:выстыть{}, // выстыть на морозе rus_verbs:вытатуировать{}, // вытатуировать на руке якорь rus_verbs:говорить{}, // говорить на повышенных тонах rus_verbs:заметить{}, // заметить на берегу rus_verbs:стоять{}, // твёрдо стоять на ногах rus_verbs:оказаться{}, // оказаться на передовой линии rus_verbs:почувствовать{}, // почувствовать на своей шкуре rus_verbs:остановиться{}, // остановиться на первом пункте rus_verbs:показаться{}, // показаться на горизонте rus_verbs:чувствовать{}, // чувствовать на своей шкуре rus_verbs:искать{}, // искать на открытом пространстве rus_verbs:иметься{}, // иметься на складе rus_verbs:клясться{}, // клясться на Коране rus_verbs:прервать{}, // прервать на полуслове rus_verbs:играть{}, // играть на чувствах rus_verbs:спуститься{}, // спуститься на парашюте rus_verbs:понадобиться{}, // понадобиться на экзамене rus_verbs:служить{}, // служить на флоте rus_verbs:подобрать{}, // подобрать на улице rus_verbs:появляться{}, // появляться на сцене rus_verbs:селить{}, // селить на чердаке rus_verbs:поймать{}, // поймать на границе rus_verbs:увидать{}, // увидать на опушке rus_verbs:подождать{}, // подождать на перроне rus_verbs:прочесть{}, // прочесть на полях rus_verbs:тонуть{}, // тонуть на мелководье rus_verbs:ощущать{}, // ощущать на коже rus_verbs:отметить{}, // отметить на полях rus_verbs:показывать{}, // показывать на графике rus_verbs:разговаривать{}, // разговаривать на иностранном языке rus_verbs:прочитать{}, // прочитать на сайте rus_verbs:попробовать{}, // попробовать на практике rus_verbs:замечать{}, // замечать на коже грязь rus_verbs:нести{}, // нести на плечах rus_verbs:носить{}, // носить на голове rus_verbs:гореть{}, // гореть на работе rus_verbs:застыть{}, // застыть на пороге инфинитив:жениться{ вид:соверш }, // жениться на королеве глагол:жениться{ вид:соверш }, прилагательное:женатый{}, прилагательное:женившийся{}, rus_verbs:спрятать{}, // спрятать на чердаке rus_verbs:развернуться{}, // развернуться на плацу rus_verbs:строить{}, // строить на песке rus_verbs:устроить{}, // устроить на даче тестральный вечер rus_verbs:настаивать{}, // настаивать на выполнении приказа rus_verbs:находить{}, // находить на берегу rus_verbs:мелькнуть{}, // мелькнуть на экране rus_verbs:очутиться{}, // очутиться на опушке леса инфинитив:использовать{вид:соверш}, // использовать на работе глагол:использовать{вид:соверш}, инфинитив:использовать{вид:несоверш}, глагол:использовать{вид:несоверш}, прилагательное:использованный{}, прилагательное:использующий{}, прилагательное:использовавший{}, rus_verbs:лететь{}, // лететь на воздушном шаре rus_verbs:смеяться{}, // смеяться на сцене rus_verbs:ездить{}, // ездить на мопеде rus_verbs:заснуть{}, // заснуть на диване rus_verbs:застать{}, // застать на рабочем месте rus_verbs:очнуться{}, // очнуться на больничной койке rus_verbs:разглядеть{}, // разглядеть на фотографии rus_verbs:обойти{}, // обойти на вираже rus_verbs:удержаться{}, // удержаться на троне rus_verbs:побывать{}, // побывать на другой планете rus_verbs:заняться{}, // заняться на выходных делом rus_verbs:вянуть{}, // вянуть на солнце rus_verbs:постоять{}, // постоять на голове rus_verbs:приобрести{}, // приобрести на распродаже rus_verbs:попасться{}, // попасться на краже rus_verbs:продолжаться{}, // продолжаться на земле rus_verbs:открывать{}, // открывать на арене rus_verbs:создавать{}, // создавать на сцене rus_verbs:обсуждать{}, // обсуждать на кухне rus_verbs:отыскать{}, // отыскать на полу rus_verbs:уснуть{}, // уснуть на диване rus_verbs:задержаться{}, // задержаться на работе rus_verbs:курить{}, // курить на свежем воздухе rus_verbs:приподняться{}, // приподняться на локтях rus_verbs:установить{}, // установить на вершине rus_verbs:запереть{}, // запереть на балконе rus_verbs:синеть{}, // синеть на воздухе rus_verbs:убивать{}, // убивать на нейтральной территории rus_verbs:скрываться{}, // скрываться на даче rus_verbs:родить{}, // родить на полу rus_verbs:описать{}, // описать на страницах книги rus_verbs:перехватить{}, // перехватить на подлете rus_verbs:скрывать{}, // скрывать на даче rus_verbs:сменить{}, // сменить на посту rus_verbs:мелькать{}, // мелькать на экране rus_verbs:присутствовать{}, // присутствовать на мероприятии rus_verbs:украсть{}, // украсть на рынке rus_verbs:победить{}, // победить на ринге rus_verbs:упомянуть{}, // упомянуть на страницах романа rus_verbs:плыть{}, // плыть на старой лодке rus_verbs:повиснуть{}, // повиснуть на перекладине rus_verbs:нащупать{}, // нащупать на дне rus_verbs:затихнуть{}, // затихнуть на дне rus_verbs:построить{}, // построить на участке rus_verbs:поддерживать{}, // поддерживать на поверхности rus_verbs:заработать{}, // заработать на бирже rus_verbs:провалиться{}, // провалиться на экзамене rus_verbs:сохранить{}, // сохранить на диске rus_verbs:располагаться{}, // располагаться на софе rus_verbs:поклясться{}, // поклясться на библии rus_verbs:сражаться{}, // сражаться на арене rus_verbs:спускаться{}, // спускаться на дельтаплане rus_verbs:уничтожить{}, // уничтожить на подступах rus_verbs:изучить{}, // изучить на практике rus_verbs:рождаться{}, // рождаться на праздниках rus_verbs:прилететь{}, // прилететь на самолете rus_verbs:догнать{}, // догнать на перекрестке rus_verbs:изобразить{}, // изобразить на бумаге rus_verbs:проехать{}, // проехать на тракторе rus_verbs:приготовить{}, // приготовить на масле rus_verbs:споткнуться{}, // споткнуться на полу rus_verbs:собирать{}, // собирать на берегу rus_verbs:отсутствовать{}, // отсутствовать на тусовке rus_verbs:приземлиться{}, // приземлиться на военном аэродроме rus_verbs:сыграть{}, // сыграть на трубе rus_verbs:прятаться{}, // прятаться на даче rus_verbs:спрятаться{}, // спрятаться на чердаке rus_verbs:провозгласить{}, // провозгласить на митинге rus_verbs:изложить{}, // изложить на бумаге rus_verbs:использоваться{}, // использоваться на практике rus_verbs:замяться{}, // замяться на входе rus_verbs:раздаваться{}, // Крик ягуара раздается на краю болота rus_verbs:сверкнуть{}, // сверкнуть на солнце rus_verbs:сверкать{}, // сверкать на свету rus_verbs:задержать{}, // задержать на митинге rus_verbs:осечься{}, // осечься на первом слове rus_verbs:хранить{}, // хранить на банковском счету rus_verbs:шутить{}, // шутить на уроке rus_verbs:кружиться{}, // кружиться на балу rus_verbs:чертить{}, // чертить на доске rus_verbs:отразиться{}, // отразиться на оценках rus_verbs:греть{}, // греть на солнце rus_verbs:рассуждать{}, // рассуждать на страницах своей книги rus_verbs:окружать{}, // окружать на острове rus_verbs:сопровождать{}, // сопровождать на охоте rus_verbs:заканчиваться{}, // заканчиваться на самом интересном месте rus_verbs:содержаться{}, // содержаться на приусадебном участке rus_verbs:поселиться{}, // поселиться на даче rus_verbs:запеть{}, // запеть на сцене инфинитив:провозить{ вид:несоверш }, // провозить на теле глагол:провозить{ вид:несоверш }, прилагательное:провезенный{}, прилагательное:провозивший{вид:несоверш}, прилагательное:провозящий{вид:несоверш}, деепричастие:провозя{}, rus_verbs:мочить{}, // мочить на месте rus_verbs:преследовать{}, // преследовать на территории другого штата rus_verbs:пролететь{}, // пролетел на параплане rus_verbs:драться{}, // драться на рапирах rus_verbs:просидеть{}, // просидеть на занятиях rus_verbs:убираться{}, // убираться на балконе rus_verbs:таять{}, // таять на солнце rus_verbs:проверять{}, // проверять на полиграфе rus_verbs:убеждать{}, // убеждать на примере rus_verbs:скользить{}, // скользить на льду rus_verbs:приобретать{}, // приобретать на распродаже rus_verbs:летать{}, // летать на метле rus_verbs:толпиться{}, // толпиться на перроне rus_verbs:плавать{}, // плавать на надувном матрасе rus_verbs:описывать{}, // описывать на страницах повести rus_verbs:пробыть{}, // пробыть на солнце слишком долго rus_verbs:застрять{}, // застрять на верхнем этаже rus_verbs:метаться{}, // метаться на полу rus_verbs:сжечь{}, // сжечь на костре rus_verbs:расслабиться{}, // расслабиться на кушетке rus_verbs:услыхать{}, // услыхать на рынке rus_verbs:удержать{}, // удержать на прежнем уровне rus_verbs:образоваться{}, // образоваться на дне rus_verbs:рассмотреть{}, // рассмотреть на поверхности чипа rus_verbs:уезжать{}, // уезжать на попутке rus_verbs:похоронить{}, // похоронить на закрытом кладбище rus_verbs:настоять{}, // настоять на пересмотре оценок rus_verbs:растянуться{}, // растянуться на горячем песке rus_verbs:покрутить{}, // покрутить на шесте rus_verbs:обнаружиться{}, // обнаружиться на болоте rus_verbs:гулять{}, // гулять на свадьбе rus_verbs:утонуть{}, // утонуть на курорте rus_verbs:храниться{}, // храниться на депозите rus_verbs:танцевать{}, // танцевать на свадьбе rus_verbs:трудиться{}, // трудиться на заводе инфинитив:засыпать{переходность:непереходный вид:несоверш}, // засыпать на кровати глагол:засыпать{переходность:непереходный вид:несоверш}, деепричастие:засыпая{переходность:непереходный вид:несоверш}, прилагательное:засыпавший{переходность:непереходный вид:несоверш}, прилагательное:засыпающий{ вид:несоверш переходность:непереходный }, // ребенок, засыпающий на руках rus_verbs:сушить{}, // сушить на открытом воздухе rus_verbs:зашевелиться{}, // зашевелиться на чердаке rus_verbs:обдумывать{}, // обдумывать на досуге rus_verbs:докладывать{}, // докладывать на научной конференции rus_verbs:промелькнуть{}, // промелькнуть на экране // прилагательное:находящийся{ вид:несоверш }, // колонна, находящаяся на ничейной территории прилагательное:написанный{}, // слово, написанное на заборе rus_verbs:умещаться{}, // компьютер, умещающийся на ладони rus_verbs:открыть{}, // книга, открытая на последней странице rus_verbs:спать{}, // йог, спящий на гвоздях rus_verbs:пробуксовывать{}, // колесо, пробуксовывающее на обледенелом асфальте rus_verbs:забуксовать{}, // колесо, забуксовавшее на обледенелом асфальте rus_verbs:отобразиться{}, // удивление, отобразившееся на лице rus_verbs:увидеть{}, // на полу я увидел чьи-то следы rus_verbs:видеть{}, // на полу я вижу чьи-то следы rus_verbs:оставить{}, // Мел оставил на доске белый след. rus_verbs:оставлять{}, // Мел оставляет на доске белый след. rus_verbs:встречаться{}, // встречаться на лекциях rus_verbs:познакомиться{}, // познакомиться на занятиях rus_verbs:устроиться{}, // она устроилась на кровати rus_verbs:ложиться{}, // ложись на полу rus_verbs:останавливаться{}, // останавливаться на достигнутом rus_verbs:спотыкаться{}, // спотыкаться на ровном месте rus_verbs:распечатать{}, // распечатать на бумаге rus_verbs:распечатывать{}, // распечатывать на бумаге rus_verbs:просмотреть{}, // просмотреть на бумаге rus_verbs:закрепляться{}, // закрепляться на плацдарме rus_verbs:погреться{}, // погреться на солнышке rus_verbs:мешать{}, // Он мешал краски на палитре. rus_verbs:занять{}, // Он занял первое место на соревнованиях. rus_verbs:заговариваться{}, // Он заговаривался иногда на уроках. деепричастие:женившись{ вид:соверш }, rus_verbs:везти{}, // Он везёт песок на тачке. прилагательное:казненный{}, // Он был казнён на электрическом стуле. rus_verbs:прожить{}, // Он безвыездно прожил всё лето на даче. rus_verbs:принести{}, // Официантка принесла нам обед на подносе. rus_verbs:переписать{}, // Перепишите эту рукопись на машинке. rus_verbs:идти{}, // Поезд идёт на малой скорости. rus_verbs:петь{}, // птички поют на рассвете rus_verbs:смотреть{}, // Смотри на обороте. rus_verbs:прибрать{}, // прибрать на столе rus_verbs:прибраться{}, // прибраться на столе rus_verbs:растить{}, // растить капусту на огороде rus_verbs:тащить{}, // тащить ребенка на руках rus_verbs:убирать{}, // убирать на столе rus_verbs:простыть{}, // Я простыл на морозе. rus_verbs:сиять{}, // ясные звезды мирно сияли на безоблачном весеннем небе. rus_verbs:проводиться{}, // такие эксперименты не проводятся на воде rus_verbs:достать{}, // Я не могу достать до яблок на верхних ветках. rus_verbs:расплыться{}, // Чернила расплылись на плохой бумаге. rus_verbs:вскочить{}, // У него вскочил прыщ на носу. rus_verbs:свить{}, // У нас на балконе воробей свил гнездо. rus_verbs:оторваться{}, // У меня на пальто оторвалась пуговица. rus_verbs:восходить{}, // Солнце восходит на востоке. rus_verbs:блестеть{}, // Снег блестит на солнце. rus_verbs:побить{}, // Рысак побил всех лошадей на скачках. rus_verbs:литься{}, // Реки крови льются на войне. rus_verbs:держаться{}, // Ребёнок уже твёрдо держится на ногах. rus_verbs:клубиться{}, // Пыль клубится на дороге. инфинитив:написать{ aux stress="напис^ать" }, // Ты должен написать статью на английском языке глагол:написать{ aux stress="напис^ать" }, // Он написал статью на русском языке. // глагол:находиться{вид:несоверш}, // мой поезд находится на первом пути // инфинитив:находиться{вид:несоверш}, rus_verbs:жить{}, // Было интересно жить на курорте. rus_verbs:повидать{}, // Он много повидал на своём веку. rus_verbs:разъезжаться{}, // Ноги разъезжаются не только на льду. rus_verbs:расположиться{}, // Оба села расположились на берегу реки. rus_verbs:объясняться{}, // Они объясняются на иностранном языке. rus_verbs:прощаться{}, // Они долго прощались на вокзале. rus_verbs:работать{}, // Она работает на ткацкой фабрике. rus_verbs:купить{}, // Она купила молоко на рынке. rus_verbs:поместиться{}, // Все книги поместились на полке. глагол:проводить{вид:несоверш}, инфинитив:проводить{вид:несоверш}, // Нужно проводить теорию на практике. rus_verbs:пожить{}, // Недолго она пожила на свете. rus_verbs:краснеть{}, // Небо краснеет на закате. rus_verbs:бывать{}, // На Волге бывает сильное волнение. rus_verbs:ехать{}, // Мы туда ехали на автобусе. rus_verbs:провести{}, // Мы провели месяц на даче. rus_verbs:поздороваться{}, // Мы поздоровались при встрече на улице. rus_verbs:расти{}, // Арбузы растут теперь не только на юге. ГЛ_ИНФ(сидеть), // три больших пса сидят на траве ГЛ_ИНФ(сесть), // три больших пса сели на траву ГЛ_ИНФ(перевернуться), // На дороге перевернулся автомобиль ГЛ_ИНФ(повезти), // я повезу тебя на машине ГЛ_ИНФ(отвезти), // мы отвезем тебя на такси ГЛ_ИНФ(пить), // пить на кухне чай ГЛ_ИНФ(найти), // найти на острове ГЛ_ИНФ(быть), // на этих костях есть следы зубов ГЛ_ИНФ(высадиться), // помощники высадились на острове ГЛ_ИНФ(делать),прилагательное:делающий{}, прилагательное:делавший{}, деепричастие:делая{}, // смотрю фильм о том, что пираты делали на необитаемом острове ГЛ_ИНФ(случиться), // это случилось на опушке леса ГЛ_ИНФ(продать), ГЛ_ИНФ(есть) // кошки ели мой корм на песчаном берегу } #endregion VerbList // Чтобы разрешить связывание в паттернах типа: смотреть на youtube fact гл_предл { if context { Гл_НА_Предл предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_НА_Предл предлог:на{} *:*{падеж:предл} } then return true } // локатив fact гл_предл { if context { Гл_НА_Предл предлог:на{} *:*{падеж:мест} } then return true } #endregion ПРЕДЛОЖНЫЙ #region ВИНИТЕЛЬНЫЙ // НА+винительный падеж: // ЗАБИРАТЬСЯ НА ВЕРШИНУ ГОРЫ #region VerbList wordentry_set Гл_НА_Вин= { rus_verbs:переметнуться{}, // Ее взгляд растерянно переметнулся на Лили. rus_verbs:отогнать{}, // Водитель отогнал машину на стоянку. rus_verbs:фапать{}, // Не фапай на желтяк и не перебивай. rus_verbs:умножить{}, // Умножьте это количество примерно на 10. //rus_verbs:умножать{}, rus_verbs:откатить{}, // Откатил Шпак валун на шлях и перекрыл им дорогу. rus_verbs:откатывать{}, rus_verbs:доносить{}, // Вот и побежали на вас доносить. rus_verbs:донести{}, rus_verbs:разбирать{}, // Ворованные автомобили злоумышленники разбирали на запчасти и продавали. безлич_глагол:хватит{}, // - На одну атаку хватит. rus_verbs:скупиться{}, // Он сражался за жизнь, не скупясь на хитрости и усилия, и пока этот стиль давал неплохие результаты. rus_verbs:поскупиться{}, // Не поскупись на похвалы! rus_verbs:подыматься{}, rus_verbs:транспортироваться{}, rus_verbs:бахнуть{}, // Бахнуть стакан на пол rus_verbs:РАЗДЕЛИТЬ{}, // Президентские выборы разделили Венесуэлу на два непримиримых лагеря (РАЗДЕЛИТЬ) rus_verbs:НАЦЕЛИВАТЬСЯ{}, // Невдалеке пролетел кондор, нацеливаясь на бизонью тушу. (НАЦЕЛИВАТЬСЯ) rus_verbs:ВЫПЛЕСНУТЬ{}, // Низкий вибрирующий гул напоминал вулкан, вот-вот готовый выплеснуть на земную твердь потоки раскаленной лавы. (ВЫПЛЕСНУТЬ) rus_verbs:ИСЧЕЗНУТЬ{}, // Оно фыркнуло и исчезло в лесу на другой стороне дороги (ИСЧЕЗНУТЬ) rus_verbs:ВЫЗВАТЬ{}, // вызвать своего брата на поединок. (ВЫЗВАТЬ) rus_verbs:ПОБРЫЗГАТЬ{}, // Матрос побрызгал немного фимиама на крошечный огонь (ПОБРЫЗГАТЬ/БРЫЗГАТЬ/БРЫЗНУТЬ/КАПНУТЬ/КАПАТЬ/ПОКАПАТЬ) rus_verbs:БРЫЗГАТЬ{}, rus_verbs:БРЫЗНУТЬ{}, rus_verbs:КАПНУТЬ{}, rus_verbs:КАПАТЬ{}, rus_verbs:ПОКАПАТЬ{}, rus_verbs:ПООХОТИТЬСЯ{}, // Мы можем когда-нибудь вернуться и поохотиться на него. (ПООХОТИТЬСЯ/ОХОТИТЬСЯ) rus_verbs:ОХОТИТЬСЯ{}, // rus_verbs:ПОПАСТЬСЯ{}, // Не думал я, что они попадутся на это (ПОПАСТЬСЯ/НАРВАТЬСЯ/НАТОЛКНУТЬСЯ) rus_verbs:НАРВАТЬСЯ{}, // rus_verbs:НАТОЛКНУТЬСЯ{}, // rus_verbs:ВЫСЛАТЬ{}, // Он выслал разведчиков на большое расстояние от основного отряда. (ВЫСЛАТЬ) прилагательное:ПОХОЖИЙ{}, // Ты не выглядишь похожим на индейца (ПОХОЖИЙ) rus_verbs:РАЗОРВАТЬ{}, // Через минуту он был мертв и разорван на части. (РАЗОРВАТЬ) rus_verbs:СТОЛКНУТЬ{}, // Только быстрыми выпадами копья он сумел столкнуть их обратно на карниз. (СТОЛКНУТЬ/СТАЛКИВАТЬ) rus_verbs:СТАЛКИВАТЬ{}, // rus_verbs:СПУСТИТЬ{}, // Я побежал к ним, но они к тому времени спустили лодку на воду (СПУСТИТЬ) rus_verbs:ПЕРЕБРАСЫВАТЬ{}, // Сирия перебрасывает на юг страны воинские подкрепления (ПЕРЕБРАСЫВАТЬ, ПЕРЕБРОСИТЬ, НАБРАСЫВАТЬ, НАБРОСИТЬ) rus_verbs:ПЕРЕБРОСИТЬ{}, // rus_verbs:НАБРАСЫВАТЬ{}, // rus_verbs:НАБРОСИТЬ{}, // rus_verbs:СВЕРНУТЬ{}, // Он вывел машину на бульвар и поехал на восток, а затем свернул на юг. (СВЕРНУТЬ/СВОРАЧИВАТЬ/ПОВЕРНУТЬ/ПОВОРАЧИВАТЬ) rus_verbs:СВОРАЧИВАТЬ{}, // // rus_verbs:ПОВЕРНУТЬ{}, // rus_verbs:ПОВОРАЧИВАТЬ{}, // rus_verbs:наорать{}, rus_verbs:ПРОДВИНУТЬСЯ{}, // Полк продвинется на десятки километров (ПРОДВИНУТЬСЯ) rus_verbs:БРОСАТЬ{}, // Он бросает обещания на ветер (БРОСАТЬ) rus_verbs:ОДОЛЖИТЬ{}, // Я вам одолжу книгу на десять дней (ОДОЛЖИТЬ) rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое rus_verbs:перегонять{}, rus_verbs:выгонять{}, rus_verbs:выгнать{}, rus_verbs:СВОДИТЬСЯ{}, // сейчас панели кузовов расходятся по десяткам покрасочных постов и потом сводятся вновь на общий конвейер (СВОДИТЬСЯ) rus_verbs:ПОЖЕРТВОВАТЬ{}, // Бывший функционер компартии Эстонии пожертвовал деньги на расследования преступлений коммунизма (ПОЖЕРТВОВАТЬ) rus_verbs:ПРОВЕРЯТЬ{}, // Школьников будут принудительно проверять на курение (ПРОВЕРЯТЬ) rus_verbs:ОТПУСТИТЬ{}, // Приставы отпустят должников на отдых (ОТПУСТИТЬ) rus_verbs:использоваться{}, // имеющийся у государства денежный запас активно используется на поддержание рынка акций rus_verbs:назначаться{}, // назначаться на пост rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал rus_verbs:ШПИОНИТЬ{}, // Канадского офицера, шпионившего на Россию, приговорили к 20 годам тюрьмы (ШПИОНИТЬ НА вин) rus_verbs:ЗАПЛАНИРОВАТЬ{}, // все деньги , запланированные на сейсмоукрепление домов на Камчатке (ЗАПЛАНИРОВАТЬ НА) // rus_verbs:ПОХОДИТЬ{}, // больше походил на обвинительную речь , адресованную руководству республики (ПОХОДИТЬ НА) rus_verbs:ДЕЙСТВОВАТЬ{}, // выявленный контрабандный канал действовал на постоянной основе (ДЕЙСТВОВАТЬ НА) rus_verbs:ПЕРЕДАТЬ{}, // после чего должно быть передано на рассмотрение суда (ПЕРЕДАТЬ НА вин) rus_verbs:НАЗНАЧИТЬСЯ{}, // Зимой на эту должность пытался назначиться народный депутат (НАЗНАЧИТЬСЯ НА) rus_verbs:РЕШИТЬСЯ{}, // Франция решилась на одностороннее и рискованное военное вмешательство (РЕШИТЬСЯ НА) rus_verbs:ОРИЕНТИРОВАТЬ{}, // Этот браузер полностью ориентирован на планшеты и сенсорный ввод (ОРИЕНТИРОВАТЬ НА вин) rus_verbs:ЗАВЕСТИ{}, // на Витьку завели дело (ЗАВЕСТИ НА) rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА) rus_verbs:НАСТРАИВАТЬСЯ{}, // гетеродин, настраивающийся на волну (НАСТРАИВАТЬСЯ НА) rus_verbs:СУЩЕСТВОВАТЬ{}, // Он существует на средства родителей. (СУЩЕСТВОВАТЬ НА) прилагательное:способный{}, // Он способен на убийство. (СПОСОБНЫЙ НА) rus_verbs:посыпаться{}, // на Нину посыпались снежинки инфинитив:нарезаться{ вид:несоверш }, // Урожай собирают механически или вручную, стебли нарезаются на куски и быстро транспортируются на перерабатывающий завод. глагол:нарезаться{ вид:несоверш }, rus_verbs:пожаловать{}, // скандально известный певец пожаловал к нам на передачу rus_verbs:показать{}, // Вадим показал на Колю rus_verbs:съехаться{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА) прилагательное:тугой{}, // Бабушка туга на ухо. (ТУГОЙ НА) rus_verbs:свисать{}, // Волосы свисают на лоб. (свисать на) rus_verbs:ЦЕНИТЬСЯ{}, // Всякая рабочая рука ценилась на вес золота. (ЦЕНИТЬСЯ НА) rus_verbs:ШУМЕТЬ{}, // Вы шумите на весь дом! (ШУМЕТЬ НА) rus_verbs:протянуться{}, // Дорога протянулась на сотни километров. (протянуться на) rus_verbs:РАССЧИТАТЬ{}, // Книга рассчитана на массового читателя. (РАССЧИТАТЬ НА) rus_verbs:СОРИЕНТИРОВАТЬ{}, // мы сориентировали процесс на повышение котировок (СОРИЕНТИРОВАТЬ НА) rus_verbs:рыкнуть{}, // рыкнуть на остальных членов стаи (рыкнуть на) rus_verbs:оканчиваться{}, // оканчиваться на звонкую согласную (оканчиваться на) rus_verbs:выехать{}, // посигналить нарушителю, выехавшему на встречную полосу (выехать на) rus_verbs:прийтись{}, // Пятое число пришлось на субботу. rus_verbs:крениться{}, // корабль кренился на правый борт (крениться на) rus_verbs:приходиться{}, // основной налоговый гнет приходится на средний бизнес (приходиться на) rus_verbs:верить{}, // верить людям на слово (верить на слово) rus_verbs:выезжать{}, // Завтра вся семья выезжает на новую квартиру. rus_verbs:записать{}, // Запишите меня на завтрашний приём к доктору. rus_verbs:пасть{}, // Жребий пал на меня. rus_verbs:ездить{}, // Вчера мы ездили на оперу. rus_verbs:влезть{}, // Мальчик влез на дерево. rus_verbs:выбежать{}, // Мальчик выбежал из комнаты на улицу. rus_verbs:разбиться{}, // окно разбилось на мелкие осколки rus_verbs:бежать{}, // я бегу на урок rus_verbs:сбегаться{}, // сбегаться на происшествие rus_verbs:присылать{}, // присылать на испытание rus_verbs:надавить{}, // надавить на педать rus_verbs:внести{}, // внести законопроект на рассмотрение rus_verbs:вносить{}, // вносить законопроект на рассмотрение rus_verbs:поворачиваться{}, // поворачиваться на 180 градусов rus_verbs:сдвинуть{}, // сдвинуть на несколько сантиметров rus_verbs:опубликовать{}, // С.Митрохин опубликовал компромат на думских подельников Гудкова rus_verbs:вырасти{}, // Официальный курс доллара вырос на 26 копеек. rus_verbs:оглядываться{}, // оглядываться на девушек rus_verbs:расходиться{}, // расходиться на отдых rus_verbs:поскакать{}, // поскакать на службу rus_verbs:прыгать{}, // прыгать на сцену rus_verbs:приглашать{}, // приглашать на обед rus_verbs:рваться{}, // Кусок ткани рвется на части rus_verbs:понестись{}, // понестись на волю rus_verbs:распространяться{}, // распространяться на всех жителей штата инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на пол инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, деепричастие:просыпавшись{}, деепричастие:просыпаясь{}, rus_verbs:заехать{}, // заехать на пандус rus_verbs:разобрать{}, // разобрать на составляющие rus_verbs:опускаться{}, // опускаться на колени rus_verbs:переехать{}, // переехать на конспиративную квартиру rus_verbs:закрывать{}, // закрывать глаза на действия конкурентов rus_verbs:поместить{}, // поместить на поднос rus_verbs:отходить{}, // отходить на подготовленные позиции rus_verbs:сыпаться{}, // сыпаться на плечи rus_verbs:отвезти{}, // отвезти на занятия rus_verbs:накинуть{}, // накинуть на плечи rus_verbs:отлететь{}, // отлететь на пол rus_verbs:закинуть{}, // закинуть на чердак rus_verbs:зашипеть{}, // зашипеть на собаку rus_verbs:прогреметь{}, // прогреметь на всю страну rus_verbs:повалить{}, // повалить на стол rus_verbs:опереть{}, // опереть на фундамент rus_verbs:забросить{}, // забросить на антресоль rus_verbs:подействовать{}, // подействовать на материал rus_verbs:разделять{}, // разделять на части rus_verbs:прикрикнуть{}, // прикрикнуть на детей rus_verbs:разложить{}, // разложить на множители rus_verbs:провожать{}, // провожать на работу rus_verbs:катить{}, // катить на стройку rus_verbs:наложить{}, // наложить запрет на проведение операций с недвижимостью rus_verbs:сохранять{}, // сохранять на память rus_verbs:злиться{}, // злиться на друга rus_verbs:оборачиваться{}, // оборачиваться на свист rus_verbs:сползти{}, // сползти на землю rus_verbs:записывать{}, // записывать на ленту rus_verbs:загнать{}, // загнать на дерево rus_verbs:забормотать{}, // забормотать на ухо rus_verbs:протиснуться{}, // протиснуться на самый край rus_verbs:заторопиться{}, // заторопиться на вручение премии rus_verbs:гаркнуть{}, // гаркнуть на шалунов rus_verbs:навалиться{}, // навалиться на виновника всей толпой rus_verbs:проскользнуть{}, // проскользнуть на крышу дома rus_verbs:подтянуть{}, // подтянуть на палубу rus_verbs:скатиться{}, // скатиться на двойки rus_verbs:давить{}, // давить на жалость rus_verbs:намекнуть{}, // намекнуть на новые обстоятельства rus_verbs:замахнуться{}, // замахнуться на святое rus_verbs:заменить{}, // заменить на свежую салфетку rus_verbs:свалить{}, // свалить на землю rus_verbs:стекать{}, // стекать на оголенные провода rus_verbs:увеличиваться{}, // увеличиваться на сотню процентов rus_verbs:развалиться{}, // развалиться на части rus_verbs:сердиться{}, // сердиться на товарища rus_verbs:обронить{}, // обронить на пол rus_verbs:подсесть{}, // подсесть на наркоту rus_verbs:реагировать{}, // реагировать на импульсы rus_verbs:отпускать{}, // отпускать на волю rus_verbs:прогнать{}, // прогнать на рабочее место rus_verbs:ложить{}, // ложить на стол rus_verbs:рвать{}, // рвать на части rus_verbs:разлететься{}, // разлететься на кусочки rus_verbs:превышать{}, // превышать на существенную величину rus_verbs:сбиться{}, // сбиться на рысь rus_verbs:пристроиться{}, // пристроиться на хорошую работу rus_verbs:удрать{}, // удрать на пастбище rus_verbs:толкать{}, // толкать на преступление rus_verbs:посматривать{}, // посматривать на экран rus_verbs:набирать{}, // набирать на судно rus_verbs:отступать{}, // отступать на дерево rus_verbs:подуть{}, // подуть на молоко rus_verbs:плеснуть{}, // плеснуть на голову rus_verbs:соскользнуть{}, // соскользнуть на землю rus_verbs:затаить{}, // затаить на кого-то обиду rus_verbs:обижаться{}, // обижаться на Колю rus_verbs:смахнуть{}, // смахнуть на пол rus_verbs:застегнуть{}, // застегнуть на все пуговицы rus_verbs:спускать{}, // спускать на землю rus_verbs:греметь{}, // греметь на всю округу rus_verbs:скосить{}, // скосить на соседа глаз rus_verbs:отважиться{}, // отважиться на прыжок rus_verbs:литься{}, // литься на землю rus_verbs:порвать{}, // порвать на тряпки rus_verbs:проследовать{}, // проследовать на сцену rus_verbs:надевать{}, // надевать на голову rus_verbs:проскочить{}, // проскочить на красный свет rus_verbs:прилечь{}, // прилечь на диванчик rus_verbs:разделиться{}, // разделиться на небольшие группы rus_verbs:завыть{}, // завыть на луну rus_verbs:переносить{}, // переносить на другую машину rus_verbs:наговорить{}, // наговорить на сотню рублей rus_verbs:намекать{}, // намекать на новые обстоятельства rus_verbs:нападать{}, // нападать на охранников rus_verbs:убегать{}, // убегать на другое место rus_verbs:тратить{}, // тратить на развлечения rus_verbs:присаживаться{}, // присаживаться на корточки rus_verbs:переместиться{}, // переместиться на вторую линию rus_verbs:завалиться{}, // завалиться на диван rus_verbs:удалиться{}, // удалиться на покой rus_verbs:уменьшаться{}, // уменьшаться на несколько процентов rus_verbs:обрушить{}, // обрушить на голову rus_verbs:резать{}, // резать на части rus_verbs:умчаться{}, // умчаться на юг rus_verbs:навернуться{}, // навернуться на камень rus_verbs:примчаться{}, // примчаться на матч rus_verbs:издавать{}, // издавать на собственные средства rus_verbs:переключить{}, // переключить на другой язык rus_verbs:отправлять{}, // отправлять на пенсию rus_verbs:залечь{}, // залечь на дно rus_verbs:установиться{}, // установиться на диск rus_verbs:направлять{}, // направлять на дополнительное обследование rus_verbs:разрезать{}, // разрезать на части rus_verbs:оскалиться{}, // оскалиться на прохожего rus_verbs:рычать{}, // рычать на пьяных rus_verbs:погружаться{}, // погружаться на дно rus_verbs:опираться{}, // опираться на костыли rus_verbs:поторопиться{}, // поторопиться на учебу rus_verbs:сдвинуться{}, // сдвинуться на сантиметр rus_verbs:увеличить{}, // увеличить на процент rus_verbs:опускать{}, // опускать на землю rus_verbs:созвать{}, // созвать на митинг rus_verbs:делить{}, // делить на части rus_verbs:пробиться{}, // пробиться на заключительную часть rus_verbs:простираться{}, // простираться на много миль rus_verbs:забить{}, // забить на учебу rus_verbs:переложить{}, // переложить на чужие плечи rus_verbs:грохнуться{}, // грохнуться на землю rus_verbs:прорваться{}, // прорваться на сцену rus_verbs:разлить{}, // разлить на землю rus_verbs:укладываться{}, // укладываться на ночевку rus_verbs:уволить{}, // уволить на пенсию rus_verbs:наносить{}, // наносить на кожу rus_verbs:набежать{}, // набежать на берег rus_verbs:заявиться{}, // заявиться на стрельбище rus_verbs:налиться{}, // налиться на крышку rus_verbs:надвигаться{}, // надвигаться на берег rus_verbs:распустить{}, // распустить на каникулы rus_verbs:переключиться{}, // переключиться на другую задачу rus_verbs:чихнуть{}, // чихнуть на окружающих rus_verbs:шлепнуться{}, // шлепнуться на спину rus_verbs:устанавливать{}, // устанавливать на крышу rus_verbs:устанавливаться{}, // устанавливаться на крышу rus_verbs:устраиваться{}, // устраиваться на работу rus_verbs:пропускать{}, // пропускать на стадион инфинитив:сбегать{ вид:соверш }, глагол:сбегать{ вид:соверш }, // сбегать на фильм инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, деепричастие:сбегав{}, деепричастие:сбегая{}, rus_verbs:показываться{}, // показываться на глаза rus_verbs:прибегать{}, // прибегать на урок rus_verbs:съездить{}, // съездить на ферму rus_verbs:прославиться{}, // прославиться на всю страну rus_verbs:опрокинуться{}, // опрокинуться на спину rus_verbs:насыпать{}, // насыпать на землю rus_verbs:употреблять{}, // употреблять на корм скоту rus_verbs:пристроить{}, // пристроить на работу rus_verbs:заворчать{}, // заворчать на вошедшего rus_verbs:завязаться{}, // завязаться на поставщиков rus_verbs:сажать{}, // сажать на стул rus_verbs:напрашиваться{}, // напрашиваться на жесткие ответные меры rus_verbs:заменять{}, // заменять на исправную rus_verbs:нацепить{}, // нацепить на голову rus_verbs:сыпать{}, // сыпать на землю rus_verbs:закрываться{}, // закрываться на ремонт rus_verbs:распространиться{}, // распространиться на всю популяцию rus_verbs:поменять{}, // поменять на велосипед rus_verbs:пересесть{}, // пересесть на велосипеды rus_verbs:подоспеть{}, // подоспеть на разбор rus_verbs:шипеть{}, // шипеть на собак rus_verbs:поделить{}, // поделить на части rus_verbs:подлететь{}, // подлететь на расстояние выстрела rus_verbs:нажимать{}, // нажимать на все кнопки rus_verbs:распасться{}, // распасться на части rus_verbs:приволочь{}, // приволочь на диван rus_verbs:пожить{}, // пожить на один доллар rus_verbs:устремляться{}, // устремляться на свободу rus_verbs:смахивать{}, // смахивать на пол rus_verbs:забежать{}, // забежать на обед rus_verbs:увеличиться{}, // увеличиться на существенную величину rus_verbs:прокрасться{}, // прокрасться на склад rus_verbs:пущать{}, // пущать на постой rus_verbs:отклонить{}, // отклонить на несколько градусов rus_verbs:насмотреться{}, // насмотреться на безобразия rus_verbs:настроить{}, // настроить на короткие волны rus_verbs:уменьшиться{}, // уменьшиться на пару сантиметров rus_verbs:поменяться{}, // поменяться на другую книжку rus_verbs:расколоться{}, // расколоться на части rus_verbs:разлиться{}, // разлиться на землю rus_verbs:срываться{}, // срываться на жену rus_verbs:осудить{}, // осудить на пожизненное заключение rus_verbs:передвинуть{}, // передвинуть на первое место rus_verbs:допускаться{}, // допускаться на полигон rus_verbs:задвинуть{}, // задвинуть на полку rus_verbs:повлиять{}, // повлиять на оценку rus_verbs:отбавлять{}, // отбавлять на осмотр rus_verbs:сбрасывать{}, // сбрасывать на землю rus_verbs:накинуться{}, // накинуться на случайных прохожих rus_verbs:пролить{}, // пролить на кожу руки rus_verbs:затащить{}, // затащить на сеновал rus_verbs:перебежать{}, // перебежать на сторону противника rus_verbs:наливать{}, // наливать на скатерть rus_verbs:пролезть{}, // пролезть на сцену rus_verbs:откладывать{}, // откладывать на черный день rus_verbs:распадаться{}, // распадаться на небольшие фрагменты rus_verbs:перечислить{}, // перечислить на счет rus_verbs:закачаться{}, // закачаться на верхний уровень rus_verbs:накрениться{}, // накрениться на правый борт rus_verbs:подвинуться{}, // подвинуться на один уровень rus_verbs:разнести{}, // разнести на мелкие кусочки rus_verbs:зажить{}, // зажить на широкую ногу rus_verbs:оглохнуть{}, // оглохнуть на правое ухо rus_verbs:посетовать{}, // посетовать на бюрократизм rus_verbs:уводить{}, // уводить на осмотр rus_verbs:ускакать{}, // ускакать на забег rus_verbs:посветить{}, // посветить на стену rus_verbs:разрываться{}, // разрываться на части rus_verbs:побросать{}, // побросать на землю rus_verbs:карабкаться{}, // карабкаться на скалу rus_verbs:нахлынуть{}, // нахлынуть на кого-то rus_verbs:разлетаться{}, // разлетаться на мелкие осколочки rus_verbs:среагировать{}, // среагировать на сигнал rus_verbs:претендовать{}, // претендовать на приз rus_verbs:дунуть{}, // дунуть на одуванчик rus_verbs:переводиться{}, // переводиться на другую работу rus_verbs:перевезти{}, // перевезти на другую площадку rus_verbs:топать{}, // топать на урок rus_verbs:относить{}, // относить на склад rus_verbs:сбивать{}, // сбивать на землю rus_verbs:укладывать{}, // укладывать на спину rus_verbs:укатить{}, // укатить на отдых rus_verbs:убирать{}, // убирать на полку rus_verbs:опасть{}, // опасть на землю rus_verbs:ронять{}, // ронять на снег rus_verbs:пялиться{}, // пялиться на тело rus_verbs:глазеть{}, // глазеть на тело rus_verbs:снижаться{}, // снижаться на безопасную высоту rus_verbs:запрыгнуть{}, // запрыгнуть на платформу rus_verbs:разбиваться{}, // разбиваться на главы rus_verbs:сгодиться{}, // сгодиться на фарш rus_verbs:перескочить{}, // перескочить на другую страницу rus_verbs:нацелиться{}, // нацелиться на главную добычу rus_verbs:заезжать{}, // заезжать на бордюр rus_verbs:забираться{}, // забираться на крышу rus_verbs:проорать{}, // проорать на всё село rus_verbs:сбежаться{}, // сбежаться на шум rus_verbs:сменять{}, // сменять на хлеб rus_verbs:мотать{}, // мотать на ус rus_verbs:раскалываться{}, // раскалываться на две половинки rus_verbs:коситься{}, // коситься на режиссёра rus_verbs:плевать{}, // плевать на законы rus_verbs:ссылаться{}, // ссылаться на авторитетное мнение rus_verbs:наставить{}, // наставить на путь истинный rus_verbs:завывать{}, // завывать на Луну rus_verbs:опаздывать{}, // опаздывать на совещание rus_verbs:залюбоваться{}, // залюбоваться на пейзаж rus_verbs:повергнуть{}, // повергнуть на землю rus_verbs:надвинуть{}, // надвинуть на лоб rus_verbs:стекаться{}, // стекаться на площадь rus_verbs:обозлиться{}, // обозлиться на тренера rus_verbs:оттянуть{}, // оттянуть на себя rus_verbs:истратить{}, // истратить на дешевых шлюх rus_verbs:вышвырнуть{}, // вышвырнуть на улицу rus_verbs:затолкать{}, // затолкать на верхнюю полку rus_verbs:заскочить{}, // заскочить на огонек rus_verbs:проситься{}, // проситься на улицу rus_verbs:натыкаться{}, // натыкаться на борщевик rus_verbs:обрушиваться{}, // обрушиваться на митингующих rus_verbs:переписать{}, // переписать на чистовик rus_verbs:переноситься{}, // переноситься на другое устройство rus_verbs:напроситься{}, // напроситься на обидный ответ rus_verbs:натягивать{}, // натягивать на ноги rus_verbs:кидаться{}, // кидаться на прохожих rus_verbs:откликаться{}, // откликаться на призыв rus_verbs:поспевать{}, // поспевать на балет rus_verbs:обратиться{}, // обратиться на кафедру rus_verbs:полюбоваться{}, // полюбоваться на бюст rus_verbs:таращиться{}, // таращиться на мустангов rus_verbs:напороться{}, // напороться на колючки rus_verbs:раздать{}, // раздать на руки rus_verbs:дивиться{}, // дивиться на танцовщиц rus_verbs:назначать{}, // назначать на ответственнейший пост rus_verbs:кидать{}, // кидать на балкон rus_verbs:нахлобучить{}, // нахлобучить на башку rus_verbs:увлекать{}, // увлекать на луг rus_verbs:ругнуться{}, // ругнуться на животину rus_verbs:переселиться{}, // переселиться на хутор rus_verbs:разрывать{}, // разрывать на части rus_verbs:утащить{}, // утащить на дерево rus_verbs:наставлять{}, // наставлять на путь rus_verbs:соблазнить{}, // соблазнить на обмен rus_verbs:накладывать{}, // накладывать на рану rus_verbs:набрести{}, // набрести на грибную поляну rus_verbs:наведываться{}, // наведываться на прежнюю работу rus_verbs:погулять{}, // погулять на чужие деньги rus_verbs:уклоняться{}, // уклоняться на два градуса влево rus_verbs:слезать{}, // слезать на землю rus_verbs:клевать{}, // клевать на мотыля // rus_verbs:назначаться{}, // назначаться на пост rus_verbs:напялить{}, // напялить на голову rus_verbs:натянуться{}, // натянуться на рамку rus_verbs:разгневаться{}, // разгневаться на придворных rus_verbs:эмигрировать{}, // эмигрировать на Кипр rus_verbs:накатить{}, // накатить на основу rus_verbs:пригнать{}, // пригнать на пастбище rus_verbs:обречь{}, // обречь на мучения rus_verbs:сокращаться{}, // сокращаться на четверть rus_verbs:оттеснить{}, // оттеснить на пристань rus_verbs:подбить{}, // подбить на аферу rus_verbs:заманить{}, // заманить на дерево инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на кустик // деепричастие:пописав{ aux stress="поп^исать" }, rus_verbs:посходить{}, // посходить на перрон rus_verbs:налечь{}, // налечь на мясцо rus_verbs:отбирать{}, // отбирать на флот rus_verbs:нашептывать{}, // нашептывать на ухо rus_verbs:откладываться{}, // откладываться на будущее rus_verbs:залаять{}, // залаять на грабителя rus_verbs:настроиться{}, // настроиться на прием rus_verbs:разбивать{}, // разбивать на куски rus_verbs:пролиться{}, // пролиться на почву rus_verbs:сетовать{}, // сетовать на объективные трудности rus_verbs:подвезти{}, // подвезти на митинг rus_verbs:припереться{}, // припереться на праздник rus_verbs:подталкивать{}, // подталкивать на прыжок rus_verbs:прорываться{}, // прорываться на сцену rus_verbs:снижать{}, // снижать на несколько процентов rus_verbs:нацелить{}, // нацелить на танк rus_verbs:расколоть{}, // расколоть на два куска rus_verbs:увозить{}, // увозить на обкатку rus_verbs:оседать{}, // оседать на дно rus_verbs:съедать{}, // съедать на ужин rus_verbs:навлечь{}, // навлечь на себя rus_verbs:равняться{}, // равняться на лучших rus_verbs:сориентироваться{}, // сориентироваться на местности rus_verbs:снизить{}, // снизить на несколько процентов rus_verbs:перенестись{}, // перенестись на много лет назад rus_verbs:завезти{}, // завезти на склад rus_verbs:проложить{}, // проложить на гору rus_verbs:понадеяться{}, // понадеяться на удачу rus_verbs:заступить{}, // заступить на вахту rus_verbs:засеменить{}, // засеменить на выход rus_verbs:запирать{}, // запирать на ключ rus_verbs:скатываться{}, // скатываться на землю rus_verbs:дробить{}, // дробить на части rus_verbs:разваливаться{}, // разваливаться на кусочки rus_verbs:завозиться{}, // завозиться на склад rus_verbs:нанимать{}, // нанимать на дневную работу rus_verbs:поспеть{}, // поспеть на концерт rus_verbs:променять{}, // променять на сытость rus_verbs:переправить{}, // переправить на север rus_verbs:налетать{}, // налетать на силовое поле rus_verbs:затворить{}, // затворить на замок rus_verbs:подогнать{}, // подогнать на пристань rus_verbs:наехать{}, // наехать на камень rus_verbs:распевать{}, // распевать на разные голоса rus_verbs:разносить{}, // разносить на клочки rus_verbs:преувеличивать{}, // преувеличивать на много килограммов rus_verbs:хромать{}, // хромать на одну ногу rus_verbs:телеграфировать{}, // телеграфировать на базу rus_verbs:порезать{}, // порезать на лоскуты rus_verbs:порваться{}, // порваться на части rus_verbs:загонять{}, // загонять на дерево rus_verbs:отбывать{}, // отбывать на место службы rus_verbs:усаживаться{}, // усаживаться на трон rus_verbs:накопить{}, // накопить на квартиру rus_verbs:зыркнуть{}, // зыркнуть на визитера rus_verbs:копить{}, // копить на машину rus_verbs:помещать{}, // помещать на верхнюю грань rus_verbs:сползать{}, // сползать на снег rus_verbs:попроситься{}, // попроситься на улицу rus_verbs:перетащить{}, // перетащить на чердак rus_verbs:растащить{}, // растащить на сувениры rus_verbs:ниспадать{}, // ниспадать на землю rus_verbs:сфотографировать{}, // сфотографировать на память rus_verbs:нагонять{}, // нагонять на конкурентов страх rus_verbs:покушаться{}, // покушаться на понтифика rus_verbs:покуситься{}, rus_verbs:наняться{}, // наняться на службу rus_verbs:просачиваться{}, // просачиваться на поверхность rus_verbs:пускаться{}, // пускаться на ветер rus_verbs:отваживаться{}, // отваживаться на прыжок rus_verbs:досадовать{}, // досадовать на объективные трудности rus_verbs:унестись{}, // унестись на небо rus_verbs:ухудшаться{}, // ухудшаться на несколько процентов rus_verbs:насадить{}, // насадить на копьё rus_verbs:нагрянуть{}, // нагрянуть на праздник rus_verbs:зашвырнуть{}, // зашвырнуть на полку rus_verbs:грешить{}, // грешить на постояльцев rus_verbs:просочиться{}, // просочиться на поверхность rus_verbs:надоумить{}, // надоумить на глупость rus_verbs:намотать{}, // намотать на шпиндель rus_verbs:замкнуть{}, // замкнуть на корпус rus_verbs:цыкнуть{}, // цыкнуть на детей rus_verbs:переворачиваться{}, // переворачиваться на спину rus_verbs:соваться{}, // соваться на площать rus_verbs:отлучиться{}, // отлучиться на обед rus_verbs:пенять{}, // пенять на себя rus_verbs:нарезать{}, // нарезать на ломтики rus_verbs:поставлять{}, // поставлять на Кипр rus_verbs:залезать{}, // залезать на балкон rus_verbs:отлучаться{}, // отлучаться на обед rus_verbs:сбиваться{}, // сбиваться на шаг rus_verbs:таращить{}, // таращить глаза на вошедшего rus_verbs:прошмыгнуть{}, // прошмыгнуть на кухню rus_verbs:опережать{}, // опережать на пару сантиметров rus_verbs:переставить{}, // переставить на стол rus_verbs:раздирать{}, // раздирать на части rus_verbs:затвориться{}, // затвориться на засовы rus_verbs:материться{}, // материться на кого-то rus_verbs:наскочить{}, // наскочить на риф rus_verbs:набираться{}, // набираться на борт rus_verbs:покрикивать{}, // покрикивать на помощников rus_verbs:заменяться{}, // заменяться на более новый rus_verbs:подсадить{}, // подсадить на верхнюю полку rus_verbs:проковылять{}, // проковылять на кухню rus_verbs:прикатить{}, // прикатить на старт rus_verbs:залететь{}, // залететь на чужую территорию rus_verbs:загрузить{}, // загрузить на конвейер rus_verbs:уплывать{}, // уплывать на материк rus_verbs:опозорить{}, // опозорить на всю деревню rus_verbs:провоцировать{}, // провоцировать на ответную агрессию rus_verbs:забивать{}, // забивать на учебу rus_verbs:набегать{}, // набегать на прибрежные деревни rus_verbs:запираться{}, // запираться на ключ rus_verbs:фотографировать{}, // фотографировать на мыльницу rus_verbs:подымать{}, // подымать на недосягаемую высоту rus_verbs:съезжаться{}, // съезжаться на симпозиум rus_verbs:отвлекаться{}, // отвлекаться на игру rus_verbs:проливать{}, // проливать на брюки rus_verbs:спикировать{}, // спикировать на зазевавшегося зайца rus_verbs:уползти{}, // уползти на вершину холма rus_verbs:переместить{}, // переместить на вторую палубу rus_verbs:превысить{}, // превысить на несколько метров rus_verbs:передвинуться{}, // передвинуться на соседнюю клетку rus_verbs:спровоцировать{}, // спровоцировать на бросок rus_verbs:сместиться{}, // сместиться на соседнюю клетку rus_verbs:заготовить{}, // заготовить на зиму rus_verbs:плеваться{}, // плеваться на пол rus_verbs:переселить{}, // переселить на север rus_verbs:напирать{}, // напирать на дверь rus_verbs:переезжать{}, // переезжать на другой этаж rus_verbs:приподнимать{}, // приподнимать на несколько сантиметров rus_verbs:трогаться{}, // трогаться на красный свет rus_verbs:надвинуться{}, // надвинуться на глаза rus_verbs:засмотреться{}, // засмотреться на купальники rus_verbs:убыть{}, // убыть на фронт rus_verbs:передвигать{}, // передвигать на второй уровень rus_verbs:отвозить{}, // отвозить на свалку rus_verbs:обрекать{}, // обрекать на гибель rus_verbs:записываться{}, // записываться на танцы rus_verbs:настраивать{}, // настраивать на другой диапазон rus_verbs:переписывать{}, // переписывать на диск rus_verbs:израсходовать{}, // израсходовать на гонки rus_verbs:обменять{}, // обменять на перспективного игрока rus_verbs:трубить{}, // трубить на всю округу rus_verbs:набрасываться{}, // набрасываться на жертву rus_verbs:чихать{}, // чихать на правила rus_verbs:наваливаться{}, // наваливаться на рычаг rus_verbs:сподобиться{}, // сподобиться на повторный анализ rus_verbs:намазать{}, // намазать на хлеб rus_verbs:прореагировать{}, // прореагировать на вызов rus_verbs:зачислить{}, // зачислить на факультет rus_verbs:наведаться{}, // наведаться на склад rus_verbs:откидываться{}, // откидываться на спинку кресла rus_verbs:захромать{}, // захромать на левую ногу rus_verbs:перекочевать{}, // перекочевать на другой берег rus_verbs:накатываться{}, // накатываться на песчаный берег rus_verbs:приостановить{}, // приостановить на некоторое время rus_verbs:запрятать{}, // запрятать на верхнюю полочку rus_verbs:прихрамывать{}, // прихрамывать на правую ногу rus_verbs:упорхнуть{}, // упорхнуть на свободу rus_verbs:расстегивать{}, // расстегивать на пальто rus_verbs:напуститься{}, // напуститься на бродягу rus_verbs:накатывать{}, // накатывать на оригинал rus_verbs:наезжать{}, // наезжать на простофилю rus_verbs:тявкнуть{}, // тявкнуть на подошедшего человека rus_verbs:отрядить{}, // отрядить на починку rus_verbs:положиться{}, // положиться на главаря rus_verbs:опрокидывать{}, // опрокидывать на голову rus_verbs:поторапливаться{}, // поторапливаться на рейс rus_verbs:налагать{}, // налагать на заемщика rus_verbs:скопировать{}, // скопировать на диск rus_verbs:опадать{}, // опадать на землю rus_verbs:купиться{}, // купиться на посулы rus_verbs:гневаться{}, // гневаться на слуг rus_verbs:слететься{}, // слететься на раздачу rus_verbs:убавить{}, // убавить на два уровня rus_verbs:спихнуть{}, // спихнуть на соседа rus_verbs:накричать{}, // накричать на ребенка rus_verbs:приберечь{}, // приберечь на ужин rus_verbs:приклеить{}, // приклеить на ветровое стекло rus_verbs:ополчиться{}, // ополчиться на посредников rus_verbs:тратиться{}, // тратиться на сувениры rus_verbs:слетаться{}, // слетаться на свет rus_verbs:доставляться{}, // доставляться на базу rus_verbs:поплевать{}, // поплевать на руки rus_verbs:огрызаться{}, // огрызаться на замечание rus_verbs:попереться{}, // попереться на рынок rus_verbs:растягиваться{}, // растягиваться на полу rus_verbs:повергать{}, // повергать на землю rus_verbs:ловиться{}, // ловиться на мотыля rus_verbs:наседать{}, // наседать на обороняющихся rus_verbs:развалить{}, // развалить на кирпичи rus_verbs:разломить{}, // разломить на несколько частей rus_verbs:примерить{}, // примерить на себя rus_verbs:лепиться{}, // лепиться на стену rus_verbs:скопить{}, // скопить на старость rus_verbs:затратить{}, // затратить на ликвидацию последствий rus_verbs:притащиться{}, // притащиться на гулянку rus_verbs:осерчать{}, // осерчать на прислугу rus_verbs:натравить{}, // натравить на медведя rus_verbs:ссыпать{}, // ссыпать на землю rus_verbs:подвозить{}, // подвозить на пристань rus_verbs:мобилизовать{}, // мобилизовать на сборы rus_verbs:смотаться{}, // смотаться на работу rus_verbs:заглядеться{}, // заглядеться на девчонок rus_verbs:таскаться{}, // таскаться на работу rus_verbs:разгружать{}, // разгружать на транспортер rus_verbs:потреблять{}, // потреблять на кондиционирование инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять на базу деепричастие:сгоняв{}, rus_verbs:посылаться{}, // посылаться на разведку rus_verbs:окрыситься{}, // окрыситься на кого-то rus_verbs:отлить{}, // отлить на сковороду rus_verbs:шикнуть{}, // шикнуть на детишек rus_verbs:уповать{}, // уповать на бескорысную помощь rus_verbs:класться{}, // класться на стол rus_verbs:поковылять{}, // поковылять на выход rus_verbs:навевать{}, // навевать на собравшихся скуку rus_verbs:накладываться{}, // накладываться на грунтовку rus_verbs:наноситься{}, // наноситься на чистую кожу // rus_verbs:запланировать{}, // запланировать на среду rus_verbs:кувыркнуться{}, // кувыркнуться на землю rus_verbs:гавкнуть{}, // гавкнуть на хозяина rus_verbs:перестроиться{}, // перестроиться на новый лад rus_verbs:расходоваться{}, // расходоваться на образование rus_verbs:дуться{}, // дуться на бабушку rus_verbs:перетаскивать{}, // перетаскивать на рабочий стол rus_verbs:издаться{}, // издаться на деньги спонсоров rus_verbs:смещаться{}, // смещаться на несколько миллиметров rus_verbs:зазывать{}, // зазывать на новогоднюю распродажу rus_verbs:пикировать{}, // пикировать на окопы rus_verbs:чертыхаться{}, // чертыхаться на мешающихся детей rus_verbs:зудить{}, // зудить на ухо rus_verbs:подразделяться{}, // подразделяться на группы rus_verbs:изливаться{}, // изливаться на землю rus_verbs:помочиться{}, // помочиться на траву rus_verbs:примерять{}, // примерять на себя rus_verbs:разрядиться{}, // разрядиться на землю rus_verbs:мотнуться{}, // мотнуться на крышу rus_verbs:налегать{}, // налегать на весла rus_verbs:зацокать{}, // зацокать на куриц rus_verbs:наниматься{}, // наниматься на корабль rus_verbs:сплевывать{}, // сплевывать на землю rus_verbs:настучать{}, // настучать на саботажника rus_verbs:приземляться{}, // приземляться на брюхо rus_verbs:наталкиваться{}, // наталкиваться на объективные трудности rus_verbs:посигналить{}, // посигналить нарушителю, выехавшему на встречную полосу rus_verbs:серчать{}, // серчать на нерасторопную помощницу rus_verbs:сваливать{}, // сваливать на подоконник rus_verbs:засобираться{}, // засобираться на работу rus_verbs:распилить{}, // распилить на одинаковые бруски //rus_verbs:умножать{}, // умножать на константу rus_verbs:копировать{}, // копировать на диск rus_verbs:накрутить{}, // накрутить на руку rus_verbs:навалить{}, // навалить на телегу rus_verbs:натолкнуть{}, // натолкнуть на свежую мысль rus_verbs:шлепаться{}, // шлепаться на бетон rus_verbs:ухлопать{}, // ухлопать на скупку произведений искусства rus_verbs:замахиваться{}, // замахиваться на авторитетнейшее мнение rus_verbs:посягнуть{}, // посягнуть на святое rus_verbs:разменять{}, // разменять на мелочь rus_verbs:откатываться{}, // откатываться на заранее подготовленные позиции rus_verbs:усаживать{}, // усаживать на скамейку rus_verbs:натаскать{}, // натаскать на поиск наркотиков rus_verbs:зашикать{}, // зашикать на кошку rus_verbs:разломать{}, // разломать на равные части rus_verbs:приглашаться{}, // приглашаться на сцену rus_verbs:присягать{}, // присягать на верность rus_verbs:запрограммировать{}, // запрограммировать на постоянную уборку rus_verbs:расщедриться{}, // расщедриться на новый компьютер rus_verbs:насесть{}, // насесть на двоечников rus_verbs:созывать{}, // созывать на собрание rus_verbs:позариться{}, // позариться на чужое добро rus_verbs:перекидываться{}, // перекидываться на соседние здания rus_verbs:наползать{}, // наползать на неповрежденную ткань rus_verbs:изрубить{}, // изрубить на мелкие кусочки rus_verbs:наворачиваться{}, // наворачиваться на глаза rus_verbs:раскричаться{}, // раскричаться на всю округу rus_verbs:переползти{}, // переползти на светлую сторону rus_verbs:уполномочить{}, // уполномочить на разведовательную операцию rus_verbs:мочиться{}, // мочиться на трупы убитых врагов rus_verbs:радировать{}, // радировать на базу rus_verbs:промотать{}, // промотать на начало rus_verbs:заснять{}, // заснять на видео rus_verbs:подбивать{}, // подбивать на матч-реванш rus_verbs:наплевать{}, // наплевать на справедливость rus_verbs:подвывать{}, // подвывать на луну rus_verbs:расплескать{}, // расплескать на пол rus_verbs:польститься{}, // польститься на бесплатный сыр rus_verbs:помчать{}, // помчать на работу rus_verbs:съезжать{}, // съезжать на обочину rus_verbs:нашептать{}, // нашептать кому-то на ухо rus_verbs:наклеить{}, // наклеить на доску объявлений rus_verbs:завозить{}, // завозить на склад rus_verbs:заявляться{}, // заявляться на любимую работу rus_verbs:наглядеться{}, // наглядеться на воробьев rus_verbs:хлопнуться{}, // хлопнуться на живот rus_verbs:забредать{}, // забредать на поляну rus_verbs:посягать{}, // посягать на исконные права собственности rus_verbs:сдвигать{}, // сдвигать на одну позицию rus_verbs:спрыгивать{}, // спрыгивать на землю rus_verbs:сдвигаться{}, // сдвигаться на две позиции rus_verbs:разделать{}, // разделать на орехи rus_verbs:разлагать{}, // разлагать на элементарные элементы rus_verbs:обрушивать{}, // обрушивать на головы врагов rus_verbs:натечь{}, // натечь на пол rus_verbs:политься{}, // вода польется на землю rus_verbs:успеть{}, // Они успеют на поезд. инфинитив:мигрировать{ вид:несоверш }, глагол:мигрировать{ вид:несоверш }, деепричастие:мигрируя{}, инфинитив:мигрировать{ вид:соверш }, глагол:мигрировать{ вид:соверш }, деепричастие:мигрировав{}, rus_verbs:двинуться{}, // Мы скоро двинемся на дачу. rus_verbs:подойти{}, // Он не подойдёт на должность секретаря. rus_verbs:потянуть{}, // Он не потянет на директора. rus_verbs:тянуть{}, // Он не тянет на директора. rus_verbs:перескакивать{}, // перескакивать с одного примера на другой rus_verbs:жаловаться{}, // Он жалуется на нездоровье. rus_verbs:издать{}, // издать на деньги спонсоров rus_verbs:показаться{}, // показаться на глаза rus_verbs:высаживать{}, // высаживать на необитаемый остров rus_verbs:вознестись{}, // вознестись на самую вершину славы rus_verbs:залить{}, // залить на youtube rus_verbs:закачать{}, // закачать на youtube rus_verbs:сыграть{}, // сыграть на деньги rus_verbs:экстраполировать{}, // Формулу можно экстраполировать на случай нескольких переменных инфинитив:экстраполироваться{ вид:несоверш}, // Ситуация легко экстраполируется на случай нескольких переменных глагол:экстраполироваться{ вид:несоверш}, инфинитив:экстраполироваться{ вид:соверш}, глагол:экстраполироваться{ вид:соверш}, деепричастие:экстраполируясь{}, инфинитив:акцентировать{вид:соверш}, // оратор акцентировал внимание слушателей на новый аспект проблемы глагол:акцентировать{вид:соверш}, инфинитив:акцентировать{вид:несоверш}, глагол:акцентировать{вид:несоверш}, прилагательное:акцентировавший{вид:несоверш}, //прилагательное:акцентировавший{вид:соверш}, прилагательное:акцентирующий{}, деепричастие:акцентировав{}, деепричастие:акцентируя{}, rus_verbs:бабахаться{}, // он бабахался на пол rus_verbs:бабахнуться{}, // мальчил бабахнулся на асфальт rus_verbs:батрачить{}, // Крестьяне батрачили на хозяина rus_verbs:бахаться{}, // Наездники бахались на землю rus_verbs:бахнуться{}, // Наездник опять бахнулся на землю rus_verbs:благословить{}, // батюшка благословил отрока на подвиг rus_verbs:благословлять{}, // батюшка благословляет отрока на подвиг rus_verbs:блевануть{}, // Он блеванул на землю rus_verbs:блевать{}, // Он блюет на землю rus_verbs:бухнуться{}, // Наездник бухнулся на землю rus_verbs:валить{}, // Ветер валил деревья на землю rus_verbs:спилить{}, // Спиленное дерево валится на землю rus_verbs:ввезти{}, // Предприятие ввезло товар на таможню rus_verbs:вдохновить{}, // Фильм вдохновил мальчика на поход в лес rus_verbs:вдохновиться{}, // Мальчик вдохновился на поход rus_verbs:вдохновлять{}, // Фильм вдохновляет на поход в лес rus_verbs:вестись{}, // Не ведись на эти уловки! rus_verbs:вешать{}, // Гости вешают одежду на вешалку rus_verbs:вешаться{}, // Одежда вешается на вешалки rus_verbs:вещать{}, // радиостанция вещает на всю страну rus_verbs:взбираться{}, // Туристы взбираются на заросший лесом холм rus_verbs:взбредать{}, // Что иногда взбредает на ум rus_verbs:взбрести{}, // Что-то взбрело на ум rus_verbs:взвалить{}, // Мама взвалила на свои плечи всё домашнее хозяйство rus_verbs:взваливаться{}, // Все домашнее хозяйство взваливается на мамины плечи rus_verbs:взваливать{}, // Не надо взваливать всё на мои плечи rus_verbs:взглянуть{}, // Кошка взглянула на мышку rus_verbs:взгромождать{}, // Мальчик взгромождает стул на стол rus_verbs:взгромождаться{}, // Мальчик взгромождается на стол rus_verbs:взгромоздить{}, // Мальчик взгромоздил стул на стол rus_verbs:взгромоздиться{}, // Мальчик взгромоздился на стул rus_verbs:взирать{}, // Очевидцы взирали на непонятный объект rus_verbs:взлетать{}, // Фабрика фейерверков взлетает на воздух rus_verbs:взлететь{}, // Фабрика фейерверков взлетела на воздух rus_verbs:взобраться{}, // Туристы взобрались на гору rus_verbs:взойти{}, // Туристы взошли на гору rus_verbs:взъесться{}, // Отец взъелся на непутевого сына rus_verbs:взъяриться{}, // Отец взъярился на непутевого сына rus_verbs:вкатить{}, // рабочие вкатили бочку на пандус rus_verbs:вкатывать{}, // рабочик вкатывают бочку на пандус rus_verbs:влиять{}, // Это решение влияет на всех игроков рынка rus_verbs:водворить{}, // водворить нарушителя на место rus_verbs:водвориться{}, // водвориться на свое место rus_verbs:водворять{}, // водворять вещь на свое место rus_verbs:водворяться{}, // водворяться на свое место rus_verbs:водружать{}, // водружать флаг на флагшток rus_verbs:водружаться{}, // Флаг водружается на флагшток rus_verbs:водрузить{}, // водрузить флаг на флагшток rus_verbs:водрузиться{}, // Флаг водрузился на вершину горы rus_verbs:воздействовать{}, // Излучение воздействует на кожу rus_verbs:воззреть{}, // воззреть на поле боя rus_verbs:воззриться{}, // воззриться на поле боя rus_verbs:возить{}, // возить туристов на гору rus_verbs:возлагать{}, // Многочисленные посетители возлагают цветы на могилу rus_verbs:возлагаться{}, // Ответственность возлагается на начальство rus_verbs:возлечь{}, // возлечь на лежанку rus_verbs:возложить{}, // возложить цветы на могилу поэта rus_verbs:вознести{}, // вознести кого-то на вершину славы rus_verbs:возноситься{}, // возносится на вершину успеха rus_verbs:возносить{}, // возносить счастливчика на вершину успеха rus_verbs:подниматься{}, // Мы поднимаемся на восьмой этаж rus_verbs:подняться{}, // Мы поднялись на восьмой этаж rus_verbs:вонять{}, // Кусок сыра воняет на всю округу rus_verbs:воодушевлять{}, // Идеалы воодушевляют на подвиги rus_verbs:воодушевляться{}, // Люди воодушевляются на подвиги rus_verbs:ворчать{}, // Старый пес ворчит на прохожих rus_verbs:воспринимать{}, // воспринимать сообщение на слух rus_verbs:восприниматься{}, // сообщение плохо воспринимается на слух rus_verbs:воспринять{}, // воспринять сообщение на слух rus_verbs:восприняться{}, // восприняться на слух rus_verbs:воссесть{}, // Коля воссел на трон rus_verbs:вправить{}, // вправить мозг на место rus_verbs:вправлять{}, // вправлять мозги на место rus_verbs:временить{}, // временить с выходом на пенсию rus_verbs:врубать{}, // врубать на полную мощность rus_verbs:врубить{}, // врубить на полную мощность rus_verbs:врубиться{}, // врубиться на полную мощность rus_verbs:врываться{}, // врываться на собрание rus_verbs:вскарабкаться{}, // вскарабкаться на утёс rus_verbs:вскарабкиваться{}, // вскарабкиваться на утёс rus_verbs:вскочить{}, // вскочить на ноги rus_verbs:всплывать{}, // всплывать на поверхность воды rus_verbs:всплыть{}, // всплыть на поверхность воды rus_verbs:вспрыгивать{}, // вспрыгивать на платформу rus_verbs:вспрыгнуть{}, // вспрыгнуть на платформу rus_verbs:встать{}, // встать на защиту чести и достоинства rus_verbs:вторгаться{}, // вторгаться на чужую территорию rus_verbs:вторгнуться{}, // вторгнуться на чужую территорию rus_verbs:въезжать{}, // въезжать на пандус rus_verbs:наябедничать{}, // наябедничать на соседа по парте rus_verbs:выблевать{}, // выблевать завтрак на пол rus_verbs:выблеваться{}, // выблеваться на пол rus_verbs:выблевывать{}, // выблевывать завтрак на пол rus_verbs:выблевываться{}, // выблевываться на пол rus_verbs:вывезти{}, // вывезти мусор на свалку rus_verbs:вывесить{}, // вывесить белье на просушку rus_verbs:вывести{}, // вывести собаку на прогулку rus_verbs:вывешивать{}, // вывешивать белье на веревку rus_verbs:вывозить{}, // вывозить детей на природу rus_verbs:вызывать{}, // Начальник вызывает на ковер rus_verbs:выйти{}, // выйти на свободу rus_verbs:выкладывать{}, // выкладывать на всеобщее обозрение rus_verbs:выкладываться{}, // выкладываться на всеобщее обозрение rus_verbs:выливать{}, // выливать на землю rus_verbs:выливаться{}, // выливаться на землю rus_verbs:вылить{}, // вылить жидкость на землю rus_verbs:вылиться{}, // Топливо вылилось на землю rus_verbs:выложить{}, // выложить на берег rus_verbs:выменивать{}, // выменивать золото на хлеб rus_verbs:вымениваться{}, // Золото выменивается на хлеб rus_verbs:выменять{}, // выменять золото на хлеб rus_verbs:выпадать{}, // снег выпадает на землю rus_verbs:выплевывать{}, // выплевывать на землю rus_verbs:выплевываться{}, // выплевываться на землю rus_verbs:выплескать{}, // выплескать на землю rus_verbs:выплескаться{}, // выплескаться на землю rus_verbs:выплескивать{}, // выплескивать на землю rus_verbs:выплескиваться{}, // выплескиваться на землю rus_verbs:выплывать{}, // выплывать на поверхность rus_verbs:выплыть{}, // выплыть на поверхность rus_verbs:выплюнуть{}, // выплюнуть на пол rus_verbs:выползать{}, // выползать на свежий воздух rus_verbs:выпроситься{}, // выпроситься на улицу rus_verbs:выпрыгивать{}, // выпрыгивать на свободу rus_verbs:выпрыгнуть{}, // выпрыгнуть на перрон rus_verbs:выпускать{}, // выпускать на свободу rus_verbs:выпустить{}, // выпустить на свободу rus_verbs:выпучивать{}, // выпучивать на кого-то глаза rus_verbs:выпучиваться{}, // глаза выпучиваются на кого-то rus_verbs:выпучить{}, // выпучить глаза на кого-то rus_verbs:выпучиться{}, // выпучиться на кого-то rus_verbs:выронить{}, // выронить на землю rus_verbs:высадить{}, // высадить на берег rus_verbs:высадиться{}, // высадиться на берег rus_verbs:высаживаться{}, // высаживаться на остров rus_verbs:выскальзывать{}, // выскальзывать на землю rus_verbs:выскочить{}, // выскочить на сцену rus_verbs:высморкаться{}, // высморкаться на землю rus_verbs:высморкнуться{}, // высморкнуться на землю rus_verbs:выставить{}, // выставить на всеобщее обозрение rus_verbs:выставиться{}, // выставиться на всеобщее обозрение rus_verbs:выставлять{}, // выставлять на всеобщее обозрение rus_verbs:выставляться{}, // выставляться на всеобщее обозрение инфинитив:высыпать{вид:соверш}, // высыпать на землю инфинитив:высыпать{вид:несоверш}, глагол:высыпать{вид:соверш}, глагол:высыпать{вид:несоверш}, деепричастие:высыпав{}, деепричастие:высыпая{}, прилагательное:высыпавший{вид:соверш}, //++прилагательное:высыпавший{вид:несоверш}, прилагательное:высыпающий{вид:несоверш}, rus_verbs:высыпаться{}, // высыпаться на землю rus_verbs:вытаращивать{}, // вытаращивать глаза на медведя rus_verbs:вытаращиваться{}, // вытаращиваться на медведя rus_verbs:вытаращить{}, // вытаращить глаза на медведя rus_verbs:вытаращиться{}, // вытаращиться на медведя rus_verbs:вытекать{}, // вытекать на землю rus_verbs:вытечь{}, // вытечь на землю rus_verbs:выучиваться{}, // выучиваться на кого-то rus_verbs:выучиться{}, // выучиться на кого-то rus_verbs:посмотреть{}, // посмотреть на экран rus_verbs:нашить{}, // нашить что-то на одежду rus_verbs:придти{}, // придти на помощь кому-то инфинитив:прийти{}, // прийти на помощь кому-то глагол:прийти{}, деепричастие:придя{}, // Придя на вокзал, он поспешно взял билеты. rus_verbs:поднять{}, // поднять на вершину rus_verbs:согласиться{}, // согласиться на ничью rus_verbs:послать{}, // послать на фронт rus_verbs:слать{}, // слать на фронт rus_verbs:надеяться{}, // надеяться на лучшее rus_verbs:крикнуть{}, // крикнуть на шалунов rus_verbs:пройти{}, // пройти на пляж rus_verbs:прислать{}, // прислать на экспертизу rus_verbs:жить{}, // жить на подачки rus_verbs:становиться{}, // становиться на ноги rus_verbs:наслать{}, // наслать на кого-то rus_verbs:принять{}, // принять на заметку rus_verbs:собираться{}, // собираться на экзамен rus_verbs:оставить{}, // оставить на всякий случай rus_verbs:звать{}, // звать на помощь rus_verbs:направиться{}, // направиться на прогулку rus_verbs:отвечать{}, // отвечать на звонки rus_verbs:отправиться{}, // отправиться на прогулку rus_verbs:поставить{}, // поставить на пол rus_verbs:обернуться{}, // обернуться на зов rus_verbs:отозваться{}, // отозваться на просьбу rus_verbs:закричать{}, // закричать на собаку rus_verbs:опустить{}, // опустить на землю rus_verbs:принести{}, // принести на пляж свой жезлонг rus_verbs:указать{}, // указать на дверь rus_verbs:ходить{}, // ходить на занятия rus_verbs:уставиться{}, // уставиться на листок rus_verbs:приходить{}, // приходить на экзамен rus_verbs:махнуть{}, // махнуть на пляж rus_verbs:явиться{}, // явиться на допрос rus_verbs:оглянуться{}, // оглянуться на дорогу rus_verbs:уехать{}, // уехать на заработки rus_verbs:повести{}, // повести на штурм rus_verbs:опуститься{}, // опуститься на колени //rus_verbs:передать{}, // передать на проверку rus_verbs:побежать{}, // побежать на занятия rus_verbs:прибыть{}, // прибыть на место службы rus_verbs:кричать{}, // кричать на медведя rus_verbs:стечь{}, // стечь на землю rus_verbs:обратить{}, // обратить на себя внимание rus_verbs:подать{}, // подать на пропитание rus_verbs:привести{}, // привести на съемки rus_verbs:испытывать{}, // испытывать на животных rus_verbs:перевести{}, // перевести на жену rus_verbs:купить{}, // купить на заемные деньги rus_verbs:собраться{}, // собраться на встречу rus_verbs:заглянуть{}, // заглянуть на огонёк rus_verbs:нажать{}, // нажать на рычаг rus_verbs:поспешить{}, // поспешить на праздник rus_verbs:перейти{}, // перейти на русский язык rus_verbs:поверить{}, // поверить на честное слово rus_verbs:глянуть{}, // глянуть на обложку rus_verbs:зайти{}, // зайти на огонёк rus_verbs:проходить{}, // проходить на сцену rus_verbs:глядеть{}, // глядеть на актрису //rus_verbs:решиться{}, // решиться на прыжок rus_verbs:пригласить{}, // пригласить на танец rus_verbs:позвать{}, // позвать на экзамен rus_verbs:усесться{}, // усесться на стул rus_verbs:поступить{}, // поступить на математический факультет rus_verbs:лечь{}, // лечь на живот rus_verbs:потянуться{}, // потянуться на юг rus_verbs:присесть{}, // присесть на корточки rus_verbs:наступить{}, // наступить на змею rus_verbs:заорать{}, // заорать на попрошаек rus_verbs:надеть{}, // надеть на голову rus_verbs:поглядеть{}, // поглядеть на девчонок rus_verbs:принимать{}, // принимать на гарантийное обслуживание rus_verbs:привезти{}, // привезти на испытания rus_verbs:рухнуть{}, // рухнуть на асфальт rus_verbs:пускать{}, // пускать на корм rus_verbs:отвести{}, // отвести на приём rus_verbs:отправить{}, // отправить на утилизацию rus_verbs:двигаться{}, // двигаться на восток rus_verbs:нести{}, // нести на пляж rus_verbs:падать{}, // падать на руки rus_verbs:откинуться{}, // откинуться на спинку кресла rus_verbs:рявкнуть{}, // рявкнуть на детей rus_verbs:получать{}, // получать на проживание rus_verbs:полезть{}, // полезть на рожон rus_verbs:направить{}, // направить на дообследование rus_verbs:приводить{}, // приводить на проверку rus_verbs:потребоваться{}, // потребоваться на замену rus_verbs:кинуться{}, // кинуться на нападавшего rus_verbs:учиться{}, // учиться на токаря rus_verbs:приподнять{}, // приподнять на один метр rus_verbs:налить{}, // налить на стол rus_verbs:играть{}, // играть на деньги rus_verbs:рассчитывать{}, // рассчитывать на подмогу rus_verbs:шепнуть{}, // шепнуть на ухо rus_verbs:швырнуть{}, // швырнуть на землю rus_verbs:прыгнуть{}, // прыгнуть на оленя rus_verbs:предлагать{}, // предлагать на выбор rus_verbs:садиться{}, // садиться на стул rus_verbs:лить{}, // лить на землю rus_verbs:испытать{}, // испытать на животных rus_verbs:фыркнуть{}, // фыркнуть на детеныша rus_verbs:годиться{}, // мясо годится на фарш rus_verbs:проверить{}, // проверить высказывание на истинность rus_verbs:откликнуться{}, // откликнуться на призывы rus_verbs:полагаться{}, // полагаться на интуицию rus_verbs:покоситься{}, // покоситься на соседа rus_verbs:повесить{}, // повесить на гвоздь инфинитив:походить{вид:соверш}, // походить на занятия глагол:походить{вид:соверш}, деепричастие:походив{}, прилагательное:походивший{}, rus_verbs:помчаться{}, // помчаться на экзамен rus_verbs:ставить{}, // ставить на контроль rus_verbs:свалиться{}, // свалиться на землю rus_verbs:валиться{}, // валиться на землю rus_verbs:подарить{}, // подарить на день рожденья rus_verbs:сбежать{}, // сбежать на необитаемый остров rus_verbs:стрелять{}, // стрелять на поражение rus_verbs:обращать{}, // обращать на себя внимание rus_verbs:наступать{}, // наступать на те же грабли rus_verbs:сбросить{}, // сбросить на землю rus_verbs:обидеться{}, // обидеться на друга rus_verbs:устроиться{}, // устроиться на стажировку rus_verbs:погрузиться{}, // погрузиться на большую глубину rus_verbs:течь{}, // течь на землю rus_verbs:отбросить{}, // отбросить на землю rus_verbs:метать{}, // метать на дно rus_verbs:пустить{}, // пустить на переплавку rus_verbs:прожить{}, // прожить на пособие rus_verbs:полететь{}, // полететь на континент rus_verbs:пропустить{}, // пропустить на сцену rus_verbs:указывать{}, // указывать на ошибку rus_verbs:наткнуться{}, // наткнуться на клад rus_verbs:рвануть{}, // рвануть на юг rus_verbs:ступать{}, // ступать на землю rus_verbs:спрыгнуть{}, // спрыгнуть на берег rus_verbs:заходить{}, // заходить на огонёк rus_verbs:нырнуть{}, // нырнуть на глубину rus_verbs:рвануться{}, // рвануться на свободу rus_verbs:натянуть{}, // натянуть на голову rus_verbs:забраться{}, // забраться на стол rus_verbs:помахать{}, // помахать на прощание rus_verbs:содержать{}, // содержать на спонсорскую помощь rus_verbs:приезжать{}, // приезжать на праздники rus_verbs:проникнуть{}, // проникнуть на территорию rus_verbs:подъехать{}, // подъехать на митинг rus_verbs:устремиться{}, // устремиться на волю rus_verbs:посадить{}, // посадить на стул rus_verbs:ринуться{}, // ринуться на голкипера rus_verbs:подвигнуть{}, // подвигнуть на подвиг rus_verbs:отдавать{}, // отдавать на перевоспитание rus_verbs:отложить{}, // отложить на черный день rus_verbs:убежать{}, // убежать на танцы rus_verbs:поднимать{}, // поднимать на верхний этаж rus_verbs:переходить{}, // переходить на цифровой сигнал rus_verbs:отослать{}, // отослать на переаттестацию rus_verbs:отодвинуть{}, // отодвинуть на другую половину стола rus_verbs:назначить{}, // назначить на должность rus_verbs:осесть{}, // осесть на дно rus_verbs:торопиться{}, // торопиться на экзамен rus_verbs:менять{}, // менять на еду rus_verbs:доставить{}, // доставить на шестой этаж rus_verbs:заслать{}, // заслать на проверку rus_verbs:дуть{}, // дуть на воду rus_verbs:сослать{}, // сослать на каторгу rus_verbs:останавливаться{}, // останавливаться на отдых rus_verbs:сдаваться{}, // сдаваться на милость победителя rus_verbs:сослаться{}, // сослаться на презумпцию невиновности rus_verbs:рассердиться{}, // рассердиться на дочь rus_verbs:кинуть{}, // кинуть на землю rus_verbs:расположиться{}, // расположиться на ночлег rus_verbs:осмелиться{}, // осмелиться на подлог rus_verbs:шептать{}, // шептать на ушко rus_verbs:уронить{}, // уронить на землю rus_verbs:откинуть{}, // откинуть на спинку кресла rus_verbs:перенести{}, // перенести на рабочий стол rus_verbs:сдаться{}, // сдаться на милость победителя rus_verbs:светить{}, // светить на дорогу rus_verbs:мчаться{}, // мчаться на бал rus_verbs:нестись{}, // нестись на свидание rus_verbs:поглядывать{}, // поглядывать на экран rus_verbs:орать{}, // орать на детей rus_verbs:уложить{}, // уложить на лопатки rus_verbs:решаться{}, // решаться на поступок rus_verbs:попадать{}, // попадать на карандаш rus_verbs:сплюнуть{}, // сплюнуть на землю rus_verbs:снимать{}, // снимать на телефон rus_verbs:опоздать{}, // опоздать на работу rus_verbs:посылать{}, // посылать на проверку rus_verbs:погнать{}, // погнать на пастбище rus_verbs:поступать{}, // поступать на кибернетический факультет rus_verbs:спускаться{}, // спускаться на уровень моря rus_verbs:усадить{}, // усадить на диван rus_verbs:проиграть{}, // проиграть на спор rus_verbs:прилететь{}, // прилететь на фестиваль rus_verbs:повалиться{}, // повалиться на спину rus_verbs:огрызнуться{}, // Собака огрызнулась на хозяина rus_verbs:задавать{}, // задавать на выходные rus_verbs:запасть{}, // запасть на девочку rus_verbs:лезть{}, // лезть на забор rus_verbs:потащить{}, // потащить на выборы rus_verbs:направляться{}, // направляться на экзамен rus_verbs:определять{}, // определять на вкус rus_verbs:поползти{}, // поползти на стену rus_verbs:поплыть{}, // поплыть на берег rus_verbs:залезть{}, // залезть на яблоню rus_verbs:сдать{}, // сдать на мясокомбинат rus_verbs:приземлиться{}, // приземлиться на дорогу rus_verbs:лаять{}, // лаять на прохожих rus_verbs:перевернуть{}, // перевернуть на бок rus_verbs:ловить{}, // ловить на живца rus_verbs:отнести{}, // отнести животное на хирургический стол rus_verbs:плюнуть{}, // плюнуть на условности rus_verbs:передавать{}, // передавать на проверку rus_verbs:нанять{}, // Босс нанял на работу еще несколько человек rus_verbs:разозлиться{}, // Папа разозлился на сына из-за плохих оценок по математике инфинитив:рассыпаться{вид:несоверш}, // рассыпаться на мелкие детали инфинитив:рассыпаться{вид:соверш}, глагол:рассыпаться{вид:несоверш}, глагол:рассыпаться{вид:соверш}, деепричастие:рассыпавшись{}, деепричастие:рассыпаясь{}, прилагательное:рассыпавшийся{вид:несоверш}, прилагательное:рассыпавшийся{вид:соверш}, прилагательное:рассыпающийся{}, rus_verbs:зарычать{}, // Медведица зарычала на медвежонка rus_verbs:призвать{}, // призвать на сборы rus_verbs:увезти{}, // увезти на дачу rus_verbs:содержаться{}, // содержаться на пожертвования rus_verbs:навести{}, // навести на скопление телескоп rus_verbs:отправляться{}, // отправляться на утилизацию rus_verbs:улечься{}, // улечься на животик rus_verbs:налететь{}, // налететь на препятствие rus_verbs:перевернуться{}, // перевернуться на спину rus_verbs:улететь{}, // улететь на родину rus_verbs:ложиться{}, // ложиться на бок rus_verbs:класть{}, // класть на место rus_verbs:отреагировать{}, // отреагировать на выступление rus_verbs:доставлять{}, // доставлять на дом rus_verbs:отнять{}, // отнять на благо правящей верхушки rus_verbs:ступить{}, // ступить на землю rus_verbs:сводить{}, // сводить на концерт знаменитой рок-группы rus_verbs:унести{}, // унести на работу rus_verbs:сходить{}, // сходить на концерт rus_verbs:потратить{}, // потратить на корм и наполнитель для туалета все деньги rus_verbs:соскочить{}, // соскочить на землю rus_verbs:пожаловаться{}, // пожаловаться на соседей rus_verbs:тащить{}, // тащить на замену rus_verbs:замахать{}, // замахать руками на паренька rus_verbs:заглядывать{}, // заглядывать на обед rus_verbs:соглашаться{}, // соглашаться на равный обмен rus_verbs:плюхнуться{}, // плюхнуться на мягкий пуфик rus_verbs:увести{}, // увести на осмотр rus_verbs:успевать{}, // успевать на контрольную работу rus_verbs:опрокинуть{}, // опрокинуть на себя rus_verbs:подавать{}, // подавать на апелляцию rus_verbs:прибежать{}, // прибежать на вокзал rus_verbs:отшвырнуть{}, // отшвырнуть на замлю rus_verbs:привлекать{}, // привлекать на свою сторону rus_verbs:опереться{}, // опереться на палку rus_verbs:перебраться{}, // перебраться на маленький островок rus_verbs:уговорить{}, // уговорить на новые траты rus_verbs:гулять{}, // гулять на спонсорские деньги rus_verbs:переводить{}, // переводить на другой путь rus_verbs:заколебаться{}, // заколебаться на один миг rus_verbs:зашептать{}, // зашептать на ушко rus_verbs:привстать{}, // привстать на цыпочки rus_verbs:хлынуть{}, // хлынуть на берег rus_verbs:наброситься{}, // наброситься на еду rus_verbs:напасть{}, // повстанцы, напавшие на конвой rus_verbs:убрать{}, // книга, убранная на полку rus_verbs:попасть{}, // путешественники, попавшие на ничейную территорию rus_verbs:засматриваться{}, // засматриваться на девчонок rus_verbs:застегнуться{}, // застегнуться на все пуговицы rus_verbs:провериться{}, // провериться на заболевания rus_verbs:проверяться{}, // проверяться на заболевания rus_verbs:тестировать{}, // тестировать на профпригодность rus_verbs:протестировать{}, // протестировать на профпригодность rus_verbs:уходить{}, // отец, уходящий на работу rus_verbs:налипнуть{}, // снег, налипший на провода rus_verbs:налипать{}, // снег, налипающий на провода rus_verbs:улетать{}, // Многие птицы улетают осенью на юг. rus_verbs:поехать{}, // она поехала на встречу с заказчиком rus_verbs:переключать{}, // переключать на резервную линию rus_verbs:переключаться{}, // переключаться на резервную линию rus_verbs:подписаться{}, // подписаться на обновление rus_verbs:нанести{}, // нанести на кожу rus_verbs:нарываться{}, // нарываться на неприятности rus_verbs:выводить{}, // выводить на орбиту rus_verbs:вернуться{}, // вернуться на родину rus_verbs:возвращаться{}, // возвращаться на родину прилагательное:падкий{}, // Он падок на деньги. прилагательное:обиженный{}, // Он обижен на отца. rus_verbs:косить{}, // Он косит на оба глаза. rus_verbs:закрыть{}, // Он забыл закрыть дверь на замок. прилагательное:готовый{}, // Он готов на всякие жертвы. rus_verbs:говорить{}, // Он говорит на скользкую тему. прилагательное:глухой{}, // Он глух на одно ухо. rus_verbs:взять{}, // Он взял ребёнка себе на колени. rus_verbs:оказывать{}, // Лекарство не оказывало на него никакого действия. rus_verbs:вести{}, // Лестница ведёт на третий этаж. rus_verbs:уполномочивать{}, // уполномочивать на что-либо глагол:спешить{ вид:несоверш }, // Я спешу на поезд. rus_verbs:брать{}, // Я беру всю ответственность на себя. rus_verbs:произвести{}, // Это произвело на меня глубокое впечатление. rus_verbs:употребить{}, // Эти деньги можно употребить на ремонт фабрики. rus_verbs:наводить{}, // Эта песня наводит на меня сон и скуку. rus_verbs:разбираться{}, // Эта машина разбирается на части. rus_verbs:оказать{}, // Эта книга оказала на меня большое влияние. rus_verbs:разбить{}, // Учитель разбил учеников на несколько групп. rus_verbs:отразиться{}, // Усиленная работа отразилась на его здоровье. rus_verbs:перегрузить{}, // Уголь надо перегрузить на другое судно. rus_verbs:делиться{}, // Тридцать делится на пять без остатка. rus_verbs:удаляться{}, // Суд удаляется на совещание. rus_verbs:показывать{}, // Стрелка компаса всегда показывает на север. rus_verbs:сохранить{}, // Сохраните это на память обо мне. rus_verbs:уезжать{}, // Сейчас все студенты уезжают на экскурсию. rus_verbs:лететь{}, // Самолёт летит на север. rus_verbs:бить{}, // Ружьё бьёт на пятьсот метров. // rus_verbs:прийтись{}, // Пятое число пришлось на субботу. rus_verbs:вынести{}, // Они вынесли из лодки на берег все вещи. rus_verbs:смотреть{}, // Она смотрит на нас из окна. rus_verbs:отдать{}, // Она отдала мне деньги на сохранение. rus_verbs:налюбоваться{}, // Не могу налюбоваться на картину. rus_verbs:любоваться{}, // гости любовались на картину rus_verbs:попробовать{}, // Дайте мне попробовать на ощупь. прилагательное:действительный{}, // Прививка оспы действительна только на три года. rus_verbs:спуститься{}, // На город спустился смог прилагательное:нечистый{}, // Он нечист на руку. прилагательное:неспособный{}, // Он неспособен на такую низость. прилагательное:злой{}, // кот очень зол на хозяина rus_verbs:пойти{}, // Девочка не пошла на урок физультуры rus_verbs:прибывать{}, // мой поезд прибывает на первый путь rus_verbs:застегиваться{}, // пальто застегивается на двадцать одну пуговицу rus_verbs:идти{}, // Дело идёт на лад. rus_verbs:лазить{}, // Он лазил на чердак. rus_verbs:поддаваться{}, // Он легко поддаётся на уговоры. // rus_verbs:действовать{}, // действующий на нервы rus_verbs:выходить{}, // Балкон выходит на площадь. rus_verbs:работать{}, // Время работает на нас. глагол:написать{aux stress="напис^ать"}, // Он написал музыку на слова Пушкина. rus_verbs:бросить{}, // Они бросили все силы на строительство. // глагол:разрезать{aux stress="разр^езать"}, глагол:разрезать{aux stress="разрез^ать"}, // Она разрезала пирог на шесть кусков. rus_verbs:броситься{}, // Она радостно бросилась мне на шею. rus_verbs:оправдать{}, // Она оправдала неявку на занятия болезнью. rus_verbs:ответить{}, // Она не ответила на мой поклон. rus_verbs:нашивать{}, // Она нашивала заплату на локоть. rus_verbs:молиться{}, // Она молится на свою мать. rus_verbs:запереть{}, // Она заперла дверь на замок. rus_verbs:заявить{}, // Она заявила свои права на наследство. rus_verbs:уйти{}, // Все деньги ушли на путешествие. rus_verbs:вступить{}, // Водолаз вступил на берег. rus_verbs:сойти{}, // Ночь сошла на землю. rus_verbs:приехать{}, // Мы приехали на вокзал слишком рано. rus_verbs:рыдать{}, // Не рыдай так безумно над ним. rus_verbs:подписать{}, // Не забудьте подписать меня на газету. rus_verbs:держать{}, // Наш пароход держал курс прямо на север. rus_verbs:свезти{}, // На выставку свезли экспонаты со всего мира. rus_verbs:ехать{}, // Мы сейчас едем на завод. rus_verbs:выбросить{}, // Волнами лодку выбросило на берег. ГЛ_ИНФ(сесть), // сесть на снег ГЛ_ИНФ(записаться), ГЛ_ИНФ(положить) // положи книгу на стол } #endregion VerbList // Чтобы разрешить связывание в паттернах типа: залить на youtube fact гл_предл { if context { Гл_НА_Вин предлог:на{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { глагол:купить{} предлог:на{} 'деньги'{падеж:вин} } then return true } fact гл_предл { if context { Гл_НА_Вин предлог:на{} *:*{ падеж:вин } } then return true } // смещаться на несколько миллиметров fact гл_предл { if context { Гл_НА_Вин предлог:на{} наречие:*{} } then return true } // партия взяла на себя нереалистичные обязательства fact гл_предл { if context { глагол:взять{} предлог:на{} 'себя'{падеж:вин} } then return true } #endregion ВИНИТЕЛЬНЫЙ // Все остальные варианты с предлогом 'НА' по умолчанию запрещаем. fact гл_предл { if context { * предлог:на{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:на{} *:*{ падеж:мест } } then return false,-3 } fact гл_предл { if context { * предлог:на{} *:*{ падеж:вин } } then return false,-4 } // Этот вариант нужен для обработки конструкций с числительными: // Президентские выборы разделили Венесуэлу на два непримиримых лагеря fact гл_предл { if context { * предлог:на{} *:*{ падеж:род } } then return false,-4 } // Продавать на eBay fact гл_предл { if context { * предлог:на{} * } then return false,-6 } #endregion Предлог_НА #region Предлог_С // ------------- ПРЕДЛОГ 'С' ----------------- // У этого предлога предпочтительная семантика привязывает его обычно к существительному. // Поэтому запрещаем по умолчанию его привязку к глаголам, а разрешенные глаголы перечислим. #region ТВОРИТЕЛЬНЫЙ wordentry_set Гл_С_Твор={ rus_verbs:помогать{}, // будет готов помогать врачам в онкологическом центре с постановкой верных диагнозов rus_verbs:перепихнуться{}, // неужели ты не хочешь со мной перепихнуться rus_verbs:забраться{}, rus_verbs:ДРАТЬСЯ{}, // Мои же собственные ратники забросали бы меня гнилой капустой, и мне пришлось бы драться с каждым рыцарем в стране, чтобы доказать свою смелость. (ДРАТЬСЯ/БИТЬСЯ/ПОДРАТЬСЯ) rus_verbs:БИТЬСЯ{}, // rus_verbs:ПОДРАТЬСЯ{}, // прилагательное:СХОЖИЙ{}, // Не был ли он схожим с одним из живых языков Земли (СХОЖИЙ) rus_verbs:ВСТУПИТЬ{}, // Он намеревался вступить с Вольфом в ближний бой. (ВСТУПИТЬ) rus_verbs:КОРРЕЛИРОВАТЬ{}, // Это коррелирует с традиционно сильными направлениями московской математической школы. (КОРРЕЛИРОВАТЬ) rus_verbs:УВИДЕТЬСЯ{}, // Он проигнорирует истерические протесты жены и увидится сначала с доктором, а затем с психотерапевтом (УВИДЕТЬСЯ) rus_verbs:ОЧНУТЬСЯ{}, // Когда он очнулся с болью в левой стороне черепа, у него возникло пугающее ощущение. (ОЧНУТЬСЯ) прилагательное:сходный{}, // Мозг этих существ сходен по размерам с мозгом динозавра rus_verbs:накрыться{}, // Было холодно, и он накрылся с головой одеялом. rus_verbs:РАСПРЕДЕЛИТЬ{}, // Бюджет распределят с участием горожан (РАСПРЕДЕЛИТЬ) rus_verbs:НАБРОСИТЬСЯ{}, // Пьяный водитель набросился с ножом на сотрудников ГИБДД (НАБРОСИТЬСЯ) rus_verbs:БРОСИТЬСЯ{}, // она со смехом бросилась прочь (БРОСИТЬСЯ) rus_verbs:КОНТАКТИРОВАТЬ{}, // Электронным магазинам стоит контактировать с клиентами (КОНТАКТИРОВАТЬ) rus_verbs:ВИДЕТЬСЯ{}, // Тогда мы редко виделись друг с другом rus_verbs:сесть{}, // сел в него с дорожной сумкой , наполненной наркотиками rus_verbs:купить{}, // Мы купили с ним одну и ту же книгу rus_verbs:ПРИМЕНЯТЬ{}, // Меры по стимулированию спроса в РФ следует применять с осторожностью (ПРИМЕНЯТЬ) rus_verbs:УЙТИ{}, // ты мог бы уйти со мной (УЙТИ) rus_verbs:ЖДАТЬ{}, // С нарастающим любопытством ждем результатов аудита золотых хранилищ европейских и американских центробанков (ЖДАТЬ) rus_verbs:ГОСПИТАЛИЗИРОВАТЬ{}, // Мэра Твери, участвовавшего в спартакиаде, госпитализировали с инфарктом (ГОСПИТАЛИЗИРОВАТЬ) rus_verbs:ЗАХЛОПНУТЬСЯ{}, // она захлопнулась со звоном (ЗАХЛОПНУТЬСЯ) rus_verbs:ОТВЕРНУТЬСЯ{}, // она со вздохом отвернулась (ОТВЕРНУТЬСЯ) rus_verbs:отправить{}, // вы можете отправить со мной человека rus_verbs:выступать{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам rus_verbs:ВЫЕЗЖАТЬ{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку (ВЫЕЗЖАТЬ С твор) rus_verbs:ПОКОНЧИТЬ{}, // со всем этим покончено (ПОКОНЧИТЬ С) rus_verbs:ПОБЕЖАТЬ{}, // Дмитрий побежал со всеми (ПОБЕЖАТЬ С) прилагательное:несовместимый{}, // характер ранений был несовместим с жизнью (НЕСОВМЕСТИМЫЙ С) rus_verbs:ПОСЕТИТЬ{}, // Его кабинет местные тележурналисты посетили со скрытой камерой (ПОСЕТИТЬ С) rus_verbs:СЛОЖИТЬСЯ{}, // сами банки принимают меры по урегулированию сложившейся с вкладчиками ситуации (СЛОЖИТЬСЯ С) rus_verbs:ЗАСТАТЬ{}, // Молодой человек убил пенсионера , застав его в постели с женой (ЗАСТАТЬ С) rus_verbs:ОЗНАКАМЛИВАТЬСЯ{}, // при заполнении заявления владельцы судов ознакамливаются с режимом (ОЗНАКАМЛИВАТЬСЯ С) rus_verbs:СООБРАЗОВЫВАТЬ{}, // И все свои задачи мы сообразовываем с этим пониманием (СООБРАЗОВЫВАТЬ С) rus_verbs:СВЫКАТЬСЯ{}, rus_verbs:стаскиваться{}, rus_verbs:спиливаться{}, rus_verbs:КОНКУРИРОВАТЬ{}, // Бедные и менее развитые страны не могут конкурировать с этими субсидиями (КОНКУРИРОВАТЬ С) rus_verbs:ВЫРВАТЬСЯ{}, // тот с трудом вырвался (ВЫРВАТЬСЯ С твор) rus_verbs:СОБРАТЬСЯ{}, // нужно собраться с силами (СОБРАТЬСЯ С) rus_verbs:УДАВАТЬСЯ{}, // удавалось это с трудом (УДАВАТЬСЯ С) rus_verbs:РАСПАХНУТЬСЯ{}, // дверь с треском распахнулась (РАСПАХНУТЬСЯ С) rus_verbs:НАБЛЮДАТЬ{}, // Олег наблюдал с любопытством (НАБЛЮДАТЬ С) rus_verbs:ПОТЯНУТЬ{}, // затем с силой потянул (ПОТЯНУТЬ С) rus_verbs:КИВНУТЬ{}, // Питер с трудом кивнул (КИВНУТЬ С) rus_verbs:СГЛОТНУТЬ{}, // Борис с трудом сглотнул (СГЛОТНУТЬ С) rus_verbs:ЗАБРАТЬ{}, // забрать его с собой (ЗАБРАТЬ С) rus_verbs:ОТКРЫТЬСЯ{}, // дверь с шипением открылась (ОТКРЫТЬСЯ С) rus_verbs:ОТОРВАТЬ{}, // с усилием оторвал взгляд (ОТОРВАТЬ С твор) rus_verbs:ОГЛЯДЕТЬСЯ{}, // Рома с любопытством огляделся (ОГЛЯДЕТЬСЯ С) rus_verbs:ФЫРКНУТЬ{}, // турок фыркнул с отвращением (ФЫРКНУТЬ С) rus_verbs:согласиться{}, // с этим согласились все (согласиться с) rus_verbs:ПОСЫПАТЬСЯ{}, // с грохотом посыпались камни (ПОСЫПАТЬСЯ С твор) rus_verbs:ВЗДОХНУТЬ{}, // Алиса вздохнула с облегчением (ВЗДОХНУТЬ С) rus_verbs:ОБЕРНУТЬСЯ{}, // та с удивлением обернулась (ОБЕРНУТЬСЯ С) rus_verbs:ХМЫКНУТЬ{}, // Алексей хмыкнул с сомнением (ХМЫКНУТЬ С твор) rus_verbs:ВЫЕХАТЬ{}, // они выехали с рассветом (ВЫЕХАТЬ С твор) rus_verbs:ВЫДОХНУТЬ{}, // Владимир выдохнул с облегчением (ВЫДОХНУТЬ С) rus_verbs:УХМЫЛЬНУТЬСЯ{}, // Кеша ухмыльнулся с сомнением (УХМЫЛЬНУТЬСЯ С) rus_verbs:НЕСТИСЬ{}, // тот несся с криком (НЕСТИСЬ С твор) rus_verbs:ПАДАТЬ{}, // падают с глухим стуком (ПАДАТЬ С твор) rus_verbs:ТВОРИТЬСЯ{}, // странное творилось с глазами (ТВОРИТЬСЯ С твор) rus_verbs:УХОДИТЬ{}, // с ними уходили эльфы (УХОДИТЬ С твор) rus_verbs:СКАКАТЬ{}, // скакали тут с топорами (СКАКАТЬ С твор) rus_verbs:ЕСТЬ{}, // здесь едят с зеленью (ЕСТЬ С твор) rus_verbs:ПОЯВИТЬСЯ{}, // с рассветом появились птицы (ПОЯВИТЬСЯ С твор) rus_verbs:ВСКОЧИТЬ{}, // Олег вскочил с готовностью (ВСКОЧИТЬ С твор) rus_verbs:БЫТЬ{}, // хочу быть с тобой (БЫТЬ С твор) rus_verbs:ПОКАЧАТЬ{}, // с сомнением покачал головой. (ПОКАЧАТЬ С СОМНЕНИЕМ) rus_verbs:ВЫРУГАТЬСЯ{}, // капитан с чувством выругался (ВЫРУГАТЬСЯ С ЧУВСТВОМ) rus_verbs:ОТКРЫТЬ{}, // с трудом открыл глаза (ОТКРЫТЬ С ТРУДОМ, таких много) rus_verbs:ПОЛУЧИТЬСЯ{}, // забавно получилось с ним (ПОЛУЧИТЬСЯ С) rus_verbs:ВЫБЕЖАТЬ{}, // старый выбежал с копьем (ВЫБЕЖАТЬ С) rus_verbs:ГОТОВИТЬСЯ{}, // Большинство компотов готовится с использованием сахара (ГОТОВИТЬСЯ С) rus_verbs:ПОДИСКУТИРОВАТЬ{}, // я бы подискутировал с Андрюхой (ПОДИСКУТИРОВАТЬ С) rus_verbs:ТУСИТЬ{}, // кто тусил со Светкой (ТУСИТЬ С) rus_verbs:БЕЖАТЬ{}, // куда она бежит со всеми? (БЕЖАТЬ С твор) rus_verbs:ГОРЕТЬ{}, // ты горел со своим кораблем? (ГОРЕТЬ С) rus_verbs:ВЫПИТЬ{}, // хотите выпить со мной чаю? (ВЫПИТЬ С) rus_verbs:МЕНЯТЬСЯ{}, // Я меняюсь с товарищем книгами. (МЕНЯТЬСЯ С) rus_verbs:ВАЛЯТЬСЯ{}, // Он уже неделю валяется с гриппом. (ВАЛЯТЬСЯ С) rus_verbs:ПИТЬ{}, // вы даже будете пить со мной пиво. (ПИТЬ С) инфинитив:кристаллизоваться{ вид:соверш }, // После этого пересыщенный раствор кристаллизуется с образованием кристаллов сахара. инфинитив:кристаллизоваться{ вид:несоверш }, глагол:кристаллизоваться{ вид:соверш }, глагол:кристаллизоваться{ вид:несоверш }, rus_verbs:ПООБЩАТЬСЯ{}, // пообщайся с Борисом (ПООБЩАТЬСЯ С) rus_verbs:ОБМЕНЯТЬСЯ{}, // Миша обменялся с Петей марками (ОБМЕНЯТЬСЯ С) rus_verbs:ПРОХОДИТЬ{}, // мы с тобой сегодня весь день проходили с вещами. (ПРОХОДИТЬ С) rus_verbs:ВСТАТЬ{}, // Он занимался всю ночь и встал с головной болью. (ВСТАТЬ С) rus_verbs:ПОВРЕМЕНИТЬ{}, // МВФ рекомендует Ирландии повременить с мерами экономии (ПОВРЕМЕНИТЬ С) rus_verbs:ГЛЯДЕТЬ{}, // Её глаза глядели с мягкой грустью. (ГЛЯДЕТЬ С + твор) rus_verbs:ВЫСКОЧИТЬ{}, // Зачем ты выскочил со своим замечанием? (ВЫСКОЧИТЬ С) rus_verbs:НЕСТИ{}, // плот несло со страшной силой. (НЕСТИ С) rus_verbs:приближаться{}, // стена приближалась со страшной быстротой. (приближаться с) rus_verbs:заниматься{}, // После уроков я занимался с отстающими учениками. (заниматься с) rus_verbs:разработать{}, // Этот лекарственный препарат разработан с использованием рецептов традиционной китайской медицины. (разработать с) rus_verbs:вестись{}, // Разработка месторождения ведется с использованием большого количества техники. (вестись с) rus_verbs:конфликтовать{}, // Маша конфликтует с Петей (конфликтовать с) rus_verbs:мешать{}, // мешать воду с мукой (мешать с) rus_verbs:иметь{}, // мне уже приходилось несколько раз иметь с ним дело. rus_verbs:синхронизировать{}, // синхронизировать с эталонным генератором rus_verbs:засинхронизировать{}, // засинхронизировать с эталонным генератором rus_verbs:синхронизироваться{}, // синхронизироваться с эталонным генератором rus_verbs:засинхронизироваться{}, // засинхронизироваться с эталонным генератором rus_verbs:стирать{}, // стирать с мылом рубашку в тазу rus_verbs:прыгать{}, // парашютист прыгает с парашютом rus_verbs:выступить{}, // Он выступил с приветствием съезду. rus_verbs:ходить{}, // В чужой монастырь со своим уставом не ходят. rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой. rus_verbs:отзываться{}, // Он отзывается об этой книге с большой похвалой. rus_verbs:вставать{}, // он встаёт с зарёй rus_verbs:мирить{}, // Его ум мирил всех с его дурным характером. rus_verbs:продолжаться{}, // стрельба тем временем продолжалась с прежней точностью. rus_verbs:договориться{}, // мы договоримся с вами rus_verbs:побыть{}, // он хотел побыть с тобой rus_verbs:расти{}, // Мировые производственные мощности растут с беспрецедентной скоростью rus_verbs:вязаться{}, // вязаться с фактами rus_verbs:отнестись{}, // отнестись к животным с сочуствием rus_verbs:относиться{}, // относиться с пониманием rus_verbs:пойти{}, // Спектакль пойдёт с участием известных артистов. rus_verbs:бракосочетаться{}, // Потомственный кузнец бракосочетался с разорившейся графиней rus_verbs:гулять{}, // бабушка гуляет с внуком rus_verbs:разбираться{}, // разбираться с задачей rus_verbs:сверить{}, // Данные были сверены с эталонными значениями rus_verbs:делать{}, // Что делать со старым телефоном rus_verbs:осматривать{}, // осматривать с удивлением rus_verbs:обсудить{}, // обсудить с приятелем прохождение уровня в новой игре rus_verbs:попрощаться{}, // попрощаться с талантливым актером rus_verbs:задремать{}, // задремать с кружкой чая в руке rus_verbs:связать{}, // связать катастрофу с действиями конкурентов rus_verbs:носиться{}, // носиться с безумной идеей rus_verbs:кончать{}, // кончать с собой rus_verbs:обмениваться{}, // обмениваться с собеседниками rus_verbs:переговариваться{}, // переговариваться с маяком rus_verbs:общаться{}, // общаться с полицией rus_verbs:завершить{}, // завершить с ошибкой rus_verbs:обняться{}, // обняться с подругой rus_verbs:сливаться{}, // сливаться с фоном rus_verbs:смешаться{}, // смешаться с толпой rus_verbs:договариваться{}, // договариваться с потерпевшим rus_verbs:обедать{}, // обедать с гостями rus_verbs:сообщаться{}, // сообщаться с подземной рекой rus_verbs:сталкиваться{}, // сталкиваться со стаей птиц rus_verbs:читаться{}, // читаться с трудом rus_verbs:смириться{}, // смириться с утратой rus_verbs:разделить{}, // разделить с другими ответственность rus_verbs:роднить{}, // роднить с медведем rus_verbs:медлить{}, // медлить с ответом rus_verbs:скрестить{}, // скрестить с ужом rus_verbs:покоиться{}, // покоиться с миром rus_verbs:делиться{}, // делиться с друзьями rus_verbs:познакомить{}, // познакомить с Олей rus_verbs:порвать{}, // порвать с Олей rus_verbs:завязать{}, // завязать с Олей знакомство rus_verbs:суетиться{}, // суетиться с изданием романа rus_verbs:соединиться{}, // соединиться с сервером rus_verbs:справляться{}, // справляться с нуждой rus_verbs:замешкаться{}, // замешкаться с ответом rus_verbs:поссориться{}, // поссориться с подругой rus_verbs:ссориться{}, // ссориться с друзьями rus_verbs:торопить{}, // торопить с решением rus_verbs:поздравить{}, // поздравить с победой rus_verbs:проститься{}, // проститься с человеком rus_verbs:поработать{}, // поработать с деревом rus_verbs:приключиться{}, // приключиться с Колей rus_verbs:сговориться{}, // сговориться с Ваней rus_verbs:отъехать{}, // отъехать с ревом rus_verbs:объединять{}, // объединять с другой кампанией rus_verbs:употребить{}, // употребить с молоком rus_verbs:перепутать{}, // перепутать с другой книгой rus_verbs:запоздать{}, // запоздать с ответом rus_verbs:подружиться{}, // подружиться с другими детьми rus_verbs:дружить{}, // дружить с Сережей rus_verbs:поравняться{}, // поравняться с финишной чертой rus_verbs:ужинать{}, // ужинать с гостями rus_verbs:расставаться{}, // расставаться с приятелями rus_verbs:завтракать{}, // завтракать с семьей rus_verbs:объединиться{}, // объединиться с соседями rus_verbs:сменяться{}, // сменяться с напарником rus_verbs:соединить{}, // соединить с сетью rus_verbs:разговориться{}, // разговориться с охранником rus_verbs:преподнести{}, // преподнести с помпой rus_verbs:напечатать{}, // напечатать с картинками rus_verbs:соединять{}, // соединять с сетью rus_verbs:расправиться{}, // расправиться с беззащитным человеком rus_verbs:распрощаться{}, // распрощаться с деньгами rus_verbs:сравнить{}, // сравнить с конкурентами rus_verbs:ознакомиться{}, // ознакомиться с выступлением инфинитив:сочетаться{ вид:несоверш }, глагол:сочетаться{ вид:несоверш }, // сочетаться с сумочкой деепричастие:сочетаясь{}, прилагательное:сочетающийся{}, прилагательное:сочетавшийся{}, rus_verbs:изнасиловать{}, // изнасиловать с применением чрезвычайного насилия rus_verbs:прощаться{}, // прощаться с боевым товарищем rus_verbs:сравнивать{}, // сравнивать с конкурентами rus_verbs:складывать{}, // складывать с весом упаковки rus_verbs:повестись{}, // повестись с ворами rus_verbs:столкнуть{}, // столкнуть с отбойником rus_verbs:переглядываться{}, // переглядываться с соседом rus_verbs:поторопить{}, // поторопить с откликом rus_verbs:развлекаться{}, // развлекаться с подружками rus_verbs:заговаривать{}, // заговаривать с незнакомцами rus_verbs:поцеловаться{}, // поцеловаться с первой девушкой инфинитив:согласоваться{ вид:несоверш }, глагол:согласоваться{ вид:несоверш }, // согласоваться с подлежащим деепричастие:согласуясь{}, прилагательное:согласующийся{}, rus_verbs:совпасть{}, // совпасть с оригиналом rus_verbs:соединяться{}, // соединяться с куратором rus_verbs:повстречаться{}, // повстречаться с героями rus_verbs:поужинать{}, // поужинать с родителями rus_verbs:развестись{}, // развестись с первым мужем rus_verbs:переговорить{}, // переговорить с коллегами rus_verbs:сцепиться{}, // сцепиться с бродячей собакой rus_verbs:сожрать{}, // сожрать с потрохами rus_verbs:побеседовать{}, // побеседовать со шпаной rus_verbs:поиграть{}, // поиграть с котятами rus_verbs:сцепить{}, // сцепить с тягачом rus_verbs:помириться{}, // помириться с подружкой rus_verbs:связываться{}, // связываться с бандитами rus_verbs:совещаться{}, // совещаться с мастерами rus_verbs:обрушиваться{}, // обрушиваться с беспощадной критикой rus_verbs:переплестись{}, // переплестись с кустами rus_verbs:мутить{}, // мутить с одногрупницами rus_verbs:приглядываться{}, // приглядываться с интересом rus_verbs:сблизиться{}, // сблизиться с врагами rus_verbs:перешептываться{}, // перешептываться с симпатичной соседкой rus_verbs:растереть{}, // растереть с солью rus_verbs:смешиваться{}, // смешиваться с известью rus_verbs:соприкоснуться{}, // соприкоснуться с тайной rus_verbs:ладить{}, // ладить с родственниками rus_verbs:сотрудничать{}, // сотрудничать с органами дознания rus_verbs:съехаться{}, // съехаться с родственниками rus_verbs:перекинуться{}, // перекинуться с коллегами парой слов rus_verbs:советоваться{}, // советоваться с отчимом rus_verbs:сравниться{}, // сравниться с лучшими rus_verbs:знакомиться{}, // знакомиться с абитуриентами rus_verbs:нырять{}, // нырять с аквалангом rus_verbs:забавляться{}, // забавляться с куклой rus_verbs:перекликаться{}, // перекликаться с другой статьей rus_verbs:тренироваться{}, // тренироваться с партнершей rus_verbs:поспорить{}, // поспорить с казночеем инфинитив:сладить{ вид:соверш }, глагол:сладить{ вид:соверш }, // сладить с бычком деепричастие:сладив{}, прилагательное:сладивший{ вид:соверш }, rus_verbs:примириться{}, // примириться с утратой rus_verbs:раскланяться{}, // раскланяться с фрейлинами rus_verbs:слечь{}, // слечь с ангиной rus_verbs:соприкасаться{}, // соприкасаться со стеной rus_verbs:смешать{}, // смешать с грязью rus_verbs:пересекаться{}, // пересекаться с трассой rus_verbs:путать{}, // путать с государственной шерстью rus_verbs:поболтать{}, // поболтать с ученицами rus_verbs:здороваться{}, // здороваться с профессором rus_verbs:просчитаться{}, // просчитаться с покупкой rus_verbs:сторожить{}, // сторожить с собакой rus_verbs:обыскивать{}, // обыскивать с собаками rus_verbs:переплетаться{}, // переплетаться с другой веткой rus_verbs:обниматься{}, // обниматься с Ксюшей rus_verbs:объединяться{}, // объединяться с конкурентами rus_verbs:погорячиться{}, // погорячиться с покупкой rus_verbs:мыться{}, // мыться с мылом rus_verbs:свериться{}, // свериться с эталоном rus_verbs:разделаться{}, // разделаться с кем-то rus_verbs:чередоваться{}, // чередоваться с партнером rus_verbs:налететь{}, // налететь с соратниками rus_verbs:поспать{}, // поспать с включенным светом rus_verbs:управиться{}, // управиться с собакой rus_verbs:согрешить{}, // согрешить с замужней rus_verbs:определиться{}, // определиться с победителем rus_verbs:перемешаться{}, // перемешаться с гранулами rus_verbs:затрудняться{}, // затрудняться с ответом rus_verbs:обождать{}, // обождать со стартом rus_verbs:фыркать{}, // фыркать с презрением rus_verbs:засидеться{}, // засидеться с приятелем rus_verbs:крепнуть{}, // крепнуть с годами rus_verbs:пировать{}, // пировать с дружиной rus_verbs:щебетать{}, // щебетать с сестричками rus_verbs:маяться{}, // маяться с кашлем rus_verbs:сближать{}, // сближать с центральным светилом rus_verbs:меркнуть{}, // меркнуть с возрастом rus_verbs:заспорить{}, // заспорить с оппонентами rus_verbs:граничить{}, // граничить с Ливаном rus_verbs:перестараться{}, // перестараться со стимуляторами rus_verbs:объединить{}, // объединить с филиалом rus_verbs:свыкнуться{}, // свыкнуться с утратой rus_verbs:посоветоваться{}, // посоветоваться с адвокатами rus_verbs:напутать{}, // напутать с ведомостями rus_verbs:нагрянуть{}, // нагрянуть с обыском rus_verbs:посовещаться{}, // посовещаться с судьей rus_verbs:провернуть{}, // провернуть с друганом rus_verbs:разделяться{}, // разделяться с сотрапезниками rus_verbs:пересечься{}, // пересечься с второй колонной rus_verbs:опережать{}, // опережать с большим запасом rus_verbs:перепутаться{}, // перепутаться с другой линией rus_verbs:соотноситься{}, // соотноситься с затратами rus_verbs:смешивать{}, // смешивать с золой rus_verbs:свидеться{}, // свидеться с тобой rus_verbs:переспать{}, // переспать с графиней rus_verbs:поладить{}, // поладить с соседями rus_verbs:протащить{}, // протащить с собой rus_verbs:разминуться{}, // разминуться с встречным потоком rus_verbs:перемежаться{}, // перемежаться с успехами rus_verbs:рассчитаться{}, // рассчитаться с кредиторами rus_verbs:срастись{}, // срастись с телом rus_verbs:знакомить{}, // знакомить с родителями rus_verbs:поругаться{}, // поругаться с родителями rus_verbs:совладать{}, // совладать с чувствами rus_verbs:обручить{}, // обручить с богатой невестой rus_verbs:сближаться{}, // сближаться с вражеским эсминцем rus_verbs:замутить{}, // замутить с Ксюшей rus_verbs:повозиться{}, // повозиться с настройкой rus_verbs:торговаться{}, // торговаться с продавцами rus_verbs:уединиться{}, // уединиться с девчонкой rus_verbs:переборщить{}, // переборщить с добавкой rus_verbs:ознакомить{}, // ознакомить с пожеланиями rus_verbs:прочесывать{}, // прочесывать с собаками rus_verbs:переписываться{}, // переписываться с корреспондентами rus_verbs:повздорить{}, // повздорить с сержантом rus_verbs:разлучить{}, // разлучить с семьей rus_verbs:соседствовать{}, // соседствовать с цыганами rus_verbs:застукать{}, // застукать с проститутками rus_verbs:напуститься{}, // напуститься с кулаками rus_verbs:сдружиться{}, // сдружиться с ребятами rus_verbs:соперничать{}, // соперничать с параллельным классом rus_verbs:прочесать{}, // прочесать с собаками rus_verbs:кокетничать{}, // кокетничать с гимназистками rus_verbs:мириться{}, // мириться с убытками rus_verbs:оплошать{}, // оплошать с билетами rus_verbs:отождествлять{}, // отождествлять с литературным героем rus_verbs:хитрить{}, // хитрить с зарплатой rus_verbs:провозиться{}, // провозиться с задачкой rus_verbs:коротать{}, // коротать с друзьями rus_verbs:соревноваться{}, // соревноваться с машиной rus_verbs:уживаться{}, // уживаться с местными жителями rus_verbs:отождествляться{}, // отождествляться с литературным героем rus_verbs:сопоставить{}, // сопоставить с эталоном rus_verbs:пьянствовать{}, // пьянствовать с друзьями rus_verbs:залетать{}, // залетать с паленой водкой rus_verbs:гастролировать{}, // гастролировать с новой цирковой программой rus_verbs:запаздывать{}, // запаздывать с кормлением rus_verbs:таскаться{}, // таскаться с сумками rus_verbs:контрастировать{}, // контрастировать с туфлями rus_verbs:сшибиться{}, // сшибиться с форвардом rus_verbs:состязаться{}, // состязаться с лучшей командой rus_verbs:затрудниться{}, // затрудниться с объяснением rus_verbs:объясниться{}, // объясниться с пострадавшими rus_verbs:разводиться{}, // разводиться со сварливой женой rus_verbs:препираться{}, // препираться с адвокатами rus_verbs:сосуществовать{}, // сосуществовать с крупными хищниками rus_verbs:свестись{}, // свестись с нулевым счетом rus_verbs:обговорить{}, // обговорить с директором rus_verbs:обвенчаться{}, // обвенчаться с ведьмой rus_verbs:экспериментировать{}, // экспериментировать с генами rus_verbs:сверять{}, // сверять с таблицей rus_verbs:сверяться{}, // свериться с таблицей rus_verbs:сблизить{}, // сблизить с точкой rus_verbs:гармонировать{}, // гармонировать с обоями rus_verbs:перемешивать{}, // перемешивать с молоком rus_verbs:трепаться{}, // трепаться с сослуживцами rus_verbs:перемигиваться{}, // перемигиваться с соседкой rus_verbs:разоткровенничаться{}, // разоткровенничаться с незнакомцем rus_verbs:распить{}, // распить с собутыльниками rus_verbs:скрестись{}, // скрестись с дикой лошадью rus_verbs:передраться{}, // передраться с дворовыми собаками rus_verbs:умыть{}, // умыть с мылом rus_verbs:грызться{}, // грызться с соседями rus_verbs:переругиваться{}, // переругиваться с соседями rus_verbs:доиграться{}, // доиграться со спичками rus_verbs:заладиться{}, // заладиться с подругой rus_verbs:скрещиваться{}, // скрещиваться с дикими видами rus_verbs:повидаться{}, // повидаться с дедушкой rus_verbs:повоевать{}, // повоевать с орками rus_verbs:сразиться{}, // сразиться с лучшим рыцарем rus_verbs:кипятить{}, // кипятить с отбеливателем rus_verbs:усердствовать{}, // усердствовать с наказанием rus_verbs:схлестнуться{}, // схлестнуться с лучшим боксером rus_verbs:пошептаться{}, // пошептаться с судьями rus_verbs:сравняться{}, // сравняться с лучшими экземплярами rus_verbs:церемониться{}, // церемониться с пьяницами rus_verbs:консультироваться{}, // консультироваться со специалистами rus_verbs:переусердствовать{}, // переусердствовать с наказанием rus_verbs:проноситься{}, // проноситься с собой rus_verbs:перемешать{}, // перемешать с гипсом rus_verbs:темнить{}, // темнить с долгами rus_verbs:сталкивать{}, // сталкивать с черной дырой rus_verbs:увольнять{}, // увольнять с волчьим билетом rus_verbs:заигрывать{}, // заигрывать с совершенно диким животным rus_verbs:сопоставлять{}, // сопоставлять с эталонными образцами rus_verbs:расторгнуть{}, // расторгнуть с нерасторопными поставщиками долгосрочный контракт rus_verbs:созвониться{}, // созвониться с мамой rus_verbs:спеться{}, // спеться с отъявленными хулиганами rus_verbs:интриговать{}, // интриговать с придворными rus_verbs:приобрести{}, // приобрести со скидкой rus_verbs:задержаться{}, // задержаться со сдачей работы rus_verbs:плавать{}, // плавать со спасательным кругом rus_verbs:якшаться{}, // Не якшайся с врагами инфинитив:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги инфинитив:ассоциировать{вид:несоверш}, глагол:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги глагол:ассоциировать{вид:несоверш}, //+прилагательное:ассоциировавший{вид:несоверш}, прилагательное:ассоциировавший{вид:соверш}, прилагательное:ассоциирующий{}, деепричастие:ассоциируя{}, деепричастие:ассоциировав{}, rus_verbs:ассоциироваться{}, // герой книги ассоциируется с реальным персонажем rus_verbs:аттестовывать{}, // Они аттестовывают сотрудников с помощью наборра тестов rus_verbs:аттестовываться{}, // Сотрудники аттестовываются с помощью набора тестов //+инфинитив:аффилировать{вид:соверш}, // эти предприятия были аффилированы с олигархом //+глагол:аффилировать{вид:соверш}, прилагательное:аффилированный{}, rus_verbs:баловаться{}, // мальчик баловался с молотком rus_verbs:балясничать{}, // женщина балясничала с товарками rus_verbs:богатеть{}, // Провинция богатеет от торговли с соседями rus_verbs:бодаться{}, // теленок бодается с деревом rus_verbs:боксировать{}, // Майкл дважды боксировал с ним rus_verbs:брататься{}, // Солдаты братались с бойцами союзников rus_verbs:вальсировать{}, // Мальчик вальсирует с девочкой rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу rus_verbs:происходить{}, // Что происходит с мировой экономикой? rus_verbs:произойти{}, // Что произошло с экономикой? rus_verbs:взаимодействовать{}, // Электроны взаимодействуют с фотонами rus_verbs:вздорить{}, // Эта женщина часто вздорила с соседями rus_verbs:сойтись{}, // Мальчик сошелся с бандой хулиганов rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями rus_verbs:водиться{}, // Няня водится с детьми rus_verbs:воевать{}, // Фермеры воевали с волками rus_verbs:возиться{}, // Няня возится с детьми rus_verbs:ворковать{}, // Голубь воркует с голубкой rus_verbs:воссоединиться{}, // Дети воссоединились с семьей rus_verbs:воссоединяться{}, // Дети воссоединяются с семьей rus_verbs:вошкаться{}, // Не вошкайся с этой ерундой rus_verbs:враждовать{}, // враждовать с соседями rus_verbs:временить{}, // временить с выходом на пенсию rus_verbs:расстаться{}, // я не могу расстаться с тобой rus_verbs:выдирать{}, // выдирать с мясом rus_verbs:выдираться{}, // выдираться с мясом rus_verbs:вытворить{}, // вытворить что-либо с чем-либо rus_verbs:вытворять{}, // вытворять что-либо с чем-либо rus_verbs:сделать{}, // сделать с чем-то rus_verbs:домыть{}, // домыть с мылом rus_verbs:случиться{}, // случиться с кем-то rus_verbs:остаться{}, // остаться с кем-то rus_verbs:случать{}, // случать с породистым кобельком rus_verbs:послать{}, // послать с весточкой rus_verbs:работать{}, // работать с роботами rus_verbs:провести{}, // провести с девчонками время rus_verbs:заговорить{}, // заговорить с незнакомкой rus_verbs:прошептать{}, // прошептать с придыханием rus_verbs:читать{}, // читать с выражением rus_verbs:слушать{}, // слушать с повышенным вниманием rus_verbs:принести{}, // принести с собой rus_verbs:спать{}, // спать с женщинами rus_verbs:закончить{}, // закончить с приготовлениями rus_verbs:помочь{}, // помочь с перестановкой rus_verbs:уехать{}, // уехать с семьей rus_verbs:случаться{}, // случаться с кем-то rus_verbs:кутить{}, // кутить с проститутками rus_verbs:разговаривать{}, // разговаривать с ребенком rus_verbs:погодить{}, // погодить с ликвидацией rus_verbs:считаться{}, // считаться с чужим мнением rus_verbs:носить{}, // носить с собой rus_verbs:хорошеть{}, // хорошеть с каждым днем rus_verbs:приводить{}, // приводить с собой rus_verbs:прыгнуть{}, // прыгнуть с парашютом rus_verbs:петь{}, // петь с чувством rus_verbs:сложить{}, // сложить с результатом rus_verbs:познакомиться{}, // познакомиться с другими студентами rus_verbs:обращаться{}, // обращаться с животными rus_verbs:съесть{}, // съесть с хлебом rus_verbs:ошибаться{}, // ошибаться с дозировкой rus_verbs:столкнуться{}, // столкнуться с медведем rus_verbs:справиться{}, // справиться с нуждой rus_verbs:торопиться{}, // торопиться с ответом rus_verbs:поздравлять{}, // поздравлять с победой rus_verbs:объясняться{}, // объясняться с начальством rus_verbs:пошутить{}, // пошутить с подругой rus_verbs:поздороваться{}, // поздороваться с коллегами rus_verbs:поступать{}, // Как поступать с таким поведением? rus_verbs:определяться{}, // определяться с кандидатами rus_verbs:связаться{}, // связаться с поставщиком rus_verbs:спорить{}, // спорить с собеседником rus_verbs:разобраться{}, // разобраться с делами rus_verbs:ловить{}, // ловить с удочкой rus_verbs:помедлить{}, // Кандидат помедлил с ответом на заданный вопрос rus_verbs:шутить{}, // шутить с диким зверем rus_verbs:разорвать{}, // разорвать с поставщиком контракт rus_verbs:увезти{}, // увезти с собой rus_verbs:унести{}, // унести с собой rus_verbs:сотворить{}, // сотворить с собой что-то нехорошее rus_verbs:складываться{}, // складываться с первым импульсом rus_verbs:соглашаться{}, // соглашаться с предложенным договором //rus_verbs:покончить{}, // покончить с развратом rus_verbs:прихватить{}, // прихватить с собой rus_verbs:похоронить{}, // похоронить с почестями rus_verbs:связывать{}, // связывать с компанией свою судьбу rus_verbs:совпадать{}, // совпадать с предсказанием rus_verbs:танцевать{}, // танцевать с девушками rus_verbs:поделиться{}, // поделиться с выжившими rus_verbs:оставаться{}, // я не хотел оставаться с ним в одной комнате. rus_verbs:беседовать{}, // преподаватель, беседующий со студентами rus_verbs:бороться{}, // человек, борющийся со смертельной болезнью rus_verbs:шептаться{}, // девочка, шепчущаяся с подругой rus_verbs:сплетничать{}, // женщина, сплетничавшая с товарками rus_verbs:поговорить{}, // поговорить с виновниками rus_verbs:сказать{}, // сказать с трудом rus_verbs:произнести{}, // произнести с трудом rus_verbs:говорить{}, // говорить с акцентом rus_verbs:произносить{}, // произносить с трудом rus_verbs:встречаться{}, // кто с Антонио встречался? rus_verbs:посидеть{}, // посидеть с друзьями rus_verbs:расквитаться{}, // расквитаться с обидчиком rus_verbs:поквитаться{}, // поквитаться с обидчиком rus_verbs:ругаться{}, // ругаться с женой rus_verbs:поскандалить{}, // поскандалить с женой rus_verbs:потанцевать{}, // потанцевать с подругой rus_verbs:скандалить{}, // скандалить с соседями rus_verbs:разругаться{}, // разругаться с другом rus_verbs:болтать{}, // болтать с подругами rus_verbs:потрепаться{}, // потрепаться с соседкой rus_verbs:войти{}, // войти с регистрацией rus_verbs:входить{}, // входить с регистрацией rus_verbs:возвращаться{}, // возвращаться с триумфом rus_verbs:опоздать{}, // Он опоздал с подачей сочинения. rus_verbs:молчать{}, // Он молчал с ледяным спокойствием. rus_verbs:сражаться{}, // Он героически сражался с врагами. rus_verbs:выходить{}, // Он всегда выходит с зонтиком. rus_verbs:сличать{}, // сличать перевод с оригиналом rus_verbs:начать{}, // я начал с товарищем спор о религии rus_verbs:согласовать{}, // Маша согласовала с Петей дальнейшие поездки rus_verbs:приходить{}, // Приходите с нею. rus_verbs:жить{}, // кто с тобой жил? rus_verbs:расходиться{}, // Маша расходится с Петей rus_verbs:сцеплять{}, // сцеплять карабин с обвязкой rus_verbs:торговать{}, // мы торгуем с ними нефтью rus_verbs:уединяться{}, // уединяться с подругой в доме rus_verbs:уладить{}, // уладить конфликт с соседями rus_verbs:идти{}, // Я шел туда с тяжёлым сердцем. rus_verbs:разделять{}, // Я разделяю с вами горе и радость. rus_verbs:обратиться{}, // Я обратился к нему с просьбой о помощи. rus_verbs:захватить{}, // Я не захватил с собой денег. прилагательное:знакомый{}, // Я знаком с ними обоими. rus_verbs:вести{}, // Я веду с ней переписку. прилагательное:сопряженный{}, // Это сопряжено с большими трудностями. прилагательное:связанный{причастие}, // Это дело связано с риском. rus_verbs:поехать{}, // Хотите поехать со мной в театр? rus_verbs:проснуться{}, // Утром я проснулся с ясной головой. rus_verbs:лететь{}, // Самолёт летел со скоростью звука. rus_verbs:играть{}, // С огнём играть опасно! rus_verbs:поделать{}, // С ним ничего не поделаешь. rus_verbs:стрястись{}, // С ней стряслось несчастье. rus_verbs:смотреться{}, // Пьеса смотрится с удовольствием. rus_verbs:смотреть{}, // Она смотрела на меня с явным неудовольствием. rus_verbs:разойтись{}, // Она разошлась с мужем. rus_verbs:пристать{}, // Она пристала ко мне с расспросами. rus_verbs:посмотреть{}, // Она посмотрела на меня с удивлением. rus_verbs:поступить{}, // Она плохо поступила с ним. rus_verbs:выйти{}, // Она вышла с усталым и недовольным видом. rus_verbs:взять{}, // Возьмите с собой только самое необходимое. rus_verbs:наплакаться{}, // Наплачется она с ним. rus_verbs:лежать{}, // Он лежит с воспалением лёгких. rus_verbs:дышать{}, // дышащий с трудом rus_verbs:брать{}, // брать с собой rus_verbs:мчаться{}, // Автомобиль мчится с необычайной быстротой. rus_verbs:упасть{}, // Ваза упала со звоном. rus_verbs:вернуться{}, // мы вернулись вчера домой с полным лукошком rus_verbs:сидеть{}, // Она сидит дома с ребенком rus_verbs:встретиться{}, // встречаться с кем-либо ГЛ_ИНФ(придти), прилагательное:пришедший{}, // пришедший с другом ГЛ_ИНФ(постирать), прилагательное:постиранный{}, деепричастие:постирав{}, rus_verbs:мыть{} } fact гл_предл { if context { Гл_С_Твор предлог:с{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_С_Твор предлог:с{} *:*{падеж:твор} } then return true } #endregion ТВОРИТЕЛЬНЫЙ #region РОДИТЕЛЬНЫЙ wordentry_set Гл_С_Род= { rus_verbs:УХОДИТЬ{}, // Но с базы не уходить. rus_verbs:РВАНУТЬ{}, // Водитель прорычал проклятие и рванул машину с места. (РВАНУТЬ) rus_verbs:ОХВАТИТЬ{}, // огонь охватил его со всех сторон (ОХВАТИТЬ) rus_verbs:ЗАМЕТИТЬ{}, // Он понимал, что свет из тайника невозможно заметить с палубы (ЗАМЕТИТЬ/РАЗГЛЯДЕТЬ) rus_verbs:РАЗГЛЯДЕТЬ{}, // rus_verbs:СПЛАНИРОВАТЬ{}, // Птицы размером с орлицу, вероятно, не могли бы подняться в воздух, не спланировав с высокого утеса. (СПЛАНИРОВАТЬ) rus_verbs:УМЕРЕТЬ{}, // Он умрет с голоду. (УМЕРЕТЬ) rus_verbs:ВСПУГНУТЬ{}, // Оба упали с лязгом, вспугнувшим птиц с ближайших деревьев (ВСПУГНУТЬ) rus_verbs:РЕВЕТЬ{}, // Время от времени какой-то ящер ревел с берега или самой реки. (РЕВЕТЬ/ЗАРЕВЕТЬ/ПРОРЕВЕТЬ/ЗАОРАТЬ/ПРООРАТЬ/ОРАТЬ/ПРОКРИЧАТЬ/ЗАКРИЧАТЬ/ВОПИТЬ/ЗАВОПИТЬ) rus_verbs:ЗАРЕВЕТЬ{}, // rus_verbs:ПРОРЕВЕТЬ{}, // rus_verbs:ЗАОРАТЬ{}, // rus_verbs:ПРООРАТЬ{}, // rus_verbs:ОРАТЬ{}, // rus_verbs:ЗАКРИЧАТЬ{}, rus_verbs:ВОПИТЬ{}, // rus_verbs:ЗАВОПИТЬ{}, // rus_verbs:СТАЩИТЬ{}, // Я видела как они стащили его с валуна и увели с собой. (СТАЩИТЬ/СТАСКИВАТЬ) rus_verbs:СТАСКИВАТЬ{}, // rus_verbs:ПРОВЫТЬ{}, // Призрак трубного зова провыл с другой стороны дверей. (ПРОВЫТЬ, ЗАВЫТЬ, ВЫТЬ) rus_verbs:ЗАВЫТЬ{}, // rus_verbs:ВЫТЬ{}, // rus_verbs:СВЕТИТЬ{}, // Полуденное майское солнце ярко светило с голубых небес Аризоны. (СВЕТИТЬ) rus_verbs:ОТСВЕЧИВАТЬ{}, // Солнце отсвечивало с белых лошадей, белых щитов и белых перьев и искрилось на наконечниках пик. (ОТСВЕЧИВАТЬ С, ИСКРИТЬСЯ НА) rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое rus_verbs:собирать{}, // мальчики начали собирать со столов посуду rus_verbs:разглядывать{}, // ты ее со всех сторон разглядывал rus_verbs:СЖИМАТЬ{}, // меня плотно сжимали со всех сторон (СЖИМАТЬ) rus_verbs:СОБРАТЬСЯ{}, // со всего света собрались! (СОБРАТЬСЯ) rus_verbs:ИЗГОНЯТЬ{}, // Вино в пакетах изгоняют с рынка (ИЗГОНЯТЬ) rus_verbs:ВЛЮБИТЬСЯ{}, // влюбился в нее с первого взгляда (ВЛЮБИТЬСЯ) rus_verbs:РАЗДАВАТЬСЯ{}, // теперь крик раздавался со всех сторон (РАЗДАВАТЬСЯ) rus_verbs:ПОСМОТРЕТЬ{}, // Посмотрите на это с моей точки зрения (ПОСМОТРЕТЬ С род) rus_verbs:СХОДИТЬ{}, // принимать участие во всех этих событиях - значит продолжать сходить с ума (СХОДИТЬ С род) rus_verbs:РУХНУТЬ{}, // В Башкирии микроавтобус рухнул с моста (РУХНУТЬ С) rus_verbs:УВОЛИТЬ{}, // рекомендовать уволить их с работы (УВОЛИТЬ С) rus_verbs:КУПИТЬ{}, // еда , купленная с рук (КУПИТЬ С род) rus_verbs:УБРАТЬ{}, // помочь убрать со стола? (УБРАТЬ С) rus_verbs:ТЯНУТЬ{}, // с моря тянуло ветром (ТЯНУТЬ С) rus_verbs:ПРИХОДИТЬ{}, // приходит с работы муж (ПРИХОДИТЬ С) rus_verbs:ПРОПАСТЬ{}, // изображение пропало с экрана (ПРОПАСТЬ С) rus_verbs:ПОТЯНУТЬ{}, // с балкона потянуло холодом (ПОТЯНУТЬ С род) rus_verbs:РАЗДАТЬСЯ{}, // с палубы раздался свист (РАЗДАТЬСЯ С род) rus_verbs:ЗАЙТИ{}, // зашел с другой стороны (ЗАЙТИ С род) rus_verbs:НАЧАТЬ{}, // давай начнем с этого (НАЧАТЬ С род) rus_verbs:УВЕСТИ{}, // дала увести с развалин (УВЕСТИ С род) rus_verbs:ОПУСКАТЬСЯ{}, // с гор опускалась ночь (ОПУСКАТЬСЯ С) rus_verbs:ВСКОЧИТЬ{}, // Тристан вскочил с места (ВСКОЧИТЬ С род) rus_verbs:БРАТЬ{}, // беру с него пример (БРАТЬ С род) rus_verbs:ПРИПОДНЯТЬСЯ{}, // голова приподнялась с плеча (ПРИПОДНЯТЬСЯ С род) rus_verbs:ПОЯВИТЬСЯ{}, // всадники появились с востока (ПОЯВИТЬСЯ С род) rus_verbs:НАЛЕТЕТЬ{}, // с моря налетел ветер (НАЛЕТЕТЬ С род) rus_verbs:ВЗВИТЬСЯ{}, // Натан взвился с места (ВЗВИТЬСЯ С род) rus_verbs:ПОДОБРАТЬ{}, // подобрал с земли копье (ПОДОБРАТЬ С) rus_verbs:ДЕРНУТЬСЯ{}, // Кирилл дернулся с места (ДЕРНУТЬСЯ С род) rus_verbs:ВОЗВРАЩАТЬСЯ{}, // они возвращались с реки (ВОЗВРАЩАТЬСЯ С род) rus_verbs:ПЛЫТЬ{}, // плыли они с запада (ПЛЫТЬ С род) rus_verbs:ЗНАТЬ{}, // одно знали с древности (ЗНАТЬ С) rus_verbs:НАКЛОНИТЬСЯ{}, // всадник наклонился с лошади (НАКЛОНИТЬСЯ С) rus_verbs:НАЧАТЬСЯ{}, // началось все со скуки (НАЧАТЬСЯ С) прилагательное:ИЗВЕСТНЫЙ{}, // Культура его известна со времен глубокой древности (ИЗВЕСТНЫЙ С) rus_verbs:СБИТЬ{}, // Порыв ветра сбил Ваньку с ног (ts СБИТЬ С) rus_verbs:СОБИРАТЬСЯ{}, // они собираются сюда со всей равнины. (СОБИРАТЬСЯ С род) rus_verbs:смыть{}, // Дождь должен смыть с листьев всю пыль. (СМЫТЬ С) rus_verbs:привстать{}, // Мартин привстал со своего стула. (привстать с) rus_verbs:спасть{}, // тяжесть спала с души. (спасть с) rus_verbs:выглядеть{}, // так оно со стороны выглядело. (ВЫГЛЯДЕТЬ С) rus_verbs:повернуть{}, // к вечеру они повернули с нее направо. (ПОВЕРНУТЬ С) rus_verbs:ТЯНУТЬСЯ{}, // со стороны реки ко мне тянулись языки тумана. (ТЯНУТЬСЯ С) rus_verbs:ВОЕВАТЬ{}, // Генерал воевал с юных лет. (ВОЕВАТЬ С чего-то) rus_verbs:БОЛЕТЬ{}, // Голова болит с похмелья. (БОЛЕТЬ С) rus_verbs:приближаться{}, // со стороны острова приближалась лодка. rus_verbs:ПОТЯНУТЬСЯ{}, // со всех сторон к нему потянулись руки. (ПОТЯНУТЬСЯ С) rus_verbs:пойти{}, // низкий гул пошел со стороны долины. (пошел с) rus_verbs:зашевелиться{}, // со всех сторон зашевелились кусты. (зашевелиться с) rus_verbs:МЧАТЬСЯ{}, // со стороны леса мчались всадники. (МЧАТЬСЯ С) rus_verbs:БЕЖАТЬ{}, // люди бежали со всех ног. (БЕЖАТЬ С) rus_verbs:СЛЫШАТЬСЯ{}, // шум слышался со стороны моря. (СЛЫШАТЬСЯ С) rus_verbs:ЛЕТЕТЬ{}, // со стороны деревни летела птица. (ЛЕТЕТЬ С) rus_verbs:ПЕРЕТЬ{}, // враги прут со всех сторон. (ПЕРЕТЬ С) rus_verbs:ПОСЫПАТЬСЯ{}, // вопросы посыпались со всех сторон. (ПОСЫПАТЬСЯ С) rus_verbs:ИДТИ{}, // угроза шла со стороны моря. (ИДТИ С + род.п.) rus_verbs:ПОСЛЫШАТЬСЯ{}, // со стен послышались крики ужаса. (ПОСЛЫШАТЬСЯ С) rus_verbs:ОБРУШИТЬСЯ{}, // звуки обрушились со всех сторон. (ОБРУШИТЬСЯ С) rus_verbs:УДАРИТЬ{}, // голоса ударили со всех сторон. (УДАРИТЬ С) rus_verbs:ПОКАЗАТЬСЯ{}, // со стороны деревни показались земляне. (ПОКАЗАТЬСЯ С) rus_verbs:прыгать{}, // придется прыгать со второго этажа. (прыгать с) rus_verbs:СТОЯТЬ{}, // со всех сторон стоял лес. (СТОЯТЬ С) rus_verbs:доноситься{}, // шум со двора доносился чудовищный. (доноситься с) rus_verbs:мешать{}, // мешать воду с мукой (мешать с) rus_verbs:вестись{}, // Переговоры ведутся с позиции силы. (вестись с) rus_verbs:вставать{}, // Он не встает с кровати. (вставать с) rus_verbs:окружать{}, // зеленые щупальца окружали ее со всех сторон. (окружать с) rus_verbs:причитаться{}, // С вас причитается 50 рублей. rus_verbs:соскользнуть{}, // его острый клюв соскользнул с ее руки. rus_verbs:сократить{}, // Его сократили со службы. rus_verbs:поднять{}, // рука подняла с пола rus_verbs:поднимать{}, rus_verbs:тащить{}, // тем временем другие пришельцы тащили со всех сторон камни. rus_verbs:полететь{}, // Мальчик полетел с лестницы. rus_verbs:литься{}, // вода льется с неба rus_verbs:натечь{}, // натечь с сапог rus_verbs:спрыгивать{}, // спрыгивать с движущегося трамвая rus_verbs:съезжать{}, // съезжать с заявленной темы rus_verbs:покатываться{}, // покатываться со смеху rus_verbs:перескакивать{}, // перескакивать с одного примера на другой rus_verbs:сдирать{}, // сдирать с тела кожу rus_verbs:соскальзывать{}, // соскальзывать с крючка rus_verbs:сметать{}, // сметать с прилавков rus_verbs:кувыркнуться{}, // кувыркнуться со ступеньки rus_verbs:прокаркать{}, // прокаркать с ветки rus_verbs:стряхивать{}, // стряхивать с одежды rus_verbs:сваливаться{}, // сваливаться с лестницы rus_verbs:слизнуть{}, // слизнуть с лица rus_verbs:доставляться{}, // доставляться с фермы rus_verbs:обступать{}, // обступать с двух сторон rus_verbs:повскакивать{}, // повскакивать с мест rus_verbs:обозревать{}, // обозревать с вершины rus_verbs:слинять{}, // слинять с урока rus_verbs:смывать{}, // смывать с лица rus_verbs:спихнуть{}, // спихнуть со стола rus_verbs:обозреть{}, // обозреть с вершины rus_verbs:накупить{}, // накупить с рук rus_verbs:схлынуть{}, // схлынуть с берега rus_verbs:спикировать{}, // спикировать с километровой высоты rus_verbs:уползти{}, // уползти с поля боя rus_verbs:сбиваться{}, // сбиваться с пути rus_verbs:отлучиться{}, // отлучиться с поста rus_verbs:сигануть{}, // сигануть с крыши rus_verbs:сместить{}, // сместить с поста rus_verbs:списать{}, // списать с оригинального устройства инфинитив:слетать{ вид:несоверш }, глагол:слетать{ вид:несоверш }, // слетать с трассы деепричастие:слетая{}, rus_verbs:напиваться{}, // напиваться с горя rus_verbs:свесить{}, // свесить с крыши rus_verbs:заполучить{}, // заполучить со склада rus_verbs:спадать{}, // спадать с глаз rus_verbs:стартовать{}, // стартовать с мыса rus_verbs:спереть{}, // спереть со склада rus_verbs:согнать{}, // согнать с живота rus_verbs:скатываться{}, // скатываться со стога rus_verbs:сняться{}, // сняться с выборов rus_verbs:слезать{}, // слезать со стола rus_verbs:деваться{}, // деваться с подводной лодки rus_verbs:огласить{}, // огласить с трибуны rus_verbs:красть{}, // красть со склада rus_verbs:расширить{}, // расширить с торца rus_verbs:угадывать{}, // угадывать с полуслова rus_verbs:оскорбить{}, // оскорбить со сцены rus_verbs:срывать{}, // срывать с головы rus_verbs:сшибить{}, // сшибить с коня rus_verbs:сбивать{}, // сбивать с одежды rus_verbs:содрать{}, // содрать с посетителей rus_verbs:столкнуть{}, // столкнуть с горы rus_verbs:отряхнуть{}, // отряхнуть с одежды rus_verbs:сбрасывать{}, // сбрасывать с борта rus_verbs:расстреливать{}, // расстреливать с борта вертолета rus_verbs:придти{}, // мать скоро придет с работы rus_verbs:съехать{}, // Миша съехал с горки rus_verbs:свисать{}, // свисать с веток rus_verbs:стянуть{}, // стянуть с кровати rus_verbs:скинуть{}, // скинуть снег с плеча rus_verbs:загреметь{}, // загреметь со стула rus_verbs:сыпаться{}, // сыпаться с неба rus_verbs:стряхнуть{}, // стряхнуть с головы rus_verbs:сползти{}, // сползти со стула rus_verbs:стереть{}, // стереть с экрана rus_verbs:прогнать{}, // прогнать с фермы rus_verbs:смахнуть{}, // смахнуть со стола rus_verbs:спускать{}, // спускать с поводка rus_verbs:деться{}, // деться с подводной лодки rus_verbs:сдернуть{}, // сдернуть с себя rus_verbs:сдвинуться{}, // сдвинуться с места rus_verbs:слететь{}, // слететь с катушек rus_verbs:обступить{}, // обступить со всех сторон rus_verbs:снести{}, // снести с плеч инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, // сбегать с уроков деепричастие:сбегая{}, прилагательное:сбегающий{}, // прилагательное:сбегавший{ вид:несоверш }, rus_verbs:запить{}, // запить с горя rus_verbs:рубануть{}, // рубануть с плеча rus_verbs:чертыхнуться{}, // чертыхнуться с досады rus_verbs:срываться{}, // срываться с цепи rus_verbs:смыться{}, // смыться с уроков rus_verbs:похитить{}, // похитить со склада rus_verbs:смести{}, // смести со своего пути rus_verbs:отгружать{}, // отгружать со склада rus_verbs:отгрузить{}, // отгрузить со склада rus_verbs:бросаться{}, // Дети бросались в воду с моста rus_verbs:броситься{}, // самоубийца бросился с моста в воду rus_verbs:взимать{}, // Билетер взимает плату с каждого посетителя rus_verbs:взиматься{}, // Плата взимается с любого посетителя rus_verbs:взыскать{}, // Приставы взыскали долг с бедолаги rus_verbs:взыскивать{}, // Приставы взыскивают с бедолаги все долги rus_verbs:взыскиваться{}, // Долги взыскиваются с алиментщиков rus_verbs:вспархивать{}, // вспархивать с цветка rus_verbs:вспорхнуть{}, // вспорхнуть с ветки rus_verbs:выбросить{}, // выбросить что-то с балкона rus_verbs:выводить{}, // выводить с одежды пятна rus_verbs:снять{}, // снять с головы rus_verbs:начинать{}, // начинать с эскиза rus_verbs:двинуться{}, // двинуться с места rus_verbs:начинаться{}, // начинаться с гардероба rus_verbs:стечь{}, // стечь с крыши rus_verbs:слезть{}, // слезть с кучи rus_verbs:спуститься{}, // спуститься с крыши rus_verbs:сойти{}, // сойти с пьедестала rus_verbs:свернуть{}, // свернуть с пути rus_verbs:сорвать{}, // сорвать с цепи rus_verbs:сорваться{}, // сорваться с поводка rus_verbs:тронуться{}, // тронуться с места rus_verbs:угадать{}, // угадать с первой попытки rus_verbs:спустить{}, // спустить с лестницы rus_verbs:соскочить{}, // соскочить с крючка rus_verbs:сдвинуть{}, // сдвинуть с места rus_verbs:подниматься{}, // туман, поднимающийся с болота rus_verbs:подняться{}, // туман, поднявшийся с болота rus_verbs:валить{}, // Резкий порывистый ветер валит прохожих с ног. rus_verbs:свалить{}, // Резкий порывистый ветер свалит тебя с ног. rus_verbs:донестись{}, // С улицы донесся шум дождя. rus_verbs:опасть{}, // Опавшие с дерева листья. rus_verbs:махнуть{}, // Он махнул с берега в воду. rus_verbs:исчезнуть{}, // исчезнуть с экрана rus_verbs:свалиться{}, // свалиться со сцены rus_verbs:упасть{}, // упасть с дерева rus_verbs:вернуться{}, // Он ещё не вернулся с работы. rus_verbs:сдувать{}, // сдувать пух с одуванчиков rus_verbs:свергать{}, // свергать царя с трона rus_verbs:сбиться{}, // сбиться с пути rus_verbs:стирать{}, // стирать тряпкой надпись с доски rus_verbs:убирать{}, // убирать мусор c пола rus_verbs:удалять{}, // удалять игрока с поля rus_verbs:окружить{}, // Япония окружена со всех сторон морями. rus_verbs:снимать{}, // Я снимаю с себя всякую ответственность за его поведение. глагол:писаться{ aux stress="пис^аться" }, // Собственные имена пишутся с большой буквы. прилагательное:спокойный{}, // С этой стороны я спокоен. rus_verbs:спросить{}, // С тебя за всё спросят. rus_verbs:течь{}, // С него течёт пот. rus_verbs:дуть{}, // С моря дует ветер. rus_verbs:капать{}, // С его лица капали крупные капли пота. rus_verbs:опустить{}, // Она опустила ребёнка с рук на пол. rus_verbs:спрыгнуть{}, // Она легко спрыгнула с коня. rus_verbs:встать{}, // Все встали со стульев. rus_verbs:сбросить{}, // Войдя в комнату, он сбросил с себя пальто. rus_verbs:взять{}, // Возьми книгу с полки. rus_verbs:спускаться{}, // Мы спускались с горы. rus_verbs:уйти{}, // Он нашёл себе заместителя и ушёл со службы. rus_verbs:порхать{}, // Бабочка порхает с цветка на цветок. rus_verbs:отправляться{}, // Ваш поезд отправляется со второй платформы. rus_verbs:двигаться{}, // Он не двигался с места. rus_verbs:отходить{}, // мой поезд отходит с первого пути rus_verbs:попасть{}, // Майкл попал в кольцо с десятиметровой дистанции rus_verbs:падать{}, // снег падает с ветвей rus_verbs:скрыться{} // Ее водитель, бросив машину, скрылся с места происшествия. } fact гл_предл { if context { Гл_С_Род предлог:с{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_С_Род предлог:с{} *:*{падеж:род} } then return true } fact гл_предл { if context { Гл_С_Род предлог:с{} *:*{падеж:парт} } then return true } #endregion РОДИТЕЛЬНЫЙ fact гл_предл { if context { * предлог:с{} *:*{ падеж:твор } } then return false,-3 } fact гл_предл { if context { * предлог:с{} *:*{ падеж:род } } then return false,-4 } fact гл_предл { if context { * предлог:с{} * } then return false,-5 } #endregion Предлог_С /* #region Предлог_ПОД // -------------- ПРЕДЛОГ 'ПОД' ----------------------- fact гл_предл { if context { * предлог:под{} @regex("[a-z]+[0-9]*") } then return true } // ПОД+вин.п. не может присоединяться к существительным, поэтому // он присоединяется к любым глаголам. fact гл_предл { if context { * предлог:под{} *:*{ падеж:вин } } then return true } wordentry_set Гл_ПОД_твор= { rus_verbs:извиваться{}, // извивалась под его длинными усами rus_verbs:РАСПРОСТРАНЯТЬСЯ{}, // Под густым ковром травы и плотным сплетением корней (РАСПРОСТРАНЯТЬСЯ) rus_verbs:БРОСИТЬ{}, // чтобы ты его под деревом бросил? (БРОСИТЬ) rus_verbs:БИТЬСЯ{}, // под моей щекой сильно билось его сердце (БИТЬСЯ) rus_verbs:ОПУСТИТЬСЯ{}, // глаза его опустились под ее желтым взглядом (ОПУСТИТЬСЯ) rus_verbs:ВЗДЫМАТЬСЯ{}, // его грудь судорожно вздымалась под ее рукой (ВЗДЫМАТЬСЯ) rus_verbs:ПРОМЧАТЬСЯ{}, // Она промчалась под ними и исчезла за изгибом горы. (ПРОМЧАТЬСЯ) rus_verbs:всплыть{}, // Наконец он всплыл под нависавшей кормой, так и не отыскав того, что хотел. (всплыть) rus_verbs:КОНЧАТЬСЯ{}, // Он почти вертикально уходит в реку и кончается глубоко под водой. (КОНЧАТЬСЯ) rus_verbs:ПОЛЗТИ{}, // Там они ползли под спутанным терновником и сквозь переплетавшиеся кусты (ПОЛЗТИ) rus_verbs:ПРОХОДИТЬ{}, // Вольф проходил под гигантскими ветвями деревьев и мхов, свисавших с ветвей зелеными водопадами. (ПРОХОДИТЬ, ПРОПОЛЗТИ, ПРОПОЛЗАТЬ) rus_verbs:ПРОПОЛЗТИ{}, // rus_verbs:ПРОПОЛЗАТЬ{}, // rus_verbs:ИМЕТЬ{}, // Эти предположения не имеют под собой никакой почвы (ИМЕТЬ) rus_verbs:НОСИТЬ{}, // она носит под сердцем ребенка (НОСИТЬ) rus_verbs:ПАСТЬ{}, // Рим пал под натиском варваров (ПАСТЬ) rus_verbs:УТОНУТЬ{}, // Выступавшие старческие вены снова утонули под гладкой твердой плотью. (УТОНУТЬ) rus_verbs:ВАЛЯТЬСЯ{}, // Под его кривыми серыми ветвями и пестрыми коричнево-зелеными листьями валялись пустые ореховые скорлупки и сердцевины плодов. (ВАЛЯТЬСЯ) rus_verbs:вздрогнуть{}, // она вздрогнула под его взглядом rus_verbs:иметься{}, // у каждого под рукой имелся арбалет rus_verbs:ЖДАТЬ{}, // Сашка уже ждал под дождем (ЖДАТЬ) rus_verbs:НОЧЕВАТЬ{}, // мне приходилось ночевать под открытым небом (НОЧЕВАТЬ) rus_verbs:УЗНАТЬ{}, // вы должны узнать меня под этим именем (УЗНАТЬ) rus_verbs:ЗАДЕРЖИВАТЬСЯ{}, // мне нельзя задерживаться под землей! (ЗАДЕРЖИВАТЬСЯ) rus_verbs:ПОГИБНУТЬ{}, // под их копытами погибли целые армии! (ПОГИБНУТЬ) rus_verbs:РАЗДАВАТЬСЯ{}, // под ногами у меня раздавался сухой хруст (РАЗДАВАТЬСЯ) rus_verbs:КРУЖИТЬСЯ{}, // поверхность планеты кружилась у него под ногами (КРУЖИТЬСЯ) rus_verbs:ВИСЕТЬ{}, // под глазами у него висели тяжелые складки кожи (ВИСЕТЬ) rus_verbs:содрогнуться{}, // содрогнулся под ногами каменный пол (СОДРОГНУТЬСЯ) rus_verbs:СОБИРАТЬСЯ{}, // темнота уже собиралась под деревьями (СОБИРАТЬСЯ) rus_verbs:УПАСТЬ{}, // толстяк упал под градом ударов (УПАСТЬ) rus_verbs:ДВИНУТЬСЯ{}, // лодка двинулась под водой (ДВИНУТЬСЯ) rus_verbs:ЦАРИТЬ{}, // под его крышей царила холодная зима (ЦАРИТЬ) rus_verbs:ПРОВАЛИТЬСЯ{}, // под копытами его лошади провалился мост (ПРОВАЛИТЬСЯ ПОД твор) rus_verbs:ЗАДРОЖАТЬ{}, // земля задрожала под ногами (ЗАДРОЖАТЬ) rus_verbs:НАХМУРИТЬСЯ{}, // государь нахмурился под маской (НАХМУРИТЬСЯ) rus_verbs:РАБОТАТЬ{}, // работать под угрозой нельзя (РАБОТАТЬ) rus_verbs:ШЕВЕЛЬНУТЬСЯ{}, // под ногой шевельнулся камень (ШЕВЕЛЬНУТЬСЯ) rus_verbs:ВИДЕТЬ{}, // видел тебя под камнем. (ВИДЕТЬ) rus_verbs:ОСТАТЬСЯ{}, // второе осталось под водой (ОСТАТЬСЯ) rus_verbs:КИПЕТЬ{}, // вода кипела под копытами (КИПЕТЬ) rus_verbs:СИДЕТЬ{}, // может сидит под деревом (СИДЕТЬ) rus_verbs:МЕЛЬКНУТЬ{}, // под нами мелькнуло море (МЕЛЬКНУТЬ) rus_verbs:ПОСЛЫШАТЬСЯ{}, // под окном послышался шум (ПОСЛЫШАТЬСЯ) rus_verbs:ТЯНУТЬСЯ{}, // под нами тянулись облака (ТЯНУТЬСЯ) rus_verbs:ДРОЖАТЬ{}, // земля дрожала под ним (ДРОЖАТЬ) rus_verbs:ПРИЙТИСЬ{}, // хуже пришлось под землей (ПРИЙТИСЬ) rus_verbs:ГОРЕТЬ{}, // лампа горела под потолком (ГОРЕТЬ) rus_verbs:ПОЛОЖИТЬ{}, // положил под деревом плащ (ПОЛОЖИТЬ) rus_verbs:ЗАГОРЕТЬСЯ{}, // под деревьями загорелся костер (ЗАГОРЕТЬСЯ) rus_verbs:ПРОНОСИТЬСЯ{}, // под нами проносились крыши (ПРОНОСИТЬСЯ) rus_verbs:ПОТЯНУТЬСЯ{}, // под кораблем потянулись горы (ПОТЯНУТЬСЯ) rus_verbs:БЕЖАТЬ{}, // беги под серой стеной ночи (БЕЖАТЬ) rus_verbs:РАЗДАТЬСЯ{}, // под окном раздалось тяжелое дыхание (РАЗДАТЬСЯ) rus_verbs:ВСПЫХНУТЬ{}, // под потолком вспыхнула яркая лампа (ВСПЫХНУТЬ) rus_verbs:СМОТРЕТЬ{}, // просто смотрите под другим углом (СМОТРЕТЬ ПОД) rus_verbs:ДУТЬ{}, // теперь под деревьями дул ветерок (ДУТЬ) rus_verbs:СКРЫТЬСЯ{}, // оно быстро скрылось под водой (СКРЫТЬСЯ ПОД) rus_verbs:ЩЕЛКНУТЬ{}, // далеко под ними щелкнул выстрел (ЩЕЛКНУТЬ) rus_verbs:ТРЕЩАТЬ{}, // осколки стекла трещали под ногами (ТРЕЩАТЬ) rus_verbs:РАСПОЛАГАТЬСЯ{}, // под ними располагались разноцветные скамьи (РАСПОЛАГАТЬСЯ) rus_verbs:ВЫСТУПИТЬ{}, // под ногтями выступили капельки крови (ВЫСТУПИТЬ) rus_verbs:НАСТУПИТЬ{}, // под куполом базы наступила тишина (НАСТУПИТЬ) rus_verbs:ОСТАНОВИТЬСЯ{}, // повозка остановилась под самым окном (ОСТАНОВИТЬСЯ) rus_verbs:РАСТАЯТЬ{}, // магазин растаял под ночным дождем (РАСТАЯТЬ) rus_verbs:ДВИГАТЬСЯ{}, // под водой двигалось нечто огромное (ДВИГАТЬСЯ) rus_verbs:БЫТЬ{}, // под снегом могут быть трещины (БЫТЬ) rus_verbs:ЗИЯТЬ{}, // под ней зияла ужасная рана (ЗИЯТЬ) rus_verbs:ЗАЗВОНИТЬ{}, // под рукой водителя зазвонил телефон (ЗАЗВОНИТЬ) rus_verbs:ПОКАЗАТЬСЯ{}, // внезапно под ними показалась вода (ПОКАЗАТЬСЯ) rus_verbs:ЗАМЕРЕТЬ{}, // эхо замерло под высоким потолком (ЗАМЕРЕТЬ) rus_verbs:ПОЙТИ{}, // затем под кораблем пошла пустыня (ПОЙТИ) rus_verbs:ДЕЙСТВОВАТЬ{}, // боги всегда действуют под маской (ДЕЙСТВОВАТЬ) rus_verbs:БЛЕСТЕТЬ{}, // мокрый мех блестел под луной (БЛЕСТЕТЬ) rus_verbs:ЛЕТЕТЬ{}, // под ним летела серая земля (ЛЕТЕТЬ) rus_verbs:СОГНУТЬСЯ{}, // содрогнулся под ногами каменный пол (СОГНУТЬСЯ) rus_verbs:КИВНУТЬ{}, // четвертый слегка кивнул под капюшоном (КИВНУТЬ) rus_verbs:УМЕРЕТЬ{}, // колдун умер под грудой каменных глыб (УМЕРЕТЬ) rus_verbs:ОКАЗЫВАТЬСЯ{}, // внезапно под ногами оказывается знакомая тропинка (ОКАЗЫВАТЬСЯ) rus_verbs:ИСЧЕЗАТЬ{}, // серая лента дороги исчезала под воротами (ИСЧЕЗАТЬ) rus_verbs:СВЕРКНУТЬ{}, // голубые глаза сверкнули под густыми бровями (СВЕРКНУТЬ) rus_verbs:СИЯТЬ{}, // под ним сияла белая пелена облаков (СИЯТЬ) rus_verbs:ПРОНЕСТИСЬ{}, // тихий смех пронесся под куполом зала (ПРОНЕСТИСЬ) rus_verbs:СКОЛЬЗИТЬ{}, // обломки судна медленно скользили под ними (СКОЛЬЗИТЬ) rus_verbs:ВЗДУТЬСЯ{}, // под серой кожей вздулись шары мускулов (ВЗДУТЬСЯ) rus_verbs:ПРОЙТИ{}, // обломок отлично пройдет под колесами слева (ПРОЙТИ) rus_verbs:РАЗВЕВАТЬСЯ{}, // светлые волосы развевались под дыханием ветра (РАЗВЕВАТЬСЯ) rus_verbs:СВЕРКАТЬ{}, // глаза огнем сверкали под темными бровями (СВЕРКАТЬ) rus_verbs:КАЗАТЬСЯ{}, // деревянный док казался очень твердым под моими ногами (КАЗАТЬСЯ) rus_verbs:ПОСТАВИТЬ{}, // четвертый маг торопливо поставил под зеркалом широкую чашу (ПОСТАВИТЬ) rus_verbs:ОСТАВАТЬСЯ{}, // запасы остаются под давлением (ОСТАВАТЬСЯ ПОД) rus_verbs:ПЕТЬ{}, // просто мы под землей любим петь. (ПЕТЬ ПОД) rus_verbs:ПОЯВИТЬСЯ{}, // под их крыльями внезапно появился дым. (ПОЯВИТЬСЯ ПОД) rus_verbs:ОКАЗАТЬСЯ{}, // мы снова оказались под солнцем. (ОКАЗАТЬСЯ ПОД) rus_verbs:ПОДХОДИТЬ{}, // мы подходили под другим углом? (ПОДХОДИТЬ ПОД) rus_verbs:СКРЫВАТЬСЯ{}, // кто под ней скрывается? (СКРЫВАТЬСЯ ПОД) rus_verbs:ХЛЮПАТЬ{}, // под ногами Аллы хлюпала грязь (ХЛЮПАТЬ ПОД) rus_verbs:ШАГАТЬ{}, // их отряд весело шагал под дождем этой музыки. (ШАГАТЬ ПОД) rus_verbs:ТЕЧЬ{}, // под ее поверхностью медленно текла ярость. (ТЕЧЬ ПОД твор) rus_verbs:ОЧУТИТЬСЯ{}, // мы очутились под стенами замка. (ОЧУТИТЬСЯ ПОД) rus_verbs:ПОБЛЕСКИВАТЬ{}, // их латы поблескивали под солнцем. (ПОБЛЕСКИВАТЬ ПОД) rus_verbs:ДРАТЬСЯ{}, // под столами дрались за кости псы. (ДРАТЬСЯ ПОД) rus_verbs:КАЧНУТЬСЯ{}, // палуба качнулась у нас под ногами. (КАЧНУЛАСЬ ПОД) rus_verbs:ПРИСЕСТЬ{}, // конь даже присел под тяжелым телом. (ПРИСЕСТЬ ПОД) rus_verbs:ЖИТЬ{}, // они живут под землей. (ЖИТЬ ПОД) rus_verbs:ОБНАРУЖИТЬ{}, // вы можете обнаружить ее под водой? (ОБНАРУЖИТЬ ПОД) rus_verbs:ПЛЫТЬ{}, // Орёл плывёт под облаками. (ПЛЫТЬ ПОД) rus_verbs:ИСЧЕЗНУТЬ{}, // потом они исчезли под водой. (ИСЧЕЗНУТЬ ПОД) rus_verbs:держать{}, // оружие все держали под рукой. (держать ПОД) rus_verbs:ВСТРЕТИТЬСЯ{}, // они встретились под водой. (ВСТРЕТИТЬСЯ ПОД) rus_verbs:уснуть{}, // Миша уснет под одеялом rus_verbs:пошевелиться{}, // пошевелиться под одеялом rus_verbs:задохнуться{}, // задохнуться под слоем снега rus_verbs:потечь{}, // потечь под избыточным давлением rus_verbs:уцелеть{}, // уцелеть под завалами rus_verbs:мерцать{}, // мерцать под лучами софитов rus_verbs:поискать{}, // поискать под кроватью rus_verbs:гудеть{}, // гудеть под нагрузкой rus_verbs:посидеть{}, // посидеть под навесом rus_verbs:укрыться{}, // укрыться под навесом rus_verbs:утихнуть{}, // утихнуть под одеялом rus_verbs:заскрипеть{}, // заскрипеть под тяжестью rus_verbs:шелохнуться{}, // шелохнуться под одеялом инфинитив:срезать{ вид:несоверш }, глагол:срезать{ вид:несоверш }, // срезать под корень деепричастие:срезав{}, прилагательное:срезающий{ вид:несоверш }, инфинитив:срезать{ вид:соверш }, глагол:срезать{ вид:соверш }, деепричастие:срезая{}, прилагательное:срезавший{ вид:соверш }, rus_verbs:пониматься{}, // пониматься под успехом rus_verbs:подразумеваться{}, // подразумеваться под правильным решением rus_verbs:промокнуть{}, // промокнуть под проливным дождем rus_verbs:засосать{}, // засосать под ложечкой rus_verbs:подписаться{}, // подписаться под воззванием rus_verbs:укрываться{}, // укрываться под навесом rus_verbs:запыхтеть{}, // запыхтеть под одеялом rus_verbs:мокнуть{}, // мокнуть под лождем rus_verbs:сгибаться{}, // сгибаться под тяжестью снега rus_verbs:намокнуть{}, // намокнуть под дождем rus_verbs:подписываться{}, // подписываться под обращением rus_verbs:тарахтеть{}, // тарахтеть под окнами инфинитив:находиться{вид:несоверш}, глагол:находиться{вид:несоверш}, // Она уже несколько лет находится под наблюдением врача. деепричастие:находясь{}, прилагательное:находившийся{вид:несоверш}, прилагательное:находящийся{}, rus_verbs:лежать{}, // лежать под капельницей rus_verbs:вымокать{}, // вымокать под дождём rus_verbs:вымокнуть{}, // вымокнуть под дождём rus_verbs:проворчать{}, // проворчать под нос rus_verbs:хмыкнуть{}, // хмыкнуть под нос rus_verbs:отыскать{}, // отыскать под кроватью rus_verbs:дрогнуть{}, // дрогнуть под ударами rus_verbs:проявляться{}, // проявляться под нагрузкой rus_verbs:сдержать{}, // сдержать под контролем rus_verbs:ложиться{}, // ложиться под клиента rus_verbs:таять{}, // таять под весенним солнцем rus_verbs:покатиться{}, // покатиться под откос rus_verbs:лечь{}, // он лег под навесом rus_verbs:идти{}, // идти под дождем прилагательное:известный{}, // Он известен под этим именем. rus_verbs:стоять{}, // Ящик стоит под столом. rus_verbs:отступить{}, // Враг отступил под ударами наших войск. rus_verbs:царапаться{}, // Мышь царапается под полом. rus_verbs:спать{}, // заяц спокойно спал у себя под кустом rus_verbs:загорать{}, // мы загораем под солнцем ГЛ_ИНФ(мыть), // мыть руки под струёй воды ГЛ_ИНФ(закопать), ГЛ_ИНФ(спрятать), ГЛ_ИНФ(прятать), ГЛ_ИНФ(перепрятать) } fact гл_предл { if context { Гл_ПОД_твор предлог:под{} *:*{ падеж:твор } } then return true } // для глаголов вне списка - запрещаем. fact гл_предл { if context { * предлог:под{} *:*{ падеж:твор } } then return false,-10 } fact гл_предл { if context { * предлог:под{} *:*{} } then return false,-11 } #endregion Предлог_ПОД */ #region Предлог_ОБ // -------------- ПРЕДЛОГ 'ОБ' ----------------------- wordentry_set Гл_ОБ_предл= { rus_verbs:СВИДЕТЕЛЬСТВОВАТЬ{}, // Об их присутствии свидетельствовало лишь тусклое пурпурное пятно, проступавшее на камне. (СВИДЕТЕЛЬСТВОВАТЬ) rus_verbs:ЗАДУМАТЬСЯ{}, // Промышленные гиганты задумались об экологии (ЗАДУМАТЬСЯ) rus_verbs:СПРОСИТЬ{}, // Он спросил нескольких из пляжников об их кажущейся всеобщей юности. (СПРОСИТЬ) rus_verbs:спрашивать{}, // как ты можешь еще спрашивать у меня об этом? rus_verbs:забывать{}, // Мы не можем забывать об их участи. rus_verbs:ГАДАТЬ{}, // теперь об этом можно лишь гадать (ГАДАТЬ) rus_verbs:ПОВЕДАТЬ{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам (ПОВЕДАТЬ ОБ) rus_verbs:СООБЩИТЬ{}, // Иран сообщил МАГАТЭ об ускорении обогащения урана (СООБЩИТЬ) rus_verbs:ЗАЯВИТЬ{}, // Об их успешном окончании заявил генеральный директор (ЗАЯВИТЬ ОБ) rus_verbs:слышать{}, // даже они слышали об этом человеке. (СЛЫШАТЬ ОБ) rus_verbs:ДОЛОЖИТЬ{}, // вернувшиеся разведчики доложили об увиденном (ДОЛОЖИТЬ ОБ) rus_verbs:ПОГОВОРИТЬ{}, // давай поговорим об этом. (ПОГОВОРИТЬ ОБ) rus_verbs:ДОГАДАТЬСЯ{}, // об остальном нетрудно догадаться. (ДОГАДАТЬСЯ ОБ) rus_verbs:ПОЗАБОТИТЬСЯ{}, // обещал обо всем позаботиться. (ПОЗАБОТИТЬСЯ ОБ) rus_verbs:ПОЗАБЫТЬ{}, // Шура позабыл обо всем. (ПОЗАБЫТЬ ОБ) rus_verbs:вспоминать{}, // Впоследствии он не раз вспоминал об этом приключении. (вспоминать об) rus_verbs:сообщать{}, // Газета сообщает об открытии сессии парламента. (сообщать об) rus_verbs:просить{}, // мы просили об отсрочке платежей (просить ОБ) rus_verbs:ПЕТЬ{}, // эта же девушка пела обо всем совершенно открыто. (ПЕТЬ ОБ) rus_verbs:сказать{}, // ты скажешь об этом капитану? (сказать ОБ) rus_verbs:знать{}, // бы хотелось знать как можно больше об этом районе. rus_verbs:кричать{}, // Все газеты кричат об этом событии. rus_verbs:советоваться{}, // Она обо всём советуется с матерью. rus_verbs:говориться{}, // об остальном говорилось легко. rus_verbs:подумать{}, // нужно крепко обо всем подумать. rus_verbs:напомнить{}, // черный дым напомнил об опасности. rus_verbs:забыть{}, // забудь об этой роскоши. rus_verbs:думать{}, // приходится обо всем думать самой. rus_verbs:отрапортовать{}, // отрапортовать об успехах rus_verbs:информировать{}, // информировать об изменениях rus_verbs:оповестить{}, // оповестить об отказе rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:заговорить{}, // заговорить об оплате rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой. rus_verbs:попросить{}, // попросить об услуге rus_verbs:объявить{}, // объявить об отставке rus_verbs:предупредить{}, // предупредить об аварии rus_verbs:предупреждать{}, // предупреждать об опасности rus_verbs:твердить{}, // твердить об обязанностях rus_verbs:заявлять{}, // заявлять об экспериментальном подтверждении rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц. rus_verbs:читать{}, // он читал об этом в журнале rus_verbs:прочитать{}, // он читал об этом в учебнике rus_verbs:узнать{}, // он узнал об этом из фильмов rus_verbs:рассказать{}, // рассказать об экзаменах rus_verbs:рассказывать{}, rus_verbs:договориться{}, // договориться об оплате rus_verbs:договариваться{}, // договариваться об обмене rus_verbs:болтать{}, // Не болтай об этом! rus_verbs:проболтаться{}, // Не проболтайся об этом! rus_verbs:заботиться{}, // кто заботится об урегулировании rus_verbs:беспокоиться{}, // вы беспокоитесь об обороне rus_verbs:помнить{}, // всем советую об этом помнить rus_verbs:мечтать{} // Мечтать об успехе } fact гл_предл { if context { Гл_ОБ_предл предлог:об{} *:*{ падеж:предл } } then return true } fact гл_предл { if context { * предлог:о{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { * предлог:об{} @regex("[a-z]+[0-9]*") } then return true } // остальные глаголы не могут связываться fact гл_предл { if context { * предлог:об{} *:*{ падеж:предл } } then return false, -4 } wordentry_set Гл_ОБ_вин= { rus_verbs:СЛОМАТЬ{}, // потом об колено сломал (СЛОМАТЬ) rus_verbs:разбить{}, // ты разбил щеку об угол ящика. (РАЗБИТЬ ОБ) rus_verbs:опереться{}, // Он опёрся об стену. rus_verbs:опираться{}, rus_verbs:постучать{}, // постучал лбом об пол. rus_verbs:удариться{}, // бутылка глухо ударилась об землю. rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:царапаться{} // Днище лодки царапалось обо что-то. } fact гл_предл { if context { Гл_ОБ_вин предлог:об{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { * предлог:об{} *:*{ падеж:вин } } then return false,-4 } fact гл_предл { if context { * предлог:об{} *:*{} } then return false,-5 } #endregion Предлог_ОБ #region Предлог_О // ------------------- С ПРЕДЛОГОМ 'О' ---------------------- wordentry_set Гл_О_Вин={ rus_verbs:шмякнуть{}, // Ей хотелось шмякнуть ими о стену. rus_verbs:болтать{}, // Болтали чаще всего о пустяках. rus_verbs:шваркнуть{}, // Она шваркнула трубкой о рычаг. rus_verbs:опираться{}, // Мать приподнялась, с трудом опираясь о стол. rus_verbs:бахнуться{}, // Бахнуться головой о стол. rus_verbs:ВЫТЕРЕТЬ{}, // Вытащи нож и вытри его о траву. (ВЫТЕРЕТЬ/ВЫТИРАТЬ) rus_verbs:ВЫТИРАТЬ{}, // rus_verbs:РАЗБИТЬСЯ{}, // Прибой накатился и с шумом разбился о белый песок. (РАЗБИТЬСЯ) rus_verbs:СТУКНУТЬ{}, // Сердце его глухо стукнуло о грудную кость (СТУКНУТЬ) rus_verbs:ЛЯЗГНУТЬ{}, // Он кинулся наземь, покатился, и копье лязгнуло о стену. (ЛЯЗГНУТЬ/ЛЯЗГАТЬ) rus_verbs:ЛЯЗГАТЬ{}, // rus_verbs:звенеть{}, // стрелы уже звенели о прутья клетки rus_verbs:ЩЕЛКНУТЬ{}, // камень щелкнул о скалу (ЩЕЛКНУТЬ) rus_verbs:БИТЬ{}, // волна бьет о берег (БИТЬ) rus_verbs:ЗАЗВЕНЕТЬ{}, // зазвенели мечи о щиты (ЗАЗВЕНЕТЬ) rus_verbs:колотиться{}, // сердце его колотилось о ребра rus_verbs:стучать{}, // глухо стучали о щиты рукояти мечей. rus_verbs:биться{}, // биться головой о стену? (биться о) rus_verbs:ударить{}, // вода ударила его о стену коридора. (ударила о) rus_verbs:разбиваться{}, // волны разбивались о скалу rus_verbs:разбивать{}, // Разбивает голову о прутья клетки. rus_verbs:облокотиться{}, // облокотиться о стену rus_verbs:точить{}, // точить о точильный камень rus_verbs:спотыкаться{}, // спотыкаться о спрятавшийся в траве пень rus_verbs:потереться{}, // потереться о дерево rus_verbs:ушибиться{}, // ушибиться о дерево rus_verbs:тереться{}, // тереться о ствол rus_verbs:шмякнуться{}, // шмякнуться о землю rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:тереть{}, // тереть о камень rus_verbs:потереть{}, // потереть о колено rus_verbs:удариться{}, // удариться о край rus_verbs:споткнуться{}, // споткнуться о камень rus_verbs:запнуться{}, // запнуться о камень rus_verbs:запинаться{}, // запинаться о камни rus_verbs:ударяться{}, // ударяться о бортик rus_verbs:стукнуться{}, // стукнуться о бортик rus_verbs:стукаться{}, // стукаться о бортик rus_verbs:опереться{}, // Он опёрся локтями о стол. rus_verbs:плескаться{} // Вода плещется о берег. } fact гл_предл { if context { Гл_О_Вин предлог:о{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { * предлог:о{} *:*{ падеж:вин } } then return false,-5 } wordentry_set Гл_О_предл={ rus_verbs:КРИЧАТЬ{}, // она кричала о смерти! (КРИЧАТЬ) rus_verbs:РАССПРОСИТЬ{}, // Я расспросил о нем нескольких горожан. (РАССПРОСИТЬ/РАССПРАШИВАТЬ) rus_verbs:РАССПРАШИВАТЬ{}, // rus_verbs:слушать{}, // ты будешь слушать о них? rus_verbs:вспоминать{}, // вспоминать о том разговоре ему было неприятно rus_verbs:МОЛЧАТЬ{}, // О чём молчат девушки (МОЛЧАТЬ) rus_verbs:ПЛАКАТЬ{}, // она плакала о себе (ПЛАКАТЬ) rus_verbs:сложить{}, // о вас сложены легенды rus_verbs:ВОЛНОВАТЬСЯ{}, // Я волнуюсь о том, что что-то серьёзно пошло не так (ВОЛНОВАТЬСЯ О) rus_verbs:УПОМЯНУТЬ{}, // упомянул о намерении команды приобрести несколько новых футболистов (УПОМЯНУТЬ О) rus_verbs:ОТЧИТЫВАТЬСЯ{}, // Судебные приставы продолжают отчитываться о борьбе с неплательщиками (ОТЧИТЫВАТЬСЯ О) rus_verbs:ДОЛОЖИТЬ{}, // провести тщательное расследование взрыва в маршрутном такси во Владикавказе и доложить о результатах (ДОЛОЖИТЬ О) rus_verbs:ПРОБОЛТАТЬ{}, // правительство страны больше проболтало о военной реформе (ПРОБОЛТАТЬ О) rus_verbs:ЗАБОТИТЬСЯ{}, // Четверть россиян заботятся о здоровье путем просмотра телевизора (ЗАБОТИТЬСЯ О) rus_verbs:ИРОНИЗИРОВАТЬ{}, // Вы иронизируете о ностальгии по тем временем (ИРОНИЗИРОВАТЬ О) rus_verbs:СИГНАЛИЗИРОВАТЬ{}, // Кризис цен на продукты питания сигнализирует о неминуемой гиперинфляции (СИГНАЛИЗИРОВАТЬ О) rus_verbs:СПРОСИТЬ{}, // Он спросил о моём здоровье. (СПРОСИТЬ О) rus_verbs:НАПОМНИТЬ{}, // больной зуб опять напомнил о себе. (НАПОМНИТЬ О) rus_verbs:осведомиться{}, // офицер осведомился о цели визита rus_verbs:объявить{}, // В газете объявили о конкурсе. (объявить о) rus_verbs:ПРЕДСТОЯТЬ{}, // о чем предстоит разговор? (ПРЕДСТОЯТЬ О) rus_verbs:объявлять{}, // объявлять о всеобщей забастовке (объявлять о) rus_verbs:зайти{}, // Разговор зашёл о политике. rus_verbs:порассказать{}, // порассказать о своих путешествиях инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть о неразделенной любви деепричастие:спев{}, прилагательное:спевший{ вид:соверш }, прилагательное:спетый{}, rus_verbs:напеть{}, rus_verbs:разговаривать{}, // разговаривать с другом о жизни rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях //rus_verbs:заботиться{}, // заботиться о престарелых родителях rus_verbs:раздумывать{}, // раздумывать о новой работе rus_verbs:договариваться{}, // договариваться о сумме компенсации rus_verbs:молить{}, // молить о пощаде rus_verbs:отзываться{}, // отзываться о книге rus_verbs:подумывать{}, // подумывать о новом подходе rus_verbs:поговаривать{}, // поговаривать о загадочном звере rus_verbs:обмолвиться{}, // обмолвиться о проклятии rus_verbs:условиться{}, // условиться о поддержке rus_verbs:призадуматься{}, // призадуматься о последствиях rus_verbs:известить{}, // известить о поступлении rus_verbs:отрапортовать{}, // отрапортовать об успехах rus_verbs:напевать{}, // напевать о любви rus_verbs:помышлять{}, // помышлять о новом деле rus_verbs:переговорить{}, // переговорить о правилах rus_verbs:повествовать{}, // повествовать о событиях rus_verbs:слыхивать{}, // слыхивать о чудище rus_verbs:потолковать{}, // потолковать о планах rus_verbs:проговориться{}, // проговориться о планах rus_verbs:умолчать{}, // умолчать о штрафах rus_verbs:хлопотать{}, // хлопотать о премии rus_verbs:уведомить{}, // уведомить о поступлении rus_verbs:горевать{}, // горевать о потере rus_verbs:запамятовать{}, // запамятовать о важном мероприятии rus_verbs:заикнуться{}, // заикнуться о прибавке rus_verbs:информировать{}, // информировать о событиях rus_verbs:проболтаться{}, // проболтаться о кладе rus_verbs:поразмыслить{}, // поразмыслить о судьбе rus_verbs:заикаться{}, // заикаться о деньгах rus_verbs:оповестить{}, // оповестить об отказе rus_verbs:печься{}, // печься о всеобщем благе rus_verbs:разглагольствовать{}, // разглагольствовать о правах rus_verbs:размечтаться{}, // размечтаться о будущем rus_verbs:лепетать{}, // лепетать о невиновности rus_verbs:грезить{}, // грезить о большой и чистой любви rus_verbs:залепетать{}, // залепетать о сокровищах rus_verbs:пронюхать{}, // пронюхать о бесплатной одежде rus_verbs:протрубить{}, // протрубить о победе rus_verbs:извещать{}, // извещать о поступлении rus_verbs:трубить{}, // трубить о поимке разбойников rus_verbs:осведомляться{}, // осведомляться о судьбе rus_verbs:поразмышлять{}, // поразмышлять о неизбежном rus_verbs:слагать{}, // слагать о подвигах викингов rus_verbs:ходатайствовать{}, // ходатайствовать о выделении материальной помощи rus_verbs:побеспокоиться{}, // побеспокоиться о правильном стимулировании rus_verbs:закидывать{}, // закидывать сообщениями об ошибках rus_verbs:базарить{}, // пацаны базарили о телках rus_verbs:балагурить{}, // мужики балагурили о новом председателе rus_verbs:балакать{}, // мужики балакали о новом председателе rus_verbs:беспокоиться{}, // Она беспокоится о детях rus_verbs:рассказать{}, // Кумир рассказал о криминале в Москве rus_verbs:возмечтать{}, // возмечтать о счастливом мире rus_verbs:вопить{}, // Кто-то вопил о несправедливости rus_verbs:сказать{}, // сказать что-то новое о ком-то rus_verbs:знать{}, // знать о ком-то что-то пикантное rus_verbs:подумать{}, // подумать о чём-то rus_verbs:думать{}, // думать о чём-то rus_verbs:узнать{}, // узнать о происшествии rus_verbs:помнить{}, // помнить о задании rus_verbs:просить{}, // просить о коде доступа rus_verbs:забыть{}, // забыть о своих обязанностях rus_verbs:сообщить{}, // сообщить о заложенной мине rus_verbs:заявить{}, // заявить о пропаже rus_verbs:задуматься{}, // задуматься о смерти rus_verbs:спрашивать{}, // спрашивать о поступлении товара rus_verbs:догадаться{}, // догадаться о причинах rus_verbs:договориться{}, // договориться о собеседовании rus_verbs:мечтать{}, // мечтать о сцене rus_verbs:поговорить{}, // поговорить о наболевшем rus_verbs:размышлять{}, // размышлять о насущном rus_verbs:напоминать{}, // напоминать о себе rus_verbs:пожалеть{}, // пожалеть о содеянном rus_verbs:ныть{}, // ныть о прибавке rus_verbs:сообщать{}, // сообщать о победе rus_verbs:догадываться{}, // догадываться о первопричине rus_verbs:поведать{}, // поведать о тайнах rus_verbs:умолять{}, // умолять о пощаде rus_verbs:сожалеть{}, // сожалеть о случившемся rus_verbs:жалеть{}, // жалеть о случившемся rus_verbs:забывать{}, // забывать о случившемся rus_verbs:упоминать{}, // упоминать о предках rus_verbs:позабыть{}, // позабыть о своем обещании rus_verbs:запеть{}, // запеть о любви rus_verbs:скорбеть{}, // скорбеть о усопшем rus_verbs:задумываться{}, // задумываться о смене работы rus_verbs:позаботиться{}, // позаботиться о престарелых родителях rus_verbs:докладывать{}, // докладывать о планах строительства целлюлозно-бумажного комбината rus_verbs:попросить{}, // попросить о замене rus_verbs:предупредить{}, // предупредить о замене rus_verbs:предупреждать{}, // предупреждать о замене rus_verbs:твердить{}, // твердить о замене rus_verbs:заявлять{}, // заявлять о подлоге rus_verbs:петь{}, // певица, поющая о лете rus_verbs:проинформировать{}, // проинформировать о переговорах rus_verbs:порассказывать{}, // порассказывать о событиях rus_verbs:послушать{}, // послушать о новинках rus_verbs:заговорить{}, // заговорить о плате rus_verbs:отозваться{}, // Он отозвался о книге с большой похвалой. rus_verbs:оставить{}, // Он оставил о себе печальную память. rus_verbs:свидетельствовать{}, // страшно исхудавшее тело свидетельствовало о долгих лишениях rus_verbs:спорить{}, // они спорили о законе глагол:написать{ aux stress="напис^ать" }, инфинитив:написать{ aux stress="напис^ать" }, // Он написал о том, что видел во время путешествия. глагол:писать{ aux stress="пис^ать" }, инфинитив:писать{ aux stress="пис^ать" }, // Он писал о том, что видел во время путешествия. rus_verbs:прочитать{}, // Я прочитал о тебе rus_verbs:услышать{}, // Я услышал о нем rus_verbs:помечтать{}, // Девочки помечтали о принце rus_verbs:слышать{}, // Мальчик слышал о приведениях rus_verbs:вспомнить{}, // Девочки вспомнили о завтраке rus_verbs:грустить{}, // Я грущу о тебе rus_verbs:осведомить{}, // о последних достижениях науки rus_verbs:рассказывать{}, // Антонио рассказывает о работе rus_verbs:говорить{}, // говорим о трех больших псах rus_verbs:идти{} // Вопрос идёт о войне. } fact гл_предл { if context { Гл_О_предл предлог:о{} *:*{ падеж:предл } } then return true } // Мы поделились впечатлениями о выставке. // ^^^^^^^^^^ ^^^^^^^^^^ fact гл_предл { if context { * предлог:о{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:о{} *:*{} } then return false,-5 } #endregion Предлог_О #region Предлог_ПО // ------------------- С ПРЕДЛОГОМ 'ПО' ---------------------- // для этих глаголов - запрещаем связывание с ПО+дат.п. wordentry_set Глаг_ПО_Дат_Запр= { rus_verbs:предпринять{}, // предпринять шаги по стимулированию продаж rus_verbs:увлечь{}, // увлечь в прогулку по парку rus_verbs:закончить{}, rus_verbs:мочь{}, rus_verbs:хотеть{} } fact гл_предл { if context { Глаг_ПО_Дат_Запр предлог:по{} *:*{ падеж:дат } } then return false,-10 } // По умолчанию разрешаем связывание в паттернах типа // Я иду по шоссе fact гл_предл { if context { * предлог:по{} *:*{ падеж:дат } } then return true } wordentry_set Глаг_ПО_Вин= { rus_verbs:ВОЙТИ{}, // лезвие вошло по рукоять (ВОЙТИ) rus_verbs:иметь{}, // все месяцы имели по тридцать дней. (ИМЕТЬ ПО) rus_verbs:материализоваться{}, // материализоваться по другую сторону барьера rus_verbs:засадить{}, // засадить по рукоятку rus_verbs:увязнуть{} // увязнуть по колено } fact гл_предл { if context { Глаг_ПО_Вин предлог:по{} *:*{ падеж:вин } } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:по{} *:*{ падеж:вин } } then return false,-5 } #endregion Предлог_ПО #region Предлог_К // ------------------- С ПРЕДЛОГОМ 'К' ---------------------- wordentry_set Гл_К_Дат={ rus_verbs:заявиться{}, // Сразу же после обеда к нам заявилась Юлия Михайловна. rus_verbs:приставлять{} , // Приставляет дуло пистолета к виску. прилагательное:НЕПРИГОДНЫЙ{}, // большинство компьютеров из этой партии оказались непригодными к эксплуатации (НЕПРИГОДНЫЙ) rus_verbs:СБЕГАТЬСЯ{}, // Они чуяли воду и сбегались к ней отовсюду. (СБЕГАТЬСЯ) rus_verbs:СБЕЖАТЬСЯ{}, // К бетонной скамье начали сбегаться люди. (СБЕГАТЬСЯ/СБЕЖАТЬСЯ) rus_verbs:ПРИТИРАТЬСЯ{}, // Менее стойких водителей буквально сметало на другую полосу, и они впритык притирались к другим машинам. (ПРИТИРАТЬСЯ) rus_verbs:РУХНУТЬ{}, // а потом ты без чувств рухнул к моим ногам (РУХНУТЬ) rus_verbs:ПЕРЕНЕСТИ{}, // Они перенесли мясо к ручью и поджарили его на костре. (ПЕРЕНЕСТИ) rus_verbs:ЗАВЕСТИ{}, // как путь мой завел меня к нему? (ЗАВЕСТИ) rus_verbs:НАГРЯНУТЬ{}, // ФБР нагрянуло с обыском к сестре бостонских террористов (НАГРЯНУТЬ) rus_verbs:ПРИСЛОНЯТЬСЯ{}, // Рабы ложились на пол, прислонялись к стене и спали. (ПРИСЛОНЯТЬСЯ,ПРИНОРАВЛИВАТЬСЯ,ПРИНОРОВИТЬСЯ) rus_verbs:ПРИНОРАВЛИВАТЬСЯ{}, // rus_verbs:ПРИНОРОВИТЬСЯ{}, // rus_verbs:СПЛАНИРОВАТЬ{}, // Вскоре она остановила свое падение и спланировала к ним. (СПЛАНИРОВАТЬ,СПИКИРОВАТЬ,РУХНУТЬ) rus_verbs:СПИКИРОВАТЬ{}, // rus_verbs:ЗАБРАТЬСЯ{}, // Поэтому он забрался ко мне в квартиру с имевшимся у него полумесяцем. (ЗАБРАТЬСЯ К, В, С) rus_verbs:ПРОТЯГИВАТЬ{}, // Оно протягивало свои длинные руки к молодому человеку, стоявшему на плоской вершине валуна. (ПРОТЯГИВАТЬ/ПРОТЯНУТЬ/ТЯНУТЬ) rus_verbs:ПРОТЯНУТЬ{}, // rus_verbs:ТЯНУТЬ{}, // rus_verbs:ПЕРЕБИРАТЬСЯ{}, // Ее губы медленно перебирались к его уху. (ПЕРЕБИРАТЬСЯ,ПЕРЕБРАТЬСЯ,ПЕРЕБАЗИРОВАТЬСЯ,ПЕРЕМЕСТИТЬСЯ,ПЕРЕМЕЩАТЬСЯ) rus_verbs:ПЕРЕБРАТЬСЯ{}, // ,,, rus_verbs:ПЕРЕБАЗИРОВАТЬСЯ{}, // rus_verbs:ПЕРЕМЕСТИТЬСЯ{}, // rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // rus_verbs:ТРОНУТЬСЯ{}, // Он отвернулся от нее и тронулся к пляжу. (ТРОНУТЬСЯ) rus_verbs:ПРИСТАВИТЬ{}, // Он поднял одну из них и приставил верхний конец к краю шахты в потолке. rus_verbs:ПРОБИТЬСЯ{}, // Отряд с невероятными приключениями, пытается пробиться к своему полку, попадает в плен и другие передряги (ПРОБИТЬСЯ) rus_verbs:хотеть{}, rus_verbs:СДЕЛАТЬ{}, // Сделайте всё к понедельнику (СДЕЛАТЬ) rus_verbs:ИСПЫТЫВАТЬ{}, // она испытывает ко мне только отвращение (ИСПЫТЫВАТЬ) rus_verbs:ОБЯЗЫВАТЬ{}, // Это меня ни к чему не обязывает (ОБЯЗЫВАТЬ) rus_verbs:КАРАБКАТЬСЯ{}, // карабкаться по горе от подножия к вершине (КАРАБКАТЬСЯ) rus_verbs:СТОЯТЬ{}, // мужчина стоял ко мне спиной (СТОЯТЬ) rus_verbs:ПОДАТЬСЯ{}, // наконец люк подался ко мне (ПОДАТЬСЯ) rus_verbs:ПРИРАВНЯТЬ{}, // Усилия нельзя приравнять к результату (ПРИРАВНЯТЬ) rus_verbs:ПРИРАВНИВАТЬ{}, // Усилия нельзя приравнивать к результату (ПРИРАВНИВАТЬ) rus_verbs:ВОЗЛОЖИТЬ{}, // Путин в Пскове возложил цветы к памятнику воинам-десантникам, погибшим в Чечне (ВОЗЛОЖИТЬ) rus_verbs:запустить{}, // Индия запустит к Марсу свой космический аппарат в 2013 г rus_verbs:ПРИСТЫКОВАТЬСЯ{}, // Роботизированный российский грузовой космический корабль пристыковался к МКС (ПРИСТЫКОВАТЬСЯ) rus_verbs:ПРИМАЗАТЬСЯ{}, // К челябинскому метеориту примазалась таинственная слизь (ПРИМАЗАТЬСЯ) rus_verbs:ПОПРОСИТЬ{}, // Попросите Лизу к телефону (ПОПРОСИТЬ К) rus_verbs:ПРОЕХАТЬ{}, // Порой школьные автобусы просто не имеют возможности проехать к некоторым населенным пунктам из-за бездорожья (ПРОЕХАТЬ К) rus_verbs:ПОДЦЕПЛЯТЬСЯ{}, // Вагоны с пассажирами подцепляются к составу (ПОДЦЕПЛЯТЬСЯ К) rus_verbs:ПРИЗВАТЬ{}, // Президент Афганистана призвал талибов к прямому диалогу (ПРИЗВАТЬ К) rus_verbs:ПРЕОБРАЗИТЬСЯ{}, // Культовый столичный отель преобразился к юбилею (ПРЕОБРАЗИТЬСЯ К) прилагательное:ЧУВСТВИТЕЛЬНЫЙ{}, // нейроны одного комплекса чувствительны к разным веществам (ЧУВСТВИТЕЛЬНЫЙ К) безлич_глагол:нужно{}, // нам нужно к воротам (НУЖНО К) rus_verbs:БРОСИТЬ{}, // огромный клюв бросил это мясо к моим ногам (БРОСИТЬ К) rus_verbs:ЗАКОНЧИТЬ{}, // к пяти утра техники закончили (ЗАКОНЧИТЬ К) rus_verbs:НЕСТИ{}, // к берегу нас несет! (НЕСТИ К) rus_verbs:ПРОДВИГАТЬСЯ{}, // племена медленно продвигались к востоку (ПРОДВИГАТЬСЯ К) rus_verbs:ОПУСКАТЬСЯ{}, // деревья опускались к самой воде (ОПУСКАТЬСЯ К) rus_verbs:СТЕМНЕТЬ{}, // к тому времени стемнело (СТЕМНЕЛО К) rus_verbs:ОТСКОЧИТЬ{}, // после отскочил к окну (ОТСКОЧИТЬ К) rus_verbs:ДЕРЖАТЬСЯ{}, // к солнцу держались спинами (ДЕРЖАТЬСЯ К) rus_verbs:КАЧНУТЬСЯ{}, // толпа качнулась к ступеням (КАЧНУТЬСЯ К) rus_verbs:ВОЙТИ{}, // Андрей вошел к себе (ВОЙТИ К) rus_verbs:ВЫБРАТЬСЯ{}, // мы выбрались к окну (ВЫБРАТЬСЯ К) rus_verbs:ПРОВЕСТИ{}, // провел к стене спальни (ПРОВЕСТИ К) rus_verbs:ВЕРНУТЬСЯ{}, // давай вернемся к делу (ВЕРНУТЬСЯ К) rus_verbs:ВОЗВРАТИТЬСЯ{}, // Среди евреев, живших в диаспоре, всегда было распространено сильное стремление возвратиться к Сиону (ВОЗВРАТИТЬСЯ К) rus_verbs:ПРИЛЕГАТЬ{}, // Задняя поверхность хрусталика прилегает к стекловидному телу (ПРИЛЕГАТЬ К) rus_verbs:ПЕРЕНЕСТИСЬ{}, // мысленно Алёна перенеслась к заливу (ПЕРЕНЕСТИСЬ К) rus_verbs:ПРОБИВАТЬСЯ{}, // сквозь болото к берегу пробивался ручей. (ПРОБИВАТЬСЯ К) rus_verbs:ПЕРЕВЕСТИ{}, // необходимо срочно перевести стадо к воде. (ПЕРЕВЕСТИ К) rus_verbs:ПРИЛЕТЕТЬ{}, // зачем ты прилетел к нам? (ПРИЛЕТЕТЬ К) rus_verbs:ДОБАВИТЬ{}, // добавить ли ее к остальным? (ДОБАВИТЬ К) rus_verbs:ПРИГОТОВИТЬ{}, // Матвей приготовил лук к бою. (ПРИГОТОВИТЬ К) rus_verbs:РВАНУТЬ{}, // человек рванул ее к себе. (РВАНУТЬ К) rus_verbs:ТАЩИТЬ{}, // они тащили меня к двери. (ТАЩИТЬ К) глагол:быть{}, // к тебе есть вопросы. прилагательное:равнодушный{}, // Он равнодушен к музыке. rus_verbs:ПОЖАЛОВАТЬ{}, // скандально известный певец пожаловал к нам на передачу (ПОЖАЛОВАТЬ К) rus_verbs:ПЕРЕСЕСТЬ{}, // Ольга пересела к Антону (ПЕРЕСЕСТЬ К) инфинитив:СБЕГАТЬ{ вид:соверш }, глагол:СБЕГАТЬ{ вид:соверш }, // сбегай к Борису (СБЕГАТЬ К) rus_verbs:ПЕРЕХОДИТЬ{}, // право хода переходит к Адаму (ПЕРЕХОДИТЬ К) rus_verbs:прижаться{}, // она прижалась щекой к его шее. (прижаться+к) rus_verbs:ПОДСКОЧИТЬ{}, // солдат быстро подскочил ко мне. (ПОДСКОЧИТЬ К) rus_verbs:ПРОБРАТЬСЯ{}, // нужно пробраться к реке. (ПРОБРАТЬСЯ К) rus_verbs:ГОТОВИТЬ{}, // нас готовили к этому. (ГОТОВИТЬ К) rus_verbs:ТЕЧЬ{}, // река текла к морю. (ТЕЧЬ К) rus_verbs:ОТШАТНУТЬСЯ{}, // епископ отшатнулся к стене. (ОТШАТНУТЬСЯ К) rus_verbs:БРАТЬ{}, // брали бы к себе. (БРАТЬ К) rus_verbs:СКОЛЬЗНУТЬ{}, // ковер скользнул к пещере. (СКОЛЬЗНУТЬ К) rus_verbs:присохнуть{}, // Грязь присохла к одежде. (присохнуть к) rus_verbs:просить{}, // Директор просит вас к себе. (просить к) rus_verbs:вызывать{}, // шеф вызывал к себе. (вызывать к) rus_verbs:присесть{}, // старик присел к огню. (присесть к) rus_verbs:НАКЛОНИТЬСЯ{}, // Ричард наклонился к брату. (НАКЛОНИТЬСЯ К) rus_verbs:выбираться{}, // будем выбираться к дороге. (выбираться к) rus_verbs:отвернуться{}, // Виктор отвернулся к стене. (отвернуться к) rus_verbs:СТИХНУТЬ{}, // огонь стих к полудню. (СТИХНУТЬ К) rus_verbs:УПАСТЬ{}, // нож упал к ногам. (УПАСТЬ К) rus_verbs:СЕСТЬ{}, // молча сел к огню. (СЕСТЬ К) rus_verbs:ХЛЫНУТЬ{}, // народ хлынул к стенам. (ХЛЫНУТЬ К) rus_verbs:покатиться{}, // они черной волной покатились ко мне. (покатиться к) rus_verbs:ОБРАТИТЬ{}, // она обратила к нему свое бледное лицо. (ОБРАТИТЬ К) rus_verbs:СКЛОНИТЬ{}, // Джон слегка склонил голову к плечу. (СКЛОНИТЬ К) rus_verbs:СВЕРНУТЬ{}, // дорожка резко свернула к южной стене. (СВЕРНУТЬ К) rus_verbs:ЗАВЕРНУТЬ{}, // Он завернул к нам по пути к месту службы. (ЗАВЕРНУТЬ К) rus_verbs:подходить{}, // цвет подходил ей к лицу. rus_verbs:БРЕСТИ{}, // Ричард покорно брел к отцу. (БРЕСТИ К) rus_verbs:ПОПАСТЬ{}, // хочешь попасть к нему? (ПОПАСТЬ К) rus_verbs:ПОДНЯТЬ{}, // Мартин поднял ружье к плечу. (ПОДНЯТЬ К) rus_verbs:ПОТЕРЯТЬ{}, // просто потеряла к нему интерес. (ПОТЕРЯТЬ К) rus_verbs:РАЗВЕРНУТЬСЯ{}, // они сразу развернулись ко мне. (РАЗВЕРНУТЬСЯ К) rus_verbs:ПОВЕРНУТЬ{}, // мальчик повернул к ним голову. (ПОВЕРНУТЬ К) rus_verbs:вызвать{}, // или вызвать к жизни? (вызвать к) rus_verbs:ВЫХОДИТЬ{}, // их земли выходят к морю. (ВЫХОДИТЬ К) rus_verbs:ЕХАТЬ{}, // мы долго ехали к вам. (ЕХАТЬ К) rus_verbs:опуститься{}, // Алиса опустилась к самому дну. (опуститься к) rus_verbs:подняться{}, // они молча поднялись к себе. (подняться к) rus_verbs:ДВИНУТЬСЯ{}, // толстяк тяжело двинулся к ним. (ДВИНУТЬСЯ К) rus_verbs:ПОПЯТИТЬСЯ{}, // ведьмак осторожно попятился к лошади. (ПОПЯТИТЬСЯ К) rus_verbs:РИНУТЬСЯ{}, // мышелов ринулся к черной стене. (РИНУТЬСЯ К) rus_verbs:ТОЛКНУТЬ{}, // к этому толкнул ее ты. (ТОЛКНУТЬ К) rus_verbs:отпрыгнуть{}, // Вадим поспешно отпрыгнул к борту. (отпрыгнуть к) rus_verbs:отступить{}, // мы поспешно отступили к стене. (отступить к) rus_verbs:ЗАБРАТЬ{}, // мы забрали их к себе. (ЗАБРАТЬ к) rus_verbs:ВЗЯТЬ{}, // потом возьму тебя к себе. (ВЗЯТЬ К) rus_verbs:лежать{}, // наш путь лежал к ним. (лежать к) rus_verbs:поползти{}, // ее рука поползла к оружию. (поползти к) rus_verbs:требовать{}, // вас требует к себе император. (требовать к) rus_verbs:поехать{}, // ты должен поехать к нему. (поехать к) rus_verbs:тянуться{}, // мордой животное тянулось к земле. (тянуться к) rus_verbs:ЖДАТЬ{}, // жди их завтра к утру. (ЖДАТЬ К) rus_verbs:ПОЛЕТЕТЬ{}, // они стремительно полетели к земле. (ПОЛЕТЕТЬ К) rus_verbs:подойти{}, // помоги мне подойти к столу. (подойти к) rus_verbs:РАЗВЕРНУТЬ{}, // мужик развернул к нему коня. (РАЗВЕРНУТЬ К) rus_verbs:ПРИВЕЗТИ{}, // нас привезли прямо к королю. (ПРИВЕЗТИ К) rus_verbs:отпрянуть{}, // незнакомец отпрянул к стене. (отпрянуть к) rus_verbs:побежать{}, // Cергей побежал к двери. (побежать к) rus_verbs:отбросить{}, // сильный удар отбросил его к стене. (отбросить к) rus_verbs:ВЫНУДИТЬ{}, // они вынудили меня к сотрудничеству (ВЫНУДИТЬ К) rus_verbs:подтянуть{}, // он подтянул к себе стул и сел на него (подтянуть к) rus_verbs:сойти{}, // по узкой тропинке путники сошли к реке. (сойти к) rus_verbs:являться{}, // по ночам к нему являлись призраки. (являться к) rus_verbs:ГНАТЬ{}, // ледяной ветер гнал их к югу. (ГНАТЬ К) rus_verbs:ВЫВЕСТИ{}, // она вывела нас точно к месту. (ВЫВЕСТИ К) rus_verbs:выехать{}, // почти сразу мы выехали к реке. rus_verbs:пододвигаться{}, // пододвигайся к окну rus_verbs:броситься{}, // большая часть защитников стен бросилась к воротам. rus_verbs:представить{}, // Его представили к ордену. rus_verbs:двигаться{}, // между тем чудище неторопливо двигалось к берегу. rus_verbs:выскочить{}, // тем временем они выскочили к реке. rus_verbs:выйти{}, // тем временем они вышли к лестнице. rus_verbs:потянуть{}, // Мальчик схватил верёвку и потянул её к себе. rus_verbs:приложить{}, // приложить к детали повышенное усилие rus_verbs:пройти{}, // пройти к стойке регистрации (стойка регистрации - проверить проверку) rus_verbs:отнестись{}, // отнестись к животным с сочуствием rus_verbs:привязать{}, // привязать за лапу веревкой к колышку, воткнутому в землю rus_verbs:прыгать{}, // прыгать к хозяину на стол rus_verbs:приглашать{}, // приглашать к доктору rus_verbs:рваться{}, // Чужие люди рвутся к власти rus_verbs:понестись{}, // понестись к обрыву rus_verbs:питать{}, // питать привязанность к алкоголю rus_verbs:заехать{}, // Коля заехал к Оле rus_verbs:переехать{}, // переехать к родителям rus_verbs:ползти{}, // ползти к дороге rus_verbs:сводиться{}, // сводиться к элементарному действию rus_verbs:добавлять{}, // добавлять к общей сумме rus_verbs:подбросить{}, // подбросить к потолку rus_verbs:призывать{}, // призывать к спокойствию rus_verbs:пробираться{}, // пробираться к партизанам rus_verbs:отвезти{}, // отвезти к родителям rus_verbs:применяться{}, // применяться к уравнению rus_verbs:сходиться{}, // сходиться к точному решению rus_verbs:допускать{}, // допускать к сдаче зачета rus_verbs:свести{}, // свести к нулю rus_verbs:придвинуть{}, // придвинуть к мальчику rus_verbs:подготовить{}, // подготовить к печати rus_verbs:подобраться{}, // подобраться к оленю rus_verbs:заторопиться{}, // заторопиться к выходу rus_verbs:пристать{}, // пристать к берегу rus_verbs:поманить{}, // поманить к себе rus_verbs:припасть{}, // припасть к алтарю rus_verbs:притащить{}, // притащить к себе домой rus_verbs:прижимать{}, // прижимать к груди rus_verbs:подсесть{}, // подсесть к симпатичной девочке rus_verbs:придвинуться{}, // придвинуться к окну rus_verbs:отпускать{}, // отпускать к другу rus_verbs:пригнуться{}, // пригнуться к земле rus_verbs:пристроиться{}, // пристроиться к колонне rus_verbs:сгрести{}, // сгрести к себе rus_verbs:удрать{}, // удрать к цыганам rus_verbs:прибавиться{}, // прибавиться к общей сумме rus_verbs:присмотреться{}, // присмотреться к покупке rus_verbs:подкатить{}, // подкатить к трюму rus_verbs:клонить{}, // клонить ко сну rus_verbs:проследовать{}, // проследовать к выходу rus_verbs:пододвинуть{}, // пододвинуть к себе rus_verbs:применять{}, // применять к сотрудникам rus_verbs:прильнуть{}, // прильнуть к экранам rus_verbs:подвинуть{}, // подвинуть к себе rus_verbs:примчаться{}, // примчаться к папе rus_verbs:подкрасться{}, // подкрасться к жертве rus_verbs:привязаться{}, // привязаться к собаке rus_verbs:забирать{}, // забирать к себе rus_verbs:прорваться{}, // прорваться к кассе rus_verbs:прикасаться{}, // прикасаться к коже rus_verbs:уносить{}, // уносить к себе rus_verbs:подтянуться{}, // подтянуться к месту rus_verbs:привозить{}, // привозить к ветеринару rus_verbs:подползти{}, // подползти к зайцу rus_verbs:приблизить{}, // приблизить к глазам rus_verbs:применить{}, // применить к уравнению простое преобразование rus_verbs:приглядеться{}, // приглядеться к изображению rus_verbs:приложиться{}, // приложиться к ручке rus_verbs:приставать{}, // приставать к девчонкам rus_verbs:запрещаться{}, // запрещаться к показу rus_verbs:прибегать{}, // прибегать к насилию rus_verbs:побудить{}, // побудить к действиям rus_verbs:притягивать{}, // притягивать к себе rus_verbs:пристроить{}, // пристроить к полезному делу rus_verbs:приговорить{}, // приговорить к смерти rus_verbs:склоняться{}, // склоняться к прекращению разработки rus_verbs:подъезжать{}, // подъезжать к вокзалу rus_verbs:привалиться{}, // привалиться к забору rus_verbs:наклоняться{}, // наклоняться к щенку rus_verbs:подоспеть{}, // подоспеть к обеду rus_verbs:прилипнуть{}, // прилипнуть к окну rus_verbs:приволочь{}, // приволочь к себе rus_verbs:устремляться{}, // устремляться к вершине rus_verbs:откатиться{}, // откатиться к исходным позициям rus_verbs:побуждать{}, // побуждать к действиям rus_verbs:прискакать{}, // прискакать к кормежке rus_verbs:присматриваться{}, // присматриваться к новичку rus_verbs:прижиматься{}, // прижиматься к борту rus_verbs:жаться{}, // жаться к огню rus_verbs:передвинуть{}, // передвинуть к окну rus_verbs:допускаться{}, // допускаться к экзаменам rus_verbs:прикрепить{}, // прикрепить к корпусу rus_verbs:отправлять{}, // отправлять к специалистам rus_verbs:перебежать{}, // перебежать к врагам rus_verbs:притронуться{}, // притронуться к реликвии rus_verbs:заспешить{}, // заспешить к семье rus_verbs:ревновать{}, // ревновать к сопернице rus_verbs:подступить{}, // подступить к горлу rus_verbs:уводить{}, // уводить к ветеринару rus_verbs:побросать{}, // побросать к ногам rus_verbs:подаваться{}, // подаваться к ужину rus_verbs:приписывать{}, // приписывать к достижениям rus_verbs:относить{}, // относить к растениям rus_verbs:принюхаться{}, // принюхаться к ароматам rus_verbs:подтащить{}, // подтащить к себе rus_verbs:прислонить{}, // прислонить к стене rus_verbs:подплыть{}, // подплыть к бую rus_verbs:опаздывать{}, // опаздывать к стилисту rus_verbs:примкнуть{}, // примкнуть к деомнстрантам rus_verbs:стекаться{}, // стекаются к стенам тюрьмы rus_verbs:подготовиться{}, // подготовиться к марафону rus_verbs:приглядываться{}, // приглядываться к новичку rus_verbs:присоединяться{}, // присоединяться к сообществу rus_verbs:клониться{}, // клониться ко сну rus_verbs:привыкать{}, // привыкать к хорошему rus_verbs:принудить{}, // принудить к миру rus_verbs:уплыть{}, // уплыть к далекому берегу rus_verbs:утащить{}, // утащить к детенышам rus_verbs:приплыть{}, // приплыть к финишу rus_verbs:подбегать{}, // подбегать к хозяину rus_verbs:лишаться{}, // лишаться средств к существованию rus_verbs:приступать{}, // приступать к операции rus_verbs:пробуждать{}, // пробуждать лекцией интерес к математике rus_verbs:подключить{}, // подключить к трубе rus_verbs:подключиться{}, // подключиться к сети rus_verbs:прилить{}, // прилить к лицу rus_verbs:стучаться{}, // стучаться к соседям rus_verbs:пристегнуть{}, // пристегнуть к креслу rus_verbs:присоединить{}, // присоединить к сети rus_verbs:отбежать{}, // отбежать к противоположной стене rus_verbs:подвезти{}, // подвезти к набережной rus_verbs:прибегнуть{}, // прибегнуть к хитрости rus_verbs:приучить{}, // приучить к туалету rus_verbs:подталкивать{}, // подталкивать к выходу rus_verbs:прорываться{}, // прорываться к выходу rus_verbs:увозить{}, // увозить к ветеринару rus_verbs:засеменить{}, // засеменить к выходу rus_verbs:крепиться{}, // крепиться к потолку rus_verbs:прибрать{}, // прибрать к рукам rus_verbs:пристраститься{}, // пристраститься к наркотикам rus_verbs:поспеть{}, // поспеть к обеду rus_verbs:привязывать{}, // привязывать к дереву rus_verbs:прилагать{}, // прилагать к документам rus_verbs:переправить{}, // переправить к дедушке rus_verbs:подогнать{}, // подогнать к воротам rus_verbs:тяготеть{}, // тяготеть к социализму rus_verbs:подбираться{}, // подбираться к оленю rus_verbs:подступать{}, // подступать к горлу rus_verbs:примыкать{}, // примыкать к первому элементу rus_verbs:приладить{}, // приладить к велосипеду rus_verbs:подбрасывать{}, // подбрасывать к потолку rus_verbs:перевозить{}, // перевозить к новому месту дислокации rus_verbs:усаживаться{}, // усаживаться к окну rus_verbs:приближать{}, // приближать к глазам rus_verbs:попроситься{}, // попроситься к бабушке rus_verbs:прибить{}, // прибить к доске rus_verbs:перетащить{}, // перетащить к себе rus_verbs:прицепить{}, // прицепить к паровозу rus_verbs:прикладывать{}, // прикладывать к ране rus_verbs:устареть{}, // устареть к началу войны rus_verbs:причалить{}, // причалить к пристани rus_verbs:приспособиться{}, // приспособиться к опозданиям rus_verbs:принуждать{}, // принуждать к миру rus_verbs:соваться{}, // соваться к директору rus_verbs:протолкаться{}, // протолкаться к прилавку rus_verbs:приковать{}, // приковать к батарее rus_verbs:подкрадываться{}, // подкрадываться к суслику rus_verbs:подсадить{}, // подсадить к арестонту rus_verbs:прикатить{}, // прикатить к финишу rus_verbs:протащить{}, // протащить к владыке rus_verbs:сужаться{}, // сужаться к основанию rus_verbs:присовокупить{}, // присовокупить к пожеланиям rus_verbs:пригвоздить{}, // пригвоздить к доске rus_verbs:отсылать{}, // отсылать к первоисточнику rus_verbs:изготовиться{}, // изготовиться к прыжку rus_verbs:прилагаться{}, // прилагаться к покупке rus_verbs:прицепиться{}, // прицепиться к вагону rus_verbs:примешиваться{}, // примешиваться к вину rus_verbs:переселить{}, // переселить к старшекурсникам rus_verbs:затрусить{}, // затрусить к выходе rus_verbs:приспособить{}, // приспособить к обогреву rus_verbs:примериться{}, // примериться к аппарату rus_verbs:прибавляться{}, // прибавляться к пенсии rus_verbs:подкатиться{}, // подкатиться к воротам rus_verbs:стягивать{}, // стягивать к границе rus_verbs:дописать{}, // дописать к роману rus_verbs:подпустить{}, // подпустить к корове rus_verbs:склонять{}, // склонять к сотрудничеству rus_verbs:припечатать{}, // припечатать к стене rus_verbs:охладеть{}, // охладеть к музыке rus_verbs:пришить{}, // пришить к шинели rus_verbs:принюхиваться{}, // принюхиваться к ветру rus_verbs:подрулить{}, // подрулить к барышне rus_verbs:наведаться{}, // наведаться к оракулу rus_verbs:клеиться{}, // клеиться к конверту rus_verbs:перетянуть{}, // перетянуть к себе rus_verbs:переметнуться{}, // переметнуться к конкурентам rus_verbs:липнуть{}, // липнуть к сокурсницам rus_verbs:поковырять{}, // поковырять к выходу rus_verbs:подпускать{}, // подпускать к пульту управления rus_verbs:присосаться{}, // присосаться к источнику rus_verbs:приклеить{}, // приклеить к стеклу rus_verbs:подтягивать{}, // подтягивать к себе rus_verbs:подкатывать{}, // подкатывать к даме rus_verbs:притрагиваться{}, // притрагиваться к опухоли rus_verbs:слетаться{}, // слетаться к водопою rus_verbs:хаживать{}, // хаживать к батюшке rus_verbs:привлекаться{}, // привлекаться к административной ответственности rus_verbs:подзывать{}, // подзывать к себе rus_verbs:прикладываться{}, // прикладываться к иконе rus_verbs:подтягиваться{}, // подтягиваться к парламенту rus_verbs:прилепить{}, // прилепить к стенке холодильника rus_verbs:пододвинуться{}, // пододвинуться к экрану rus_verbs:приползти{}, // приползти к дереву rus_verbs:запаздывать{}, // запаздывать к обеду rus_verbs:припереть{}, // припереть к стене rus_verbs:нагибаться{}, // нагибаться к цветку инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять к воротам деепричастие:сгоняв{}, rus_verbs:поковылять{}, // поковылять к выходу rus_verbs:привалить{}, // привалить к столбу rus_verbs:отпроситься{}, // отпроситься к родителям rus_verbs:приспосабливаться{}, // приспосабливаться к новым условиям rus_verbs:прилипать{}, // прилипать к рукам rus_verbs:подсоединить{}, // подсоединить к приборам rus_verbs:приливать{}, // приливать к голове rus_verbs:подселить{}, // подселить к другим новичкам rus_verbs:прилепиться{}, // прилепиться к шкуре rus_verbs:подлетать{}, // подлетать к пункту назначения rus_verbs:пристегнуться{}, // пристегнуться к креслу ремнями rus_verbs:прибиться{}, // прибиться к стае, улетающей на юг rus_verbs:льнуть{}, // льнуть к заботливому хозяину rus_verbs:привязываться{}, // привязываться к любящему хозяину rus_verbs:приклеиться{}, // приклеиться к спине rus_verbs:стягиваться{}, // стягиваться к сенату rus_verbs:подготавливать{}, // подготавливать к выходу на арену rus_verbs:приглашаться{}, // приглашаться к доктору rus_verbs:причислять{}, // причислять к отличникам rus_verbs:приколоть{}, // приколоть к лацкану rus_verbs:наклонять{}, // наклонять к горизонту rus_verbs:припадать{}, // припадать к первоисточнику rus_verbs:приобщиться{}, // приобщиться к культурному наследию rus_verbs:придираться{}, // придираться к мелким ошибкам rus_verbs:приучать{}, // приучать к лотку rus_verbs:промотать{}, // промотать к началу rus_verbs:прихлынуть{}, // прихлынуть к голове rus_verbs:пришвартоваться{}, // пришвартоваться к первому пирсу rus_verbs:прикрутить{}, // прикрутить к велосипеду rus_verbs:подплывать{}, // подплывать к лодке rus_verbs:приравниваться{}, // приравниваться к побегу rus_verbs:подстрекать{}, // подстрекать к вооруженной борьбе с оккупантами rus_verbs:изготовляться{}, // изготовляться к прыжку из стратосферы rus_verbs:приткнуться{}, // приткнуться к первой группе туристов rus_verbs:приручить{}, // приручить котика к лотку rus_verbs:приковывать{}, // приковывать к себе все внимание прессы rus_verbs:приготовляться{}, // приготовляться к первому экзамену rus_verbs:остыть{}, // Вода остынет к утру. rus_verbs:приехать{}, // Он приедет к концу будущей недели. rus_verbs:подсаживаться{}, rus_verbs:успевать{}, // успевать к стилисту rus_verbs:привлекать{}, // привлекать к себе внимание прилагательное:устойчивый{}, // переводить в устойчивую к перегреву форму rus_verbs:прийтись{}, // прийтись ко двору инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована к условиям крайнего севера инфинитив:адаптировать{вид:соверш}, глагол:адаптировать{вид:несоверш}, глагол:адаптировать{вид:соверш}, деепричастие:адаптировав{}, деепричастие:адаптируя{}, прилагательное:адаптирующий{}, прилагательное:адаптировавший{ вид:соверш }, //+прилагательное:адаптировавший{ вид:несоверш }, прилагательное:адаптированный{}, инфинитив:адаптироваться{вид:соверш}, // тело адаптировалось к условиям суровой зимы инфинитив:адаптироваться{вид:несоверш}, глагол:адаптироваться{вид:соверш}, глагол:адаптироваться{вид:несоверш}, деепричастие:адаптировавшись{}, деепричастие:адаптируясь{}, прилагательное:адаптировавшийся{вид:соверш}, //+прилагательное:адаптировавшийся{вид:несоверш}, прилагательное:адаптирующийся{}, rus_verbs:апеллировать{}, // оратор апеллировал к патриотизму своих слушателей rus_verbs:близиться{}, // Шторм близится к побережью rus_verbs:доставить{}, // Эскиз ракеты, способной доставить корабль к Луне rus_verbs:буксировать{}, // Буксир буксирует танкер к месту стоянки rus_verbs:причислить{}, // Мы причислили его к числу экспертов rus_verbs:вести{}, // Наша партия ведет народ к процветанию rus_verbs:взывать{}, // Учителя взывают к совести хулигана rus_verbs:воззвать{}, // воззвать соплеменников к оружию rus_verbs:возревновать{}, // возревновать к поклонникам rus_verbs:воспылать{}, // Коля воспылал к Оле страстной любовью rus_verbs:восходить{}, // восходить к вершине rus_verbs:восшествовать{}, // восшествовать к вершине rus_verbs:успеть{}, // успеть к обеду rus_verbs:повернуться{}, // повернуться к кому-то rus_verbs:обратиться{}, // обратиться к охраннику rus_verbs:звать{}, // звать к столу rus_verbs:отправиться{}, // отправиться к парикмахеру rus_verbs:обернуться{}, // обернуться к зовущему rus_verbs:явиться{}, // явиться к следователю rus_verbs:уехать{}, // уехать к родне rus_verbs:прибыть{}, // прибыть к перекличке rus_verbs:привыкнуть{}, // привыкнуть к голоду rus_verbs:уходить{}, // уходить к цыганам rus_verbs:привести{}, // привести к себе rus_verbs:шагнуть{}, // шагнуть к славе rus_verbs:относиться{}, // относиться к прежним периодам rus_verbs:подослать{}, // подослать к врагам rus_verbs:поспешить{}, // поспешить к обеду rus_verbs:зайти{}, // зайти к подруге rus_verbs:позвать{}, // позвать к себе rus_verbs:потянуться{}, // потянуться к рычагам rus_verbs:пускать{}, // пускать к себе rus_verbs:отвести{}, // отвести к врачу rus_verbs:приблизиться{}, // приблизиться к решению задачи rus_verbs:прижать{}, // прижать к стене rus_verbs:отправить{}, // отправить к доктору rus_verbs:падать{}, // падать к многолетним минимумам rus_verbs:полезть{}, // полезть к дерущимся rus_verbs:лезть{}, // Ты сама ко мне лезла! rus_verbs:направить{}, // направить к майору rus_verbs:приводить{}, // приводить к дантисту rus_verbs:кинуться{}, // кинуться к двери rus_verbs:поднести{}, // поднести к глазам rus_verbs:подниматься{}, // подниматься к себе rus_verbs:прибавить{}, // прибавить к результату rus_verbs:зашагать{}, // зашагать к выходу rus_verbs:склониться{}, // склониться к земле rus_verbs:стремиться{}, // стремиться к вершине rus_verbs:лететь{}, // лететь к родственникам rus_verbs:ездить{}, // ездить к любовнице rus_verbs:приближаться{}, // приближаться к финише rus_verbs:помчаться{}, // помчаться к стоматологу rus_verbs:прислушаться{}, // прислушаться к происходящему rus_verbs:изменить{}, // изменить к лучшему собственную жизнь rus_verbs:проявить{}, // проявить к погибшим сострадание rus_verbs:подбежать{}, // подбежать к упавшему rus_verbs:терять{}, // терять к партнерам доверие rus_verbs:пропустить{}, // пропустить к певцу rus_verbs:подвести{}, // подвести к глазам rus_verbs:меняться{}, // меняться к лучшему rus_verbs:заходить{}, // заходить к другу rus_verbs:рвануться{}, // рвануться к воде rus_verbs:привлечь{}, // привлечь к себе внимание rus_verbs:присоединиться{}, // присоединиться к сети rus_verbs:приезжать{}, // приезжать к дедушке rus_verbs:дернуться{}, // дернуться к борту rus_verbs:подъехать{}, // подъехать к воротам rus_verbs:готовиться{}, // готовиться к дождю rus_verbs:убежать{}, // убежать к маме rus_verbs:поднимать{}, // поднимать к источнику сигнала rus_verbs:отослать{}, // отослать к руководителю rus_verbs:приготовиться{}, // приготовиться к худшему rus_verbs:приступить{}, // приступить к выполнению обязанностей rus_verbs:метнуться{}, // метнуться к фонтану rus_verbs:прислушиваться{}, // прислушиваться к голосу разума rus_verbs:побрести{}, // побрести к выходу rus_verbs:мчаться{}, // мчаться к успеху rus_verbs:нестись{}, // нестись к обрыву rus_verbs:попадать{}, // попадать к хорошему костоправу rus_verbs:опоздать{}, // опоздать к психотерапевту rus_verbs:посылать{}, // посылать к доктору rus_verbs:поплыть{}, // поплыть к берегу rus_verbs:подтолкнуть{}, // подтолкнуть к активной работе rus_verbs:отнести{}, // отнести животное к ветеринару rus_verbs:прислониться{}, // прислониться к стволу rus_verbs:наклонить{}, // наклонить к миске с молоком rus_verbs:прикоснуться{}, // прикоснуться к поверхности rus_verbs:увезти{}, // увезти к бабушке rus_verbs:заканчиваться{}, // заканчиваться к концу путешествия rus_verbs:подозвать{}, // подозвать к себе rus_verbs:улететь{}, // улететь к теплым берегам rus_verbs:ложиться{}, // ложиться к мужу rus_verbs:убираться{}, // убираться к чертовой бабушке rus_verbs:класть{}, // класть к другим документам rus_verbs:доставлять{}, // доставлять к подъезду rus_verbs:поворачиваться{}, // поворачиваться к источнику шума rus_verbs:заглядывать{}, // заглядывать к любовнице rus_verbs:занести{}, // занести к заказчикам rus_verbs:прибежать{}, // прибежать к папе rus_verbs:притянуть{}, // притянуть к причалу rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму rus_verbs:подать{}, // он подал лимузин к подъезду rus_verbs:подавать{}, // она подавала соус к мясу rus_verbs:приобщаться{}, // приобщаться к культуре прилагательное:неспособный{}, // Наша дочка неспособна к учению. прилагательное:неприспособленный{}, // Эти устройства неприспособлены к работе в жару прилагательное:предназначенный{}, // Старый дом предназначен к сносу. прилагательное:внимательный{}, // Она всегда внимательна к гостям. прилагательное:назначенный{}, // Дело назначено к докладу. прилагательное:разрешенный{}, // Эта книга разрешена к печати. прилагательное:снисходительный{}, // Этот учитель снисходителен к ученикам. прилагательное:готовый{}, // Я готов к экзаменам. прилагательное:требовательный{}, // Он очень требователен к себе. прилагательное:жадный{}, // Он жаден к деньгам. прилагательное:глухой{}, // Он глух к моей просьбе. прилагательное:добрый{}, // Он добр к детям. rus_verbs:проявлять{}, // Он всегда проявлял живой интерес к нашим делам. rus_verbs:плыть{}, // Пароход плыл к берегу. rus_verbs:пойти{}, // я пошел к доктору rus_verbs:придти{}, // придти к выводу rus_verbs:заглянуть{}, // Я заглянул к вам мимоходом. rus_verbs:принадлежать{}, // Это существо принадлежит к разряду растений. rus_verbs:подготавливаться{}, // Ученики подготавливаются к экзаменам. rus_verbs:спускаться{}, // Улица круто спускается к реке. rus_verbs:спуститься{}, // Мы спустились к реке. rus_verbs:пустить{}, // пускать ко дну rus_verbs:приговаривать{}, // Мы приговариваем тебя к пожизненному веселью! rus_verbs:отойти{}, // Дом отошёл к племяннику. rus_verbs:отходить{}, // Коля отходил ко сну. rus_verbs:приходить{}, // местные жители к нему приходили лечиться rus_verbs:кидаться{}, // не кидайся к столу rus_verbs:ходить{}, // Она простудилась и сегодня ходила к врачу. rus_verbs:закончиться{}, // Собрание закончилось к вечеру. rus_verbs:послать{}, // Они выбрали своих депутатов и послали их к заведующему. rus_verbs:направиться{}, // Мы сошли на берег и направились к городу. rus_verbs:направляться{}, rus_verbs:свестись{}, // Всё свелось к нулю. rus_verbs:прислать{}, // Пришлите кого-нибудь к ней. rus_verbs:присылать{}, // Он присылал к должнику своих головорезов rus_verbs:подлететь{}, // Самолёт подлетел к лесу. rus_verbs:возвращаться{}, // он возвращается к старой работе глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, деепричастие:находясь{}, прилагательное:находившийся{}, прилагательное:находящийся{}, // Япония находится к востоку от Китая. rus_verbs:возвращать{}, // возвращать к жизни rus_verbs:располагать{}, // Атмосфера располагает к работе. rus_verbs:возвратить{}, // Колокольный звон возвратил меня к прошлому. rus_verbs:поступить{}, // К нам поступила жалоба. rus_verbs:поступать{}, // К нам поступают жалобы. rus_verbs:прыгнуть{}, // Белка прыгнула к дереву rus_verbs:торопиться{}, // пассажиры торопятся к выходу rus_verbs:поторопиться{}, // поторопитесь к выходу rus_verbs:вернуть{}, // вернуть к активной жизни rus_verbs:припирать{}, // припирать к стенке rus_verbs:проваливать{}, // Проваливай ко всем чертям! rus_verbs:вбежать{}, // Коля вбежал ко мне rus_verbs:вбегать{}, // Коля вбегал ко мне глагол:забегать{ вид:несоверш }, // Коля забегал ко мне rus_verbs:постучаться{}, // Коля постучался ко мне. rus_verbs:повести{}, // Спросил я озорного Антонио и повел его к дому rus_verbs:понести{}, // Мы понесли кота к ветеринару rus_verbs:принести{}, // Я принес кота к ветеринару rus_verbs:устремиться{}, // Мы устремились к ручью. rus_verbs:подводить{}, // Учитель подводил детей к аквариуму rus_verbs:следовать{}, // Я получил приказ следовать к месту нового назначения. rus_verbs:пригласить{}, // Я пригласил к себе товарищей. rus_verbs:собираться{}, // Я собираюсь к тебе в гости. rus_verbs:собраться{}, // Маша собралась к дантисту rus_verbs:сходить{}, // Я схожу к врачу. rus_verbs:идти{}, // Маша уверенно шла к Пете rus_verbs:измениться{}, // Основные индексы рынка акций РФ почти не изменились к закрытию. rus_verbs:отыграть{}, // Российский рынок акций отыграл падение к закрытию. rus_verbs:заканчивать{}, // Заканчивайте к обеду rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время rus_verbs:окончить{}, // rus_verbs:дозвониться{}, // Я не мог к вам дозвониться. глагол:прийти{}, инфинитив:прийти{}, // Антонио пришел к Элеонор rus_verbs:уйти{}, // Антонио ушел к Элеонор rus_verbs:бежать{}, // Антонио бежит к Элеонор rus_verbs:спешить{}, // Антонио спешит к Элеонор rus_verbs:скакать{}, // Антонио скачет к Элеонор rus_verbs:красться{}, // Антонио крадётся к Элеонор rus_verbs:поскакать{}, // беглецы поскакали к холмам rus_verbs:перейти{} // Антонио перешел к Элеонор } fact гл_предл { if context { Гл_К_Дат предлог:к{} *:*{ падеж:дат } } then return true } fact гл_предл { if context { Гл_К_Дат предлог:к{} @regex("[a-z]+[0-9]*") } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:к{} *:*{} } then return false,-5 } #endregion Предлог_К #region Предлог_ДЛЯ // ------------------- С ПРЕДЛОГОМ 'ДЛЯ' ---------------------- wordentry_set Гл_ДЛЯ_Род={ частица:нет{}, // для меня нет других путей. частица:нету{}, rus_verbs:ЗАДЕРЖАТЬ{}, // полиция может задержать их для выяснения всех обстоятельств и дальнейшего опознания. (ЗАДЕРЖАТЬ) rus_verbs:ДЕЛАТЬСЯ{}, // это делалось для людей (ДЕЛАТЬСЯ) rus_verbs:обернуться{}, // обернулась для греческого рынка труда банкротствами предприятий и масштабными сокращениями (обернуться) rus_verbs:ПРЕДНАЗНАЧАТЬСЯ{}, // Скорее всего тяжелый клинок вообще не предназначался для бросков (ПРЕДНАЗНАЧАТЬСЯ) rus_verbs:ПОЛУЧИТЬ{}, // ты можешь получить его для нас? (ПОЛУЧИТЬ) rus_verbs:ПРИДУМАТЬ{}, // Ваш босс уже придумал для нас веселенькую смерть. (ПРИДУМАТЬ) rus_verbs:оказаться{}, // это оказалось для них тяжелой задачей rus_verbs:ГОВОРИТЬ{}, // теперь она говорила для нас обоих (ГОВОРИТЬ) rus_verbs:ОСВОБОДИТЬ{}, // освободить ее для тебя? (ОСВОБОДИТЬ) rus_verbs:работать{}, // Мы работаем для тех, кто ценит удобство rus_verbs:СТАТЬ{}, // кем она станет для него? (СТАТЬ) rus_verbs:ЯВИТЬСЯ{}, // вы для этого явились сюда? (ЯВИТЬСЯ) rus_verbs:ПОТЕРЯТЬ{}, // жизнь потеряла для меня всякий смысл (ПОТЕРЯТЬ) rus_verbs:УТРАТИТЬ{}, // мой мир утратил для меня всякое подобие смысла (УТРАТИТЬ) rus_verbs:ДОСТАТЬ{}, // ты должен достать ее для меня! (ДОСТАТЬ) rus_verbs:БРАТЬ{}, // некоторые берут для себя (БРАТЬ) rus_verbs:ИМЕТЬ{}, // имею для вас новость (ИМЕТЬ) rus_verbs:ЖДАТЬ{}, // тебя ждут для разговора (ЖДАТЬ) rus_verbs:ПРОПАСТЬ{}, // совсем пропал для мира (ПРОПАСТЬ) rus_verbs:ПОДНЯТЬ{}, // нас подняли для охоты (ПОДНЯТЬ) rus_verbs:ОСТАНОВИТЬСЯ{}, // время остановилось для нее (ОСТАНОВИТЬСЯ) rus_verbs:НАЧИНАТЬСЯ{}, // для него начинается новая жизнь (НАЧИНАТЬСЯ) rus_verbs:КОНЧИТЬСЯ{}, // кончились для него эти игрушки (КОНЧИТЬСЯ) rus_verbs:НАСТАТЬ{}, // для него настало время действовать (НАСТАТЬ) rus_verbs:СТРОИТЬ{}, // для молодых строили новый дом (СТРОИТЬ) rus_verbs:ВЗЯТЬ{}, // возьми для защиты этот меч (ВЗЯТЬ) rus_verbs:ВЫЯСНИТЬ{}, // попытаюсь выяснить для вас всю цепочку (ВЫЯСНИТЬ) rus_verbs:ПРИГОТОВИТЬ{}, // давай попробуем приготовить для них сюрприз (ПРИГОТОВИТЬ) rus_verbs:ПОДХОДИТЬ{}, // берег моря мертвых подходил для этого идеально (ПОДХОДИТЬ) rus_verbs:ОСТАТЬСЯ{}, // внешний вид этих тварей остался для нас загадкой (ОСТАТЬСЯ) rus_verbs:ПРИВЕЗТИ{}, // для меня привезли пиво (ПРИВЕЗТИ) прилагательное:ХАРАКТЕРНЫЙ{}, // Для всей территории края характерен умеренный континентальный климат (ХАРАКТЕРНЫЙ) rus_verbs:ПРИВЕСТИ{}, // для меня белую лошадь привели (ПРИВЕСТИ ДЛЯ) rus_verbs:ДЕРЖАТЬ{}, // их держат для суда (ДЕРЖАТЬ ДЛЯ) rus_verbs:ПРЕДОСТАВИТЬ{}, // вьетнамец предоставил для мигрантов места проживания в ряде вологодских общежитий (ПРЕДОСТАВИТЬ ДЛЯ) rus_verbs:ПРИДУМЫВАТЬ{}, // придумывая для этого разнообразные причины (ПРИДУМЫВАТЬ ДЛЯ) rus_verbs:оставить{}, // или вообще решили оставить планету для себя rus_verbs:оставлять{}, rus_verbs:ВОССТАНОВИТЬ{}, // как ты можешь восстановить это для меня? (ВОССТАНОВИТЬ ДЛЯ) rus_verbs:ТАНЦЕВАТЬ{}, // а вы танцевали для меня танец семи покрывал (ТАНЦЕВАТЬ ДЛЯ) rus_verbs:ДАТЬ{}, // твой принц дал мне это для тебя! (ДАТЬ ДЛЯ) rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // мужчина из лагеря решил воспользоваться для передвижения рекой (ВОСПОЛЬЗОВАТЬСЯ ДЛЯ) rus_verbs:СЛУЖИТЬ{}, // они служили для разговоров (СЛУЖИТЬ ДЛЯ) rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // Для вычисления радиуса поражения ядерных взрывов используется формула (ИСПОЛЬЗОВАТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНЯТЬСЯ{}, // Применяется для изготовления алкогольных коктейлей (ПРИМЕНЯТЬСЯ ДЛЯ) rus_verbs:СОВЕРШАТЬСЯ{}, // Для этого совершался специальный магический обряд (СОВЕРШАТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНИТЬ{}, // а здесь попробуем применить ее для других целей. (ПРИМЕНИТЬ ДЛЯ) rus_verbs:ПОЗВАТЬ{}, // ты позвал меня для настоящей работы. (ПОЗВАТЬ ДЛЯ) rus_verbs:НАЧАТЬСЯ{}, // очередной денек начался для Любки неудачно (НАЧАТЬСЯ ДЛЯ) rus_verbs:ПОСТАВИТЬ{}, // вас здесь для красоты поставили? (ПОСТАВИТЬ ДЛЯ) rus_verbs:умереть{}, // или умерла для всяких чувств? (умереть для) rus_verbs:ВЫБРАТЬ{}, // ты сам выбрал для себя этот путь. (ВЫБРАТЬ ДЛЯ) rus_verbs:ОТМЕТИТЬ{}, // тот же отметил для себя другое. (ОТМЕТИТЬ ДЛЯ) rus_verbs:УСТРОИТЬ{}, // мы хотим устроить для них школу. (УСТРОИТЬ ДЛЯ) rus_verbs:БЫТЬ{}, // у меня есть для тебя работа. (БЫТЬ ДЛЯ) rus_verbs:ВЫЙТИ{}, // для всего нашего поколения так вышло. (ВЫЙТИ ДЛЯ) прилагательное:ВАЖНЫЙ{}, // именно твое мнение для нас крайне важно. (ВАЖНЫЙ ДЛЯ) прилагательное:НУЖНЫЙ{}, // для любого племени нужна прежде всего сила. (НУЖЕН ДЛЯ) прилагательное:ДОРОГОЙ{}, // эти места были дороги для них обоих. (ДОРОГОЙ ДЛЯ) rus_verbs:НАСТУПИТЬ{}, // теперь для больших людей наступило время действий. (НАСТУПИТЬ ДЛЯ) rus_verbs:ДАВАТЬ{}, // старый пень давал для этого хороший огонь. (ДАВАТЬ ДЛЯ) rus_verbs:ГОДИТЬСЯ{}, // доброе старое время годится лишь для воспоминаний. (ГОДИТЬСЯ ДЛЯ) rus_verbs:ТЕРЯТЬ{}, // время просто теряет для вас всякое значение. (ТЕРЯТЬ ДЛЯ) rus_verbs:ЖЕНИТЬСЯ{}, // настало время жениться для пользы твоего клана. (ЖЕНИТЬСЯ ДЛЯ) rus_verbs:СУЩЕСТВОВАТЬ{}, // весь мир перестал существовать для них обоих. (СУЩЕСТВОВАТЬ ДЛЯ) rus_verbs:ЖИТЬ{}, // жить для себя или жить для них. (ЖИТЬ ДЛЯ) rus_verbs:открыть{}, // двери моего дома всегда открыты для вас. (ОТКРЫТЫЙ ДЛЯ) rus_verbs:закрыть{}, // этот мир будет закрыт для них. (ЗАКРЫТЫЙ ДЛЯ) rus_verbs:ТРЕБОВАТЬСЯ{}, // для этого требуется огромное количество энергии. (ТРЕБОВАТЬСЯ ДЛЯ) rus_verbs:РАЗОРВАТЬ{}, // Алексей разорвал для этого свою рубаху. (РАЗОРВАТЬ ДЛЯ) rus_verbs:ПОДОЙТИ{}, // вполне подойдет для начала нашей экспедиции. (ПОДОЙТИ ДЛЯ) прилагательное:опасный{}, // сильный холод опасен для открытой раны. (ОПАСЕН ДЛЯ) rus_verbs:ПРИЙТИ{}, // для вас пришло очень важное сообщение. (ПРИЙТИ ДЛЯ) rus_verbs:вывести{}, // мы специально вывели этих животных для мяса. rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ) rus_verbs:оставаться{}, // механизм этого воздействия остается для меня загадкой. (остается для) rus_verbs:ЯВЛЯТЬСЯ{}, // Чай является для китайцев обычным ежедневным напитком (ЯВЛЯТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНЯТЬ{}, // Для оценок будущих изменений климата применяют модели общей циркуляции атмосферы. (ПРИМЕНЯТЬ ДЛЯ) rus_verbs:ПОВТОРЯТЬ{}, // повторяю для Пети (ПОВТОРЯТЬ ДЛЯ) rus_verbs:УПОТРЕБЛЯТЬ{}, // Краски, употребляемые для живописи (УПОТРЕБЛЯТЬ ДЛЯ) rus_verbs:ВВЕСТИ{}, // Для злостных нарушителей предложили ввести повышенные штрафы (ВВЕСТИ ДЛЯ) rus_verbs:найтись{}, // у вас найдется для него работа? rus_verbs:заниматься{}, // они занимаются этим для развлечения. (заниматься для) rus_verbs:заехать{}, // Коля заехал для обсуждения проекта rus_verbs:созреть{}, // созреть для побега rus_verbs:наметить{}, // наметить для проверки rus_verbs:уяснить{}, // уяснить для себя rus_verbs:нанимать{}, // нанимать для разовой работы rus_verbs:приспособить{}, // приспособить для удовольствия rus_verbs:облюбовать{}, // облюбовать для посиделок rus_verbs:прояснить{}, // прояснить для себя rus_verbs:задействовать{}, // задействовать для патрулирования rus_verbs:приготовлять{}, // приготовлять для проверки инфинитив:использовать{ вид:соверш }, // использовать для достижения цели инфинитив:использовать{ вид:несоверш }, глагол:использовать{ вид:соверш }, глагол:использовать{ вид:несоверш }, прилагательное:использованный{}, деепричастие:используя{}, деепричастие:использовав{}, rus_verbs:напрячься{}, // напрячься для решительного рывка rus_verbs:одобрить{}, // одобрить для использования rus_verbs:одобрять{}, // одобрять для использования rus_verbs:пригодиться{}, // пригодиться для тестирования rus_verbs:готовить{}, // готовить для выхода в свет rus_verbs:отобрать{}, // отобрать для участия в конкурсе rus_verbs:потребоваться{}, // потребоваться для подтверждения rus_verbs:пояснить{}, // пояснить для слушателей rus_verbs:пояснять{}, // пояснить для экзаменаторов rus_verbs:понадобиться{}, // понадобиться для обоснования инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована для условий крайнего севера инфинитив:адаптировать{вид:соверш}, глагол:адаптировать{вид:несоверш}, глагол:адаптировать{вид:соверш}, деепричастие:адаптировав{}, деепричастие:адаптируя{}, прилагательное:адаптирующий{}, прилагательное:адаптировавший{ вид:соверш }, //+прилагательное:адаптировавший{ вид:несоверш }, прилагательное:адаптированный{}, rus_verbs:найти{}, // Папа нашел для детей няню прилагательное:вредный{}, // Это вредно для здоровья. прилагательное:полезный{}, // Прогулки полезны для здоровья. прилагательное:обязательный{}, // Этот пункт обязателен для исполнения прилагательное:бесполезный{}, // Это лекарство бесполезно для него прилагательное:необходимый{}, // Это лекарство необходимо для выздоровления rus_verbs:создать{}, // Он не создан для этого дела. прилагательное:сложный{}, // задача сложна для младших школьников прилагательное:несложный{}, прилагательное:лёгкий{}, прилагательное:сложноватый{}, rus_verbs:становиться{}, rus_verbs:представлять{}, // Это не представляет для меня интереса. rus_verbs:значить{}, // Я рос в деревне и хорошо знал, что для деревенской жизни значат пруд или речка rus_verbs:пройти{}, // День прошёл спокойно для него. rus_verbs:проходить{}, rus_verbs:высадиться{}, // большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ rus_verbs:высаживаться{}, rus_verbs:прибавлять{}, // Он любит прибавлять для красного словца. rus_verbs:прибавить{}, rus_verbs:составить{}, // Ряд тригонометрических таблиц был составлен для астрономических расчётов. rus_verbs:составлять{}, rus_verbs:стараться{}, // Я старался для вас rus_verbs:постараться{}, // Я постарался для вас rus_verbs:сохраниться{}, // Старик хорошо сохранился для своего возраста. rus_verbs:собраться{}, // собраться для обсуждения rus_verbs:собираться{}, // собираться для обсуждения rus_verbs:уполномочивать{}, rus_verbs:уполномочить{}, // его уполномочили для ведения переговоров rus_verbs:принести{}, // Я принёс эту книгу для вас. rus_verbs:делать{}, // Я это делаю для удовольствия. rus_verbs:сделать{}, // Я сделаю это для удовольствия. rus_verbs:подготовить{}, // я подготовил для друзей сюрприз rus_verbs:подготавливать{}, // я подготавливаю для гостей новый сюрприз rus_verbs:закупить{}, // Руководство района обещало закупить новые комбайны для нашего села rus_verbs:купить{}, // Руководство района обещало купить новые комбайны для нашего села rus_verbs:прибыть{} // они прибыли для участия } fact гл_предл { if context { Гл_ДЛЯ_Род предлог:для{} *:*{ падеж:род } } then return true } fact гл_предл { if context { Гл_ДЛЯ_Род предлог:для{} @regex("[a-z]+[0-9]*") } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:для{} *:*{} } then return false,-4 } #endregion Предлог_ДЛЯ #region Предлог_ОТ // попробуем иную стратегию - запретить связывание с ОТ для отдельных глаголов, разрешив для всех остальных. wordentry_set Глаг_ОТ_Род_Запр= { rus_verbs:наслаждаться{}, // свободой от обязательств rus_verbs:насладиться{}, rus_verbs:мочь{}, // Он не мог удержаться от смеха. // rus_verbs:хотеть{}, rus_verbs:желать{}, rus_verbs:чувствовать{}, // все время от времени чувствуют его. rus_verbs:планировать{}, rus_verbs:приняться{} // мы принялись обниматься от радости. } fact гл_предл { if context { Глаг_ОТ_Род_Запр предлог:от{} * } then return false } #endregion Предлог_ОТ #region Предлог_БЕЗ /* // запретить связывание с БЕЗ для отдельных глаголов, разрешив для всех остальных. wordentry_set Глаг_БЕЗ_Род_Запр= { rus_verbs:мочь{}, // Он мог читать часами без отдыха. rus_verbs:хотеть{}, rus_verbs:желать{}, rus_verbs:планировать{}, rus_verbs:приняться{} } fact гл_предл { if context { Глаг_БЕЗ_Род_Запр предлог:без{} * } then return false } */ #endregion Предлог_БЕЗ #region Предлог_КРОМЕ fact гл_предл { if context { * ПредлогДляВсе * } then return false,-5 } #endregion Предлог_КРОМЕ // ------------------------------------ // По умолчанию разрешаем все остальные сочетания. fact гл_предл { if context { * * * } then return true }
продрогнуть на морозе
rus_verbs:продрогнуть{},
5,484,422
[ 1, 145, 128, 146, 227, 145, 127, 145, 117, 146, 227, 145, 127, 145, 116, 145, 126, 146, 230, 146, 229, 146, 239, 225, 145, 126, 145, 113, 225, 145, 125, 145, 127, 146, 227, 145, 127, 145, 120, 145, 118, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 436, 407, 67, 502, 2038, 30, 145, 128, 146, 227, 145, 127, 145, 117, 146, 227, 145, 127, 145, 116, 145, 126, 146, 230, 146, 229, 146, 239, 2916, 16, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.6; import "./Supplier.sol"; contract Exchange { address public owner; uint public currentTicket; // the next ticket to be served once an order has come in uint public recentTicket; // the ticket most in the future to serve the order mapping (bytes32 => address) supplierListed; // NOTE: This mapping might not be necessary struct Order { // the state can also be expressed as an // enum instead of a string bytes32 state; address contractAddress; address recipientAddress; uint256 amount; } struct supplier { uint ticket; address contractAddress; } mapping (address => Order) orders; mapping (uint => address) public supplierQueue; mapping (uint => address) public orderQueue; function Exchange(address _owner){ owner = _owner; currentTicket = 0; recentTicket = 0; } function enlist(address supplierContractAddress) { // TODO if already enlisted throw Supplier supplierContract = Supplier(supplierContractAddress); bytes32 supplierNameBytes = supplierContract.getSupplierNameBytes(); supplierListed[supplierNameBytes] = supplierContractAddress; recentTicket = recentTicket + 1; supplierQueue[recentTicket] = supplierContractAddress; Enlisted(supplierContractAddress); } function registerOrder(address _recipientAddress, uint256 _amount) { orders[msg.sender].state = "received"; orders[msg.sender].contractAddress = msg.sender; //TODO checkt that the _recipientAddress address is not 0x0 orders[msg.sender].recipientAddress = _recipientAddress; orders[msg.sender].amount = _amount; currentTicket = currentTicket + 1; orderQueue[currentTicket] = msg.sender; } function getNextSupplier() constant returns (address supplierAddress) { return supplierQueue[currentTicket]; } function fulfillOrder() returns (bool result) { // TODO only the owner can call this function address supplierContractAddress = getNextSupplier(); address _orderAddress; Supplier supplierContract = Supplier(supplierContractAddress); _orderAddress = orderQueue[currentTicket]; // TODO update state and check if the transaction goes through // if the transaction does not go through revert the state supplierContract.sendToOrder(orders[_orderAddress].recipientAddress, orders[_orderAddress].amount); currentTicket = currentTicket + 1; /* if(!supplierContract.sendToOrder(_orderAddress, orders[_orderAddress].recipientAddress)){ currentTicket = currentTicket - 1; return false; } else { return true; } */ //_supplierAddress = supplierQueue[currentTicket]; //if(!_supplierAddresssendWithGas /* if(!_orderAddress.send({from:_supplierAddress, value:orderContract.amount})) throw; else{ return true; } */ } function isExistByBytes(bytes32 supplierNameBytes) constant returns (bool result) { //supplier if (supplierListed[supplierNameBytes] == 0x0) return false; else return true; } function isOrderExistByAddress(address _orderAddress) constant returns (bool result) { if(orders[_orderAddress].contractAddress != 0x0) return true; else return false; } function sendWithGas(address destination, uint256 value, uint256 extraGasAmt) internal returns (bool){ return destination.call.value(value).gas(extraGasAmt)(); } event Enlisted(address indexed supplierContract); }
TODO if already enlisted throw
function enlist(address supplierContractAddress) { Supplier supplierContract = Supplier(supplierContractAddress); bytes32 supplierNameBytes = supplierContract.getSupplierNameBytes(); supplierListed[supplierNameBytes] = supplierContractAddress; recentTicket = recentTicket + 1; supplierQueue[recentTicket] = supplierContractAddress; Enlisted(supplierContractAddress); }
1,823,420
[ 1, 6241, 309, 1818, 570, 18647, 604, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 570, 1098, 12, 2867, 17402, 8924, 1887, 13, 288, 203, 565, 17216, 17402, 8924, 273, 17216, 12, 2859, 5742, 8924, 1887, 1769, 203, 565, 1731, 1578, 17402, 461, 2160, 273, 17402, 8924, 18, 588, 13254, 461, 2160, 5621, 203, 565, 17402, 682, 329, 63, 2859, 5742, 461, 2160, 65, 273, 17402, 8924, 1887, 31, 203, 565, 8399, 13614, 273, 8399, 13614, 397, 404, 31, 203, 565, 17402, 3183, 63, 20872, 13614, 65, 273, 17402, 8924, 1887, 31, 203, 565, 1374, 18647, 12, 2859, 5742, 8924, 1887, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/9001/0xf0EE62005149B008bD3991EdfEA2cAd5EAE592aA/sources/contracts/governed-owner/SimpleGovernance.sol
voter addr -> voting power
mapping(address => uint256) public voterPowers;
11,533,147
[ 1, 90, 20005, 3091, 317, 331, 17128, 7212, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 331, 20005, 28289, 414, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xBe2B3A004204245812739B29a21dCD9C0b5CE7c3/sources/contracts/PullPaymentMarket.sol
Function to remove a token from the whitelist
function removeFromWhitelist(address _token) external onlyOwner { whitelistedTokens[_token] = false; }
16,398,459
[ 1, 2083, 358, 1206, 279, 1147, 628, 326, 10734, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 22386, 18927, 12, 2867, 389, 2316, 13, 3903, 1338, 5541, 288, 203, 3639, 26944, 5157, 63, 67, 2316, 65, 273, 629, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xdDc2c27eA8a42b35B329c4e0216600F12EED13d1/sources/contracts/wombat-core/pool/PoolV3.sol
@notice Dev address
address public dev;
2,762,401
[ 1, 8870, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 1071, 4461, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// 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); } /** * @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); function keyOfRoot(uint256 root) external view returns (address); /** * @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; } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; address private _pending_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"); _; } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } function proposeOwner(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new pending owner is the zero address"); _pending_owner = newOwner; } function claimOwner() public virtual { require(_pending_owner == msg.sender, "Ownable: msg.sender is not the pending owner"); address oldOwner = _owner; _owner = _pending_owner; _pending_owner = address(0); emit OwnershipTransferred(oldOwner, _owner); } } /** * @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; } } /** * @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); } /** * @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); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev 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; } function keyOfRoot(uint256 root) public view virtual override returns (address) { return _owners[root]; } /** * @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(to).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 {} } /** * @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 the assets stored by the contract. */ function assets() external view returns (address); /** * @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); function rootOfKey(address key) external view returns (uint256); } /** * @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; address private _assets; /** * @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; } function assets() external view virtual override returns (address) { return _assets; } /** * @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]; } function rootOfKey(address key) public view virtual override returns (uint256) { return ERC721.balanceOf(key) == 0 ? type(uint256).max : _ownedTokens[key][0]; } /** * @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 != 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); require(length == 0, "Root: already exists!"); _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). require(ERC721.balanceOf(from) == 1, "Root: not exists!"); // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][0]; } /** * @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(); } function _setAssets(address assets_) internal { _assets = assets_; } } contract Root is ERC721Enumerable, ReentrancyGuard, Ownable { using Address for address; uint256 public start_time = 0; uint256 public deploy_time = 0; uint256 public MAX_TOTAL_SUPPLY = 21000000; function claim() external nonReentrant { require(claimable(), "not claimable"); uint256 ts = totalSupply(); if (ts == 2100) { start_time = deploy_time + (21 days); } else if (ts == 21000) { start_time = deploy_time + (21 * 4 days); } else if (ts == 210000) { start_time = deploy_time + (21 * 4 * 4 days); } else if (ts == 2100000) { start_time = deploy_time + (21 * 4 * 4 * 4 days); } _safeMint(_msgSender(), ts); } function claimable() public view returns (bool) { return block.timestamp >= start_time && totalSupply() < MAX_TOTAL_SUPPLY; } function claimableId() external view returns (uint256) { return claimable() ? totalSupply() : type(uint256).max; } function setAssets(address _assets) external onlyOwner { super._setAssets(_assets); } function expand() external onlyOwner { require(totalSupply() == MAX_TOTAL_SUPPLY, "ROOT: totalSupply not equal to current max_total_supply"); MAX_TOTAL_SUPPLY = MAX_TOTAL_SUPPLY * 10; } constructor() ERC721("ROOT", "ROOT") Ownable() { deploy_time = block.timestamp; } }
* @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); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } }
13,826,581
[ 1, 5394, 716, 353, 2566, 1865, 1281, 1147, 7412, 18, 1220, 6104, 312, 474, 310, 471, 18305, 310, 18, 21020, 4636, 30, 300, 5203, 1375, 2080, 68, 471, 1375, 869, 68, 854, 3937, 1661, 17, 7124, 16, 12176, 2080, 10335, 11, 87, 1375, 2316, 548, 68, 903, 506, 906, 4193, 358, 1375, 869, 8338, 300, 5203, 1375, 2080, 68, 353, 3634, 16, 1375, 2316, 548, 68, 903, 506, 312, 474, 329, 364, 1375, 869, 8338, 300, 5203, 1375, 869, 68, 353, 3634, 16, 12176, 2080, 10335, 11, 87, 1375, 2316, 548, 68, 903, 506, 18305, 329, 18, 300, 1375, 2080, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 2974, 16094, 1898, 2973, 9153, 16, 910, 358, 15187, 30, 9185, 30, 408, 2846, 17, 16351, 87, 18, 4539, 9940, 17, 10468, 63, 7736, 13725, 87, 8009, 19, 2, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 262, 2713, 5024, 3849, 288, 203, 3639, 2240, 6315, 5771, 1345, 5912, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 203, 3639, 309, 261, 2080, 422, 1758, 12, 20, 3719, 288, 203, 5411, 389, 1289, 1345, 774, 1595, 5157, 21847, 12, 2316, 548, 1769, 203, 5411, 389, 4479, 1345, 1265, 5541, 21847, 12, 2080, 16, 1147, 548, 1769, 203, 3639, 289, 203, 540, 203, 3639, 309, 261, 869, 480, 628, 13, 288, 203, 5411, 389, 1289, 1345, 774, 5541, 21847, 12, 869, 16, 1147, 548, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xe7Ebc638409b8f4f0DAde04c16e843a94bBc667e/sources/src/Access.sol
* @dev Toggles the transferrable status of a specific token. @param _tokenId The ID of the token. @param _status The new transferrable status of the token./
function toggleTransferrable(uint256 _tokenId, bool _status) public onlyRole(ADMIN_ROLE()) { tokenTransferrableStatus[_tokenId] = [++transferrableCounter, bool2uint(_status)]; }
5,606,049
[ 1, 56, 23972, 1040, 326, 7412, 354, 7119, 1267, 434, 279, 2923, 1147, 18, 225, 389, 2316, 548, 1021, 1599, 434, 326, 1147, 18, 225, 389, 2327, 1021, 394, 7412, 354, 7119, 1267, 434, 326, 1147, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 10486, 5912, 354, 7119, 12, 11890, 5034, 389, 2316, 548, 16, 1426, 389, 2327, 13, 1071, 1338, 2996, 12, 15468, 67, 16256, 10756, 288, 203, 3639, 1147, 5912, 354, 7119, 1482, 63, 67, 2316, 548, 65, 273, 306, 9904, 13866, 354, 7119, 4789, 16, 1426, 22, 11890, 24899, 2327, 13, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/84531/0xD920Cd72ea026c9ce7620d19245A773a972c555a/sources/contracts/prebuilts/account/managed/ManagedAccountFactory.sol
@dev Returns whether all relevant permission and other checks are met before any upgrade.
function _isAuthorizedCallToUpgrade() internal view virtual override returns (bool) { return hasRole(keccak256("EXTENSION_ROLE"), msg.sender); }
14,307,482
[ 1, 1356, 2856, 777, 9368, 4132, 471, 1308, 4271, 854, 5100, 1865, 1281, 8400, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 291, 15341, 1477, 774, 10784, 1435, 2713, 1476, 5024, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 327, 28335, 12, 79, 24410, 581, 5034, 2932, 12796, 67, 16256, 6, 3631, 1234, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xfcbf96EE4780Cb4cE0080151785D4F21Aa960CAB/sources/contracts/1_Storage.sol
ERC20("CRYPTO LeisureMeta", "LeisureMeta")constructor (string memory name, string memory symbol)
contract LeisureMetaCoin is ERC20,ERC20Burnable,ERC20Pausable { constructor () public { _mint(msg.sender, 10000000000 * (10**uint256(18))); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } }
8,122,631
[ 1, 654, 39, 3462, 2932, 14306, 51, 3519, 291, 594, 2781, 3113, 315, 1682, 291, 594, 2781, 7923, 12316, 261, 1080, 3778, 508, 16, 533, 3778, 3273, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3519, 291, 594, 2781, 27055, 353, 4232, 39, 3462, 16, 654, 39, 3462, 38, 321, 429, 16, 654, 39, 3462, 16507, 16665, 288, 203, 565, 3885, 1832, 203, 3639, 1071, 203, 565, 288, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 2130, 12648, 380, 261, 2163, 636, 11890, 5034, 12, 2643, 3719, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 3844, 13, 2713, 5024, 3849, 12, 654, 39, 3462, 16, 4232, 39, 3462, 16507, 16665, 13, 288, 203, 3639, 2240, 6315, 5771, 1345, 5912, 12, 2080, 16, 358, 16, 3844, 1769, 203, 565, 289, 377, 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 ]
./full_match/222000222/0xc3023a2c9f7B92d1dd19F488AF6Ee107a78Df9DB/sources/contracts/MasterChef.sol
MELD tokens created per block.
uint256 public meldPerBlock;
13,222,818
[ 1, 958, 12069, 2430, 2522, 1534, 1203, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 1071, 312, 488, 2173, 1768, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; /** * @title NFT Smart Contract * @author Stephan Fowler * @notice ERC721 contract for stand-alone NFT collections with lazy-minting * @dev Enables lazy-minting by any user via precomputed signatures */ contract NFTsurface is ERC721, EIP712 { event IdFloorSet(uint256 idFloor); event Receipt(uint256 value); event Withdrawal(uint256 value); event BaseMintPriceSet(uint256 baseMintPrice); event PriceSet(uint256 id, uint256 price); event Bought(uint256 id, address buyer); address public immutable owner; uint256 private constant MAX_INT = type(uint256).max; uint256 public baseMintPrice; uint256 public totalSupply; uint256 public idFloor; uint256 public immutable royaltyBasisPoints; mapping(uint256 => string) private tokenURIs; mapping(uint256 => uint256) private prices; /** * @dev Constructor immutably sets "owner" to the message sender; be sure to deploy contract using the account of the creator/artist/brand/etc. * @param _name ERC721 token name * @param _symbol ERC721 token symbol * @param _baseMintPrice The initial mint price in wei * @param _royaltyBasisPoints Percentage basis-points for royalty on secondary sales, eg 495 == 4.95% */ constructor( string memory _name, string memory _symbol, uint256 _baseMintPrice, uint256 _royaltyBasisPoints ) ERC721(_name, _symbol) EIP712("NFTsurface", "1.0.0") { owner = _msgSender(); baseMintPrice = _baseMintPrice; royaltyBasisPoints = _royaltyBasisPoints; } /** * @notice Receive ETH */ receive() external payable { emit Receipt(msg.value); } /** * @notice Withdraw ETH balance */ function withdraw() external { require(_msgSender() == owner, "unauthorized to withdraw"); uint256 balance = address(this).balance; (bool success, ) = _msgSender().call{value: balance}(""); require(success, "transfer failed"); emit Withdrawal(balance); } /** * @notice Minting by the agent only * @param recipient The recipient of the NFT * @param id The intended token id * @param uri The intended token URI */ function mintAuthorized( address recipient, uint256 id, string memory uri ) external { require(_msgSender() == owner, "unauthorized to mint"); require(vacant(id)); _mint(recipient, id, uri); } /** * @notice Minting at baseMintPrice, given the owner's signature of the specified arguments * @param id The intended token id * @param uri The intended token URI * @param signature The ERC712 signature */ function mint( uint256 id, string memory uri, bytes calldata signature ) external payable { mintAtPrice(MAX_INT, id, uri, signature); } /** * @notice Minting at price, given the owner's signature over the specified arguments * @param price Minting price in wei. If MAX_INT, baseMintPrice applies. * @param id The intended token id * @param uri The intended token URI * @param signature The ERC712 signature */ function mintAtPrice( uint256 price, uint256 id, string memory uri, bytes calldata signature ) public payable { require( (price == MAX_INT && msg.value == baseMintPrice) || msg.value == price, "incorrect ETH sent" ); require(mintable(price, id, uri, signature)); _mint(_msgSender(), id, uri); } /** * @notice Checks availability for minting, and validity of the owner's signature * @param price Minting price in wei. If MAX_INT, baseMintPrice applies. * @param id The intended token id * @param uri The intended token URI * @param signature The ERC712 signature */ function mintable( uint256 price, uint256 id, string memory uri, bytes calldata signature ) public view returns (bool) { require(vacant(id)); require( owner == ECDSA.recover(_hash(price, id, uri), signature), "signature invalid or signer unauthorized" ); return true; } /** * @notice Checks availability for minting * @param id The token id */ function vacant(uint256 id) public view returns (bool) { require(!_exists(id), "tokenId already minted"); require(id >= idFloor, "tokenId below floor"); return true; } /** * @notice Sets the price at which a token may be bought. A zero price cancels the sale. * @param id The token id * @param _price The token price in wei */ function setPrice(uint256 id, uint256 _price) external { require(_msgSender() == ownerOf(id), "caller is not token owner"); prices[id] = _price; emit PriceSet(id, _price); } /** * @notice Returns the price at which a token may be bought. Zero means the token is not for sale. * @param id The token id */ function priceOf(uint256 id) external view returns (uint256) { return prices[id]; } /** * @notice Transfers the token to the caller, and transfers the paid ETH to its owner (minus royalty) * @param id The token id */ function buy(uint256 id) external payable { require(_msgSender() != ownerOf(id), "caller is token owner"); require(prices[id] > 0, "token not for sale"); require(msg.value == prices[id], "incorrect ETH sent"); address seller = ownerOf(id); delete prices[id]; _safeTransfer(seller, _msgSender(), id, ""); Address.sendValue( payable(seller), (10000 - royaltyBasisPoints) * (msg.value / 10000) ); emit Bought(id, _msgSender()); } /** * @notice Sets the mint price * @param _baseMintPrice The new mint price */ function setBaseMintPrice(uint256 _baseMintPrice) external { require(_msgSender() == owner, "unauthorized to set baseMintPrice"); baseMintPrice = _baseMintPrice; emit BaseMintPriceSet(_baseMintPrice); } /** * @notice Disables minting of ids below floor, thus revoking any signatures that include them * @param floor The floor for new token ids minted from now */ function setIdFloor(uint256 floor) external { require(_msgSender() == owner, "unauthorized to set idFloor"); idFloor = floor; emit IdFloorSet(idFloor); } /** * @notice Returns the token URI, given the token id * @param id The token id */ function tokenURI(uint256 id) public view override returns (string memory) { return tokenURIs[id]; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view override(ERC721) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev Minting also increments totalSupply */ function _mint( address recipient, uint256 id, string memory uri ) internal { _safeMint(recipient, id); _setTokenURI(id, uri); totalSupply += 1; } /** * @dev Recreates the hash that the signer (may have) signed */ function _hash( uint256 price, uint256 id, string memory uri ) internal view returns (bytes32) { return _hashTypedDataV4( keccak256( abi.encode( keccak256( "mint(uint256 price,uint256 tokenId,string tokenURI)" ), price, id, keccak256(bytes(uri)) ) ) ); } /** * @dev record a token's URI against its id */ function _setTokenURI(uint256 id, string memory uri) internal { require(bytes(uri).length != 0, "tokenURI cannot be empty"); tokenURIs[id] = uri; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721) { super._beforeTokenTransfer(from, to, tokenId); delete prices[tokenId]; } }
* @notice Returns the price at which a token may be bought. Zero means the token is not for sale. @param id The token id/
function priceOf(uint256 id) external view returns (uint256) { return prices[id]; }
7,277,399
[ 1, 1356, 326, 6205, 622, 1492, 279, 1147, 2026, 506, 800, 9540, 18, 12744, 4696, 326, 1147, 353, 486, 364, 272, 5349, 18, 282, 612, 1021, 1147, 612, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6205, 951, 12, 11890, 5034, 612, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 19827, 63, 350, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.5.0; contract MyCasino { //OWNER OF THE ACCOUNT address payable public owner; constructor(uint _minBet) public { owner = msg.sender; //USER THAT CREATED THIS CONTRACT IS THE OWNER if(_minBet != 0) minimumBet = _minBet; //MINIMUM BET VALUE } //ARRAY FOR ALL THE PLAYERS address payable[] public players; //MINIMUM PRICE OF BET uint public minimumBet; //TOTAL ETHER COLLECTED uint public totalBetAmount; //NUMBER OF BETS PLACED uint256 public numberOfBets ; //MAXIMUM NUMBER OF BETS ALLOWED //A NEW ROUND WILL TAKE PLACE AFTER 10 BETS uint256 public maxBets = 100 ; //SO THAT ETHER DOES NOT GET LOST function()external payable { } //ONLY THE OWNER CAN KILL THE CONTRACT //THE REMAINING ETHER WOULD BE SENT TO THE OWNER function kill() external { if(msg.sender == owner) { selfdestruct(owner); } } struct Player { uint betAmount; uint256 numberChosen; } //TO MAP THE ADDRESS WITH PLAYER DETAILS mapping (address => Player) public playerChoice; //THIS EVENT INDICATES THAT A RANDOM NUMBER IS GENERATED event NumberGenerated(uint number); //THIS EVENT INDICATES THAT USER HAS BEEN REWARDED event rewardGenerated(); function checkTotalbets() public returns(bool){ if( (numberOfBets < maxBets) && (numberOfBets != maxBets)) return true; else { return false; } } //TO PLACE THE BET function placeBet(uint256 _betNumber, uint bet_price) public payable { //playerExists(msg.sender) //require(checkTotalbets()); //require(checkTotalbets(),"Total bets completed"); if( checkTotalbets()) { require(_betNumber >=1 && _betNumber<=10,"Number selected is not in range 1-10."); require(bet_price >= minimumBet,"Bet value is less than Minimum bet value."); playerChoice[msg.sender].betAmount = bet_price; playerChoice[msg.sender].numberChosen = _betNumber; numberOfBets++; // increase the number of bets players.push(msg.sender); totalBetAmount += bet_price; } else generateNumber(); } //GENERATE A RANDOM NUMBER function generateNumber() public{ uint256 win_number = uint(uint256(keccak256(abi.encodePacked(block.timestamp,block.difficulty))) % 10); emit NumberGenerated(win_number); awardPrize(win_number); // awardPrize(win_number); } //TO DISTRIBUTE PRIZES function awardPrize(uint winner_number) public payable { address payable[20] memory winners; uint count=0; address payable playerAddress; for(uint i=0; i<players.length; i++){ playerAddress = players[i]; if(playerChoice[playerAddress].numberChosen == winner_number) { winners[count] = playerAddress; count++; } delete playerChoice[playerAddress]; //delete the player from the mapping } delete players; //*******clear players array //DISTRIBUTE ETHER AMONG PLAYERS uint finalAmount = totalBetAmount/ winners.length; for(uint i=0; i<count;i++) { if(winners[i] != address(0)) // Check that the address in this fixed array is not empty winners[i].transfer(finalAmount); emit rewardGenerated(); } totalBetAmount = 0; numberOfBets = 0; } }
USER THAT CREATED THIS CONTRACT IS THE OWNER
owner = msg.sender;
1,011,794
[ 1, 4714, 7662, 789, 21397, 20676, 8020, 2849, 1268, 4437, 12786, 531, 22527, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3410, 273, 1234, 18, 15330, 31, 1377, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import {BTCUtils} from "@interlay/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {BytesLib} from "@interlay/bitcoin-spv-sol/contracts/BytesLib.sol"; import {S_ReplaceRequest, RequestStatus} from "./Request.sol"; import {TxValidate} from "./TxValidate.sol"; import {ICollateral} from "./Collateral.sol"; import {VaultRegistry} from "./VaultRegistry.sol"; import {Math} from "@openzeppelin/contracts/math/Math.sol"; abstract contract Replace is ICollateral, VaultRegistry { // using BTCUtils for bytes; // using BytesLib for bytes; event RequestReplace( address indexed oldVault, uint256 btcAmount, uint256 griefingCollateral ); event WithdrawReplace( address indexed oldVault, uint256 withdrawnTokens, uint256 withdrawnGriefingCollateral ); event AcceptReplace( uint256 indexed replaceId, address indexed oldVault, address indexed newVault, uint256 btcAmount, uint256 collateral, address btcAddress ); event ExecuteReplace( uint256 indexed replaceId, address indexed oldVault, address indexed newVault ); event CancelReplace( uint256 indexed replaceId, address indexed oldVault, address indexed newVault, uint256 slashedCollateral ); mapping(uint256 => S_ReplaceRequest) public replaceRequests; function getReplaceId(address user) private view returns (uint256) { //getSecureId return uint256( keccak256(abi.encodePacked(user, blockhash(block.number - 1))) ); } function getReplaceBtcDustValue() private returns(uint256) { // TODO return 0; } function getReplaceGriefingCollateral(uint256 amountBtc) private returns (uint256) { // TODO return amountBtc; } function _requestReplace( address payable oldVaultId, uint256 btcAmount, uint256 griefingCollateral ) internal { require(msg.sender == oldVaultId, 'Sender should be owner of this Vault'); // TODO: SECURITY CHECK (The oldVault MUST NOT be banned) uint256 requestableTokens = VaultRegistry.requestableToBeReplacedTokens(oldVaultId); uint256 toBeReplacedIncrease = Math.min(requestableTokens, btcAmount); uint256 replaceCollateralIncrease = griefingCollateral; if(btcAmount > 0) { replaceCollateralIncrease = VaultRegistry.calculateCollateral(griefingCollateral, toBeReplacedIncrease, btcAmount); } (uint256 totalToBeReplaced, uint256 totalGriefingCollateral) = VaultRegistry.tryIncreaseToBeReplacedTokens(oldVaultId, toBeReplacedIncrease, replaceCollateralIncrease); // check that total-to-be-replaced is above the minimum. NOTE: this means that even // a request with amount=0 is valid, as long the _total_ is above DUST. This might // be the case if the vault just wants to increase the griefing collateral, for example. uint256 dustValue = getReplaceBtcDustValue(); require(totalToBeReplaced >= dustValue, 'AmountBelowDustAmount'); // check that that the total griefing collateral is sufficient to back the total to-be-replaced amount require( getReplaceGriefingCollateral(totalToBeReplaced) <= totalGriefingCollateral, "InsufficientCollateral" ); // Lock the oldVault’s griefing collateral. Note that this directly locks the amount ICollateral.lockCollateral(oldVaultId, replaceCollateralIncrease); emit RequestReplace(oldVaultId, toBeReplacedIncrease, replaceCollateralIncrease); } function _withdrawReplace(address oldVaultId, uint256 btcAmount) internal { require(msg.sender == oldVaultId, 'Sender should be old Vault owner'); // TODO: SECURITY CHECK (The oldVault MUST NOT be banned) (uint256 withdrawnTokens, uint256 toWithdrawCollateral) = VaultRegistry.decreaseToBeReplacedTokens(oldVaultId, btcAmount); ICollateral.releaseCollateral(oldVaultId, toWithdrawCollateral); require(withdrawnTokens == 0, 'Withdraw tokens is zero'); emit WithdrawReplace(oldVaultId, withdrawnTokens, toWithdrawCollateral); } function _acceptReplace( address oldVaultId, address newVaultId, uint256 btcAmount, uint256 collateral, uint256 btcPublicKeyX, uint256 btcPublicKeyY ) internal { require(msg.sender == newVaultId, 'Sender should be new Vault owner'); require(oldVaultId != newVaultId, 'oldVault MUST NOT be equal to newVault'); // TODO: The newVault’s free balance MUST be enough to lock collateral. // TODO: SECURITY CHECK (The oldVault, newVault MUST NOT be banned) Vault storage oldVault = VaultRegistry.vaults[oldVaultId]; Vault storage newVault = VaultRegistry.vaults[newVaultId]; require(oldVault.btcPublicKeyX != 0, "vaultNotExist"); require(newVault.btcPublicKeyX != 0, "vaultNotExist"); // decrease old-vault's to-be-replaced tokens (uint256 redeemableTokens, uint256 griefingCollateral) = VaultRegistry.decreaseToBeReplacedTokens(oldVaultId, btcAmount); // TODO: check amount_btc is above the minimum uint256 dustValue = getReplaceBtcDustValue(); require(redeemableTokens >= dustValue, 'AmountBelowDustAmount'); // Calculate and lock the new-vault's additional collateral uint256 actualNewVaultCollateral = VaultRegistry.calculateCollateral(collateral, redeemableTokens, btcAmount); VaultRegistry.tryDepositCollateral(newVaultId, actualNewVaultCollateral); // increase old-vault's to-be-redeemed tokens - this should never fail VaultRegistry.tryIncreaseToBeRedeemedTokens(oldVaultId, redeemableTokens); // increase new-vault's to-be-issued tokens - this will fail if there is insufficient collateral VaultRegistry.tryIncreaseToBeIssuedTokens(newVaultId, redeemableTokens); uint256 replaceId = getReplaceId(oldVaultId); address btcAddress = VaultRegistry.insertVaultDepositAddress(newVaultId, btcPublicKeyX, btcPublicKeyY, replaceId); S_ReplaceRequest storage replace = replaceRequests[replaceId]; require(replace.status == RequestStatus.None, "This replace already created"); { replace.oldVault = address(uint160(oldVaultId)); replace.newVault = address(uint160(newVaultId)); replace.amount = redeemableTokens; replace.btcAddress = btcAddress; replace.collateral = actualNewVaultCollateral; replace.griefingCollateral = griefingCollateral; replace.period = 2 days; replace.btcHeight = 0; replace.status = RequestStatus.Pending; } emit AcceptReplace( replaceId, replace.oldVault, replace.newVault, replace.amount, replace.collateral, replace.btcAddress ); } function _executeReplace(uint256 replaceId, bytes memory _vout) internal { // Retrieve the ReplaceRequest as per the replaceId parameter from Vaults in the VaultRegistry S_ReplaceRequest storage replace = replaceRequests[replaceId]; require(replace.status == RequestStatus.Pending, "Wrong request status"); // NOTE: anyone can call this method provided the proof is correct address oldVaultId = replace.oldVault; address newVaultId = replace.newVault; uint256 amountTransferred = TxValidate.validateTransaction( _vout, 0, replace.btcAddress, replaceId ); require (amountTransferred >= replace.amount, 'Transaction contain wrong btc amount'); // decrease old-vault's issued & to-be-redeemed tokens, and // change new-vault's to-be-issued tokens to issued tokens VaultRegistry.replaceTokens(oldVaultId, newVaultId, replace.amount, replace.collateral); // if the old vault has not been liquidated, give it back its griefing collateral ICollateral.releaseCollateral(oldVaultId, replace.griefingCollateral); // Emit ExecuteReplace event. emit ExecuteReplace(replaceId, oldVaultId, newVaultId); // Remove replace request { replace.status = RequestStatus.Completed; } } }
Retrieve the ReplaceRequest as per the replaceId parameter from Vaults in the VaultRegistry NOTE: anyone can call this method provided the proof is correct decrease old-vault's issued & to-be-redeemed tokens, and change new-vault's to-be-issued tokens to issued tokens if the old vault has not been liquidated, give it back its griefing collateral Emit ExecuteReplace event. Remove replace request
function _executeReplace(uint256 replaceId, bytes memory _vout) internal { S_ReplaceRequest storage replace = replaceRequests[replaceId]; require(replace.status == RequestStatus.Pending, "Wrong request status"); address oldVaultId = replace.oldVault; address newVaultId = replace.newVault; uint256 amountTransferred = TxValidate.validateTransaction( _vout, 0, replace.btcAddress, replaceId ); require (amountTransferred >= replace.amount, 'Transaction contain wrong btc amount'); VaultRegistry.replaceTokens(oldVaultId, newVaultId, replace.amount, replace.collateral); ICollateral.releaseCollateral(oldVaultId, replace.griefingCollateral); emit ExecuteReplace(replaceId, oldVaultId, newVaultId); { replace.status = RequestStatus.Completed; } }
13,048,517
[ 1, 5767, 326, 6910, 691, 487, 1534, 326, 1453, 548, 1569, 628, 17329, 87, 316, 326, 17329, 4243, 5219, 30, 1281, 476, 848, 745, 333, 707, 2112, 326, 14601, 353, 3434, 20467, 1592, 17, 26983, 1807, 16865, 473, 358, 17, 2196, 17, 266, 24903, 329, 2430, 16, 471, 2549, 394, 17, 26983, 1807, 358, 17, 2196, 17, 1054, 5957, 2430, 358, 16865, 2430, 309, 326, 1592, 9229, 711, 486, 2118, 4501, 26595, 690, 16, 8492, 518, 1473, 2097, 314, 17802, 310, 4508, 2045, 287, 16008, 7903, 5729, 871, 18, 3581, 1453, 590, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 8837, 5729, 12, 11890, 5034, 1453, 548, 16, 1731, 3778, 389, 90, 659, 13, 2713, 288, 203, 3639, 348, 67, 5729, 691, 2502, 1453, 273, 1453, 6421, 63, 2079, 548, 15533, 203, 3639, 2583, 12, 2079, 18, 2327, 422, 1567, 1482, 18, 8579, 16, 315, 13634, 590, 1267, 8863, 203, 203, 3639, 1758, 1592, 12003, 548, 273, 1453, 18, 1673, 12003, 31, 203, 3639, 1758, 394, 12003, 548, 273, 1453, 18, 2704, 12003, 31, 203, 203, 3639, 2254, 5034, 3844, 1429, 4193, 273, 203, 5411, 6424, 4270, 18, 5662, 3342, 12, 203, 7734, 389, 90, 659, 16, 203, 7734, 374, 16, 203, 7734, 1453, 18, 70, 5111, 1887, 16, 203, 7734, 1453, 548, 203, 5411, 11272, 203, 203, 3639, 2583, 261, 8949, 1429, 4193, 1545, 1453, 18, 8949, 16, 296, 3342, 912, 7194, 12798, 3844, 8284, 203, 203, 3639, 17329, 4243, 18, 2079, 5157, 12, 1673, 12003, 548, 16, 394, 12003, 548, 16, 1453, 18, 8949, 16, 1453, 18, 12910, 2045, 287, 1769, 203, 203, 3639, 467, 13535, 2045, 287, 18, 9340, 13535, 2045, 287, 12, 1673, 12003, 548, 16, 1453, 18, 75, 17802, 310, 13535, 2045, 287, 1769, 203, 203, 3639, 3626, 7903, 5729, 12, 2079, 548, 16, 1592, 12003, 548, 16, 394, 12003, 548, 1769, 203, 203, 3639, 288, 203, 5411, 1453, 18, 2327, 273, 1567, 1482, 18, 9556, 31, 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 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.7.1; // File: contracts/oracle/RegularIntervalOracleInterface.sol /** * @dev Interface of the regular interval price oracle. */ interface RegularIntervalOracleInterface { function setPrice(uint256 roundId) external returns (bool); function setOptimizedParameters(uint16 lambdaE4) external returns (bool); function updateQuantsAddress(address quantsAddress) external returns (bool); function getNormalizedTimeStamp(uint256 timestamp) external view returns (uint256); function getDecimals() external view returns (uint8); function getInterval() external view returns (uint256); function getLatestTimestamp() external view returns (uint256); function getOldestTimestamp() external view returns (uint256); function getVolatility() external view returns (uint256 volE8); function getInfo() external view returns (address chainlink, address quants); function getPrice() external view returns (uint256); function setSequentialPrices(uint256[] calldata roundIds) external returns (bool); function getPriceTimeOf(uint256 unixtime) external view returns (uint256); function getVolatilityTimeOf(uint256 unixtime) external view returns (uint256 volE8); function getCurrentParameters() external view returns (uint16 lambdaE4, uint16 dataNum); function getVolatility(uint64 untilMaturity) external view returns (uint64 volatilityE8); } // File: contracts/ChainLinkAggregator/ChainLinkAggregatorInterface.sol // https://github.com/smartcontractkit/chainlink/blob/feature/whitelisted-interface/evm-contracts/src/v0.6/interfaces/AggregatorV3Interface.sol // https://github.com/smartcontractkit/chainlink/blob/feature/whitelisted-interface/evm-contracts/src/v0.6/interfaces/AggregatorInterface.sol interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); function decimals() external view returns (uint8); function latestRoundData() external view returns ( uint256 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint256 answeredInRound ); } // File: @openzeppelin/contracts/utils/SafeCast.sol /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/oracle/RegularIntervalOracle.sol /** * @dev Record chainlink price once a day */ contract RegularIntervalOracle is RegularIntervalOracleInterface { using SafeCast for uint16; using SafeCast for uint32; using SafeCast for uint256; using SafeMath for uint256; struct PriceData { uint64 priceE8; uint64 ewmaVolatilityE8; } // Max ETH Price = $1 million per ETH int256 constant MAX_VALID_ETHPRICE = 10**14; /* ========== CONSTANT VARIABLES ========== */ AggregatorInterface immutable internal _chainlinkOracle; uint256 immutable internal _interval; uint8 immutable internal _decimals; uint128 immutable internal _timeCorrectionFactor; uint128 immutable internal _oldestTimestamp; uint16 immutable internal _dataNum; /* ========== STATE VARIABLES ========== */ address internal _quantsAddress; uint256 internal _latestTimestamp; mapping(uint256 => PriceData) internal _regularIntervalPriceData; uint16 internal lambdaE4; event LambdaChanged(uint16 newLambda); event QuantsChanged(address newQuantsAddress); /* ========== CONSTRUCTOR ========== */ /** * @param quantsAddress can set optimized parameters * @param chainlinkOracleAddress Chainlink price oracle * @param startTimestamp Recording timestamp is startTimestamp +- n * interval * @param interval Daily record = 3600*24 * @param decimals Decimals of price */ constructor( uint8 decimals, uint16 initialLambdaE4, uint16 initialDataNum, uint32 initialVolE4, address quantsAddress, address chainlinkOracleAddress, uint256 startTimestamp, uint256 interval, uint256 initialRoundId ) { _dataNum = initialDataNum; lambdaE4 = initialLambdaE4; _quantsAddress = quantsAddress; _chainlinkOracle = AggregatorInterface(chainlinkOracleAddress); _interval = interval; _decimals = decimals; _timeCorrectionFactor = uint128(startTimestamp % interval); initialRoundId = _getValidRoundIDWithAggregator(initialRoundId, startTimestamp, AggregatorInterface(chainlinkOracleAddress)); int256 priceE8 = _getPriceFromChainlinkWithAggregator(initialRoundId, AggregatorInterface(chainlinkOracleAddress)); _regularIntervalPriceData[startTimestamp] = PriceData( uint256(priceE8).toUint64(), uint64(initialVolE4) ); _latestTimestamp = uint128(startTimestamp); _oldestTimestamp = uint128(startTimestamp); require(initialDataNum > 1, "Error: Decimals should be more than 0"); require(quantsAddress != address(0), "Error: Invalid initial quant address"); require(chainlinkOracleAddress != address(0), "Error: Invalid chainlink address"); require(interval != 0, "Error: Interval should be more than 0"); } /* ========== MUTABLE FUNCTIONS ========== */ /** * @notice Set new price * @dev Prices must be updated by regular interval * @param roundId is chainlink roundId */ function setPrice(uint256 roundId) public override returns (bool) { _latestTimestamp += _interval; require(_latestTimestamp <= block.timestamp, "Error: This function should be after interval"); //If next oldestTimestamp == _latestTimestamp roundId = _getValidRoundID(roundId, _latestTimestamp); _setPrice(roundId, _latestTimestamp); return true; } /** * @notice Set sequential prices * @param roundIds Array of roundIds which contain the first timestamp after the regular interval timestamp */ function setSequentialPrices(uint256[] calldata roundIds) external override returns (bool) { uint256 roundIdsLength = roundIds.length; uint256 normalizedCurrentTimestamp = getNormalizedTimeStamp(block.timestamp); require(_latestTimestamp <= normalizedCurrentTimestamp, "Error: This function should be after interval"); // If length of roundIds is too short or too long, return false if ( (normalizedCurrentTimestamp - _latestTimestamp) / _interval < roundIdsLength || roundIdsLength < 2 ) { return false; } for (uint256 i = 0; i < roundIdsLength; i++) { setPrice(roundIds[i]); } return true; } /** * @notice Set optimized parameters for EWMA only by quants address * Recalculate latest Volatility with new lambda * Recalculation starts from price at `latestTimestamp - _dataNum * _interval` */ function setOptimizedParameters(uint16 newLambdaE4) external override onlyQuants returns (bool) { require( newLambdaE4 > 9000 && newLambdaE4 < 10000, "new lambda is out of valid range" ); require( (_latestTimestamp - _oldestTimestamp) / _interval > _dataNum, "Error: Insufficient number of data registered" ); lambdaE4 = newLambdaE4; uint256 oldTimestamp = _latestTimestamp - _dataNum * _interval; uint256 pNew = _getPrice(oldTimestamp + _interval); uint256 updatedVol = _getVolatility(oldTimestamp); for (uint256 i = 0; i < _dataNum; i++) { updatedVol = _getEwmaVolatility(oldTimestamp, pNew, updatedVol); oldTimestamp += _interval; pNew = _getPrice(oldTimestamp + _interval); } _regularIntervalPriceData[_latestTimestamp].ewmaVolatilityE8 = updatedVol .toUint64(); emit LambdaChanged(newLambdaE4); return true; } /** * @notice Update quants address only by quants address */ function updateQuantsAddress(address quantsAddress) external override onlyQuants returns (bool) { _quantsAddress = quantsAddress; require(quantsAddress != address(0), "Error: Invalid new quant address"); emit QuantsChanged(quantsAddress); } /* ========== MODIFIERS ========== */ modifier onlyQuants() { require(msg.sender == _quantsAddress, "only quants address can call"); _; } /* ========== INTERNAL FUNCTIONS ========== */ /** * @return price at the `unixtime` */ function _getPrice(uint256 unixtime) internal view returns (uint256) { return _regularIntervalPriceData[unixtime].priceE8; } /** * @return Volatility at the `unixtime` */ function _getVolatility(uint256 unixtime) internal view returns (uint256) { return _regularIntervalPriceData[unixtime].ewmaVolatilityE8; } /** * @notice Get annualized ewma volatility. * @param oldTimestamp is the previous term to calculate volatility */ function _getEwmaVolatility( uint256 oldTimestamp, uint256 pNew, uint256 oldVolE8 ) internal view returns (uint256 volE8) { uint256 pOld = _getPrice(oldTimestamp); uint256 rrE8 = pNew >= pOld ? ((pNew * (10**4)) / pOld - (10**4))**2 : ((10**4) - (pNew * (10**4)) / pOld)**2; uint256 vol_2E16 = (oldVolE8**2 * lambdaE4) / 10**4 + (10**4 - lambdaE4) * rrE8 * 10**4; volE8 = _sqrt(vol_2E16); } /** * @dev Calcurate an approximation of the square root of x by Babylonian method. */ function _sqrt(uint256 x) internal pure returns (uint256 y) { if (x > 3) { uint z = x / 2 + 1; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } else if (x != 0) { y = 1; } } function _getValidRoundID(uint256 hintID, uint256 targetTimeStamp) internal view returns (uint256 roundID) { return _getValidRoundIDWithAggregator(hintID, targetTimeStamp, _chainlinkOracle); } function _getValidRoundIDWithAggregator(uint256 hintID, uint256 targetTimeStamp, AggregatorInterface _chainlinkAggregator) internal view returns (uint256 roundID) { if (hintID == 0) { hintID = _chainlinkAggregator.latestRound(); } uint256 timeStampOfHintID = _chainlinkAggregator.getTimestamp(hintID); require( timeStampOfHintID >= targetTimeStamp, "Hint round or Latest round should be registered after target time" ); require(hintID != 0, "Invalid hint ID"); for (uint256 index = hintID - 1; index > 0; index--) { uint256 timestamp = _chainlinkAggregator.getTimestamp(index); if (timestamp != 0 && timestamp <= targetTimeStamp) { return index + 1; } } require(false, "No valid round ID found"); } function _setPrice(uint256 roundId, uint256 timeStamp) internal { int256 priceE8 = _getPriceFromChainlink(roundId); require(priceE8 > 0, "Should return valid price"); uint256 ewmaVolatilityE8 = _getEwmaVolatility( timeStamp - _interval, uint256(priceE8), _getVolatility(timeStamp - _interval) ); _regularIntervalPriceData[timeStamp] = PriceData( uint256(priceE8).toUint64(), ewmaVolatilityE8.toUint64() ); } function _getPriceFromChainlink(uint256 roundId) internal view returns (int256 priceE8) { return _getPriceFromChainlinkWithAggregator(roundId, _chainlinkOracle); } function _getPriceFromChainlinkWithAggregator(uint256 roundId, AggregatorInterface _chainlinkAggregator) internal view returns (int256 priceE8) { while (true) { priceE8 = _chainlinkAggregator.getAnswer(roundId); if (priceE8 > 0 && priceE8 < MAX_VALID_ETHPRICE ) { break; } roundId -= 1; } } /* ========== CALL FUNCTIONS ========== */ /** * @notice Calculate normalized timestamp to get valid value */ function getNormalizedTimeStamp(uint256 timestamp) public view override returns (uint256) { return ((timestamp.sub(_timeCorrectionFactor)) / _interval) * _interval + _timeCorrectionFactor; } function getInfo() external view override returns (address chainlink, address quants) { return (address(_chainlinkOracle), _quantsAddress); } /** * @return Decimals of price */ function getDecimals() external view override returns (uint8) { return _decimals; } /** * @return Interval of historical data */ function getInterval() external view override returns (uint256) { return _interval; } /** * @return Latest timestamp in this oracle */ function getLatestTimestamp() external view override returns (uint256) { return _latestTimestamp; } /** * @return Oldest timestamp in this oracle */ function getOldestTimestamp() external view override returns (uint256) { return _oldestTimestamp; } function getPrice() external view override returns (uint256) { return _getPrice(_latestTimestamp); } function getCurrentParameters() external view override returns (uint16 lambda, uint16 dataNum) { return (lambdaE4, _dataNum); } function getPriceTimeOf(uint256 unixtime) external view override returns (uint256) { uint256 normalizedUnixtime = getNormalizedTimeStamp(unixtime); return _getPrice(normalizedUnixtime); } function _getCurrentVolatility() internal view returns (uint256 volE8) { uint256 latestRound = _chainlinkOracle.latestRound(); uint256 latestVolatility = _getVolatility(_latestTimestamp); uint256 currentVolatility = _getEwmaVolatility( _latestTimestamp, uint256(_getPriceFromChainlink(latestRound)), _getVolatility(_latestTimestamp) ); volE8 = latestVolatility >= currentVolatility ? latestVolatility : currentVolatility; } /** * @notice Calculate lastest ewmaVolatility * @dev Calculate new volatility with chainlink price at latest round * @param volE8 Return the larger of `latestVolatility` and `currentVolatility` */ function getVolatility() external view override returns (uint256 volE8) { volE8 = _getCurrentVolatility(); } /** * @notice This function has the same interface with Lien Volatility Oracle */ function getVolatility(uint64) external view override returns (uint64 volatilityE8) { uint256 volE8 = _getCurrentVolatility(); return volE8.toUint64(); } /** * @notice Get registered ewmaVolatility of given timestamp */ function getVolatilityTimeOf(uint256 unixtime) external view override returns (uint256 volE8) { uint256 normalizedUnixtime = getNormalizedTimeStamp(unixtime); return _regularIntervalPriceData[normalizedUnixtime].ewmaVolatilityE8; } }
* @notice Set optimized parameters for EWMA only by quants address Recalculate latest Volatility with new lambda Recalculation starts from price at `latestTimestamp - _dataNum _interval`/
function setOptimizedParameters(uint16 newLambdaE4) external override onlyQuants returns (bool) { require( newLambdaE4 > 9000 && newLambdaE4 < 10000, "new lambda is out of valid range" ); require( (_latestTimestamp - _oldestTimestamp) / _interval > _dataNum, "Error: Insufficient number of data registered" ); lambdaE4 = newLambdaE4; uint256 oldTimestamp = _latestTimestamp - _dataNum * _interval; uint256 pNew = _getPrice(oldTimestamp + _interval); uint256 updatedVol = _getVolatility(oldTimestamp); for (uint256 i = 0; i < _dataNum; i++) { updatedVol = _getEwmaVolatility(oldTimestamp, pNew, updatedVol); oldTimestamp += _interval; pNew = _getPrice(oldTimestamp + _interval); } _regularIntervalPriceData[_latestTimestamp].ewmaVolatilityE8 = updatedVol .toUint64(); emit LambdaChanged(newLambdaE4); return true; }
5,808,640
[ 1, 694, 15411, 1472, 364, 512, 59, 5535, 1338, 635, 719, 4388, 1758, 868, 11162, 4891, 26861, 30139, 598, 394, 3195, 868, 29916, 2542, 628, 6205, 622, 1375, 13550, 4921, 300, 389, 892, 2578, 225, 389, 6624, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 444, 13930, 1235, 2402, 12, 11890, 2313, 394, 12025, 41, 24, 13, 203, 565, 3903, 203, 565, 3849, 203, 565, 1338, 928, 4388, 203, 565, 1135, 261, 6430, 13, 203, 225, 288, 203, 377, 203, 565, 2583, 12, 203, 1377, 394, 12025, 41, 24, 405, 2468, 3784, 597, 394, 12025, 41, 24, 411, 12619, 16, 203, 1377, 315, 2704, 3195, 353, 596, 434, 923, 1048, 6, 203, 565, 11272, 203, 565, 2583, 12, 203, 1377, 261, 67, 13550, 4921, 300, 389, 1673, 395, 4921, 13, 342, 389, 6624, 405, 389, 892, 2578, 16, 203, 1377, 315, 668, 30, 22085, 11339, 1300, 434, 501, 4104, 6, 203, 565, 11272, 203, 565, 3195, 41, 24, 273, 394, 12025, 41, 24, 31, 203, 565, 2254, 5034, 1592, 4921, 273, 389, 13550, 4921, 300, 389, 892, 2578, 380, 389, 6624, 31, 203, 565, 2254, 5034, 293, 1908, 273, 389, 588, 5147, 12, 1673, 4921, 397, 389, 6624, 1769, 203, 565, 2254, 5034, 3526, 17431, 273, 389, 588, 17431, 30139, 12, 1673, 4921, 1769, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 892, 2578, 31, 277, 27245, 288, 203, 1377, 3526, 17431, 273, 389, 588, 41, 91, 2540, 17431, 30139, 12, 1673, 4921, 16, 293, 1908, 16, 3526, 17431, 1769, 203, 1377, 1592, 4921, 1011, 389, 6624, 31, 203, 1377, 293, 1908, 273, 389, 588, 5147, 12, 1673, 4921, 397, 389, 6624, 1769, 203, 565, 289, 203, 203, 565, 389, 16819, 4006, 5147, 751, 63, 67, 13550, 4921, 8009, 359, 2540, 17431, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; import "./ERC2746.sol"; import "./TransactionStateInterface.sol"; import "./WonkaLibrary.sol"; import "./WonkaEngineMetadata.sol"; import "./WonkaEngineRuleSets.sol"; /// @title An Ethereum contract that contains the functionality for a rules engine /// @author Aaron Kendall /// @notice 1.) Certain steps are required in order to use this engine correctly + 2.) Deployment of this contract to a blockchain is expensive (~8000000 gas) + 3.) Various require() statements are commented out to save deployment costs /// @dev Even though you can create rule trees by calling this contract directly, it is generally recommended that you create them using the Nethereum library contract WonkaEngineOpt is ERC2746 { using WonkaLibrary for *; string constant blankValue = ""; address public rulesMaster; address lastSenderAddressProvided; bool lastTransactionSuccess; // The cache of rule trees that are owned by owner mapping(address => WonkaLibrary.WonkaRuleTree) private ruletrees; // The cache that indicates if a transaction state exist for a RuleTree mapping(bytes32 => bool) transStateInd; // The cache of transaction states assigned to RuleTrees mapping(bytes32 => TransactionStateInterface) transStateMap; WonkaEngineMetadata wonkaMetadata; WonkaEngineRuleSets wonkaRuleSets; /// @dev Constructor for the rules engine /// @notice Currently, the engine will create three dummy Attributes within the cache by default, but they will be removed later constructor(address _metadataAddr, address _rulesetsAddr) { lastTransactionSuccess = false; rulesMaster = msg.sender; wonkaMetadata = WonkaEngineMetadata(_metadataAddr); wonkaRuleSets = WonkaEngineRuleSets(_rulesetsAddr); } modifier onlyEngineOwner() { require(msg.sender == rulesMaster, "No exec perm"); // Do not forget the "_;"! It will // be replaced by the actual function // body when the modifier is used. _; } modifier onlyEngineOwnerOrTreeOwner(address _RTOwner) { require((msg.sender == rulesMaster) || (msg.sender == _RTOwner), "No exec perm"); require(ruletrees[_RTOwner].isValue == true, "No RT"); // Do not forget the "_;"! It will // be replaced by the actual function // body when the modifier is used. _; } /// @dev This method will add a new Attribute to the cache. By adding Attributes, we expand the set of possible values that can be held by a record. /// @notice function addAttribute(bytes32 pAttrName, uint pMaxLen, uint pMaxNumVal, string memory pDefVal, bool pIsStr, bool pIsNum) public onlyEngineOwner override { wonkaMetadata.addAttribute(pAttrName, pMaxLen, pMaxNumVal, pDefVal, pIsStr, pIsNum); } /// @dev This method will add a new Attribute to the cache. Using flagFailImmediately is not recommended and will likely be deprecated in the near future. /// @notice Currently, only one ruletree can be defined for any given address/account function addRuleTree(address ruler, bytes32 rsName, string memory desc, bool severeFailureFlag, bool useAndOperator, bool flagFailImmediately) public onlyEngineOwner override { require(ruletrees[ruler].isValue != true, "RT already exists"); WonkaLibrary.WonkaRuleTree storage NewRuleTree = ruletrees[ruler]; NewRuleTree.ruleTreeId = rsName; NewRuleTree.description = desc; NewRuleTree.rootRuleSetName = rsName; NewRuleTree.allRuleSetList = new bytes32[](0); NewRuleTree.totalRuleCount = 0; NewRuleTree.isValue = true; wonkaRuleSets.addRuleSet(ruler, rsName, desc, "", severeFailureFlag, useAndOperator, flagFailImmediately); transStateInd[ruletrees[ruler].ruleTreeId] = false; } /// @dev This method will add a new custom operator to the cache. /// @notice function addCustomOp(bytes32 srcName, bytes32 sts, address cntrtAddr, bytes32 methName) public onlyEngineOwner { wonkaRuleSets.addCustomOp(srcName, sts, cntrtAddr, methName); } /// @dev This method will add a new RuleSet to the cache and to the indicated RuleTree. Using flagFailImmediately is not recommended and will likely be deprecated in the near future. /// @notice Currently, a RuleSet can only belong to one RuleTree and be a child of one parent RuleSet, though there are plans to have a RuleSet capable of being shared among parents function addRuleSet(address ruler, bytes32 ruleSetName, string memory desc, bytes32 parentRSName, bool severeFailureFlag, bool useAndOperator, bool flagFailImmediately) public onlyEngineOwnerOrTreeOwner(ruler) override { ruletrees[ruler].allRuleSetList.push(ruleSetName); wonkaRuleSets.addRuleSet(ruler, ruleSetName, desc, parentRSName, severeFailureFlag, useAndOperator, flagFailImmediately); } /// @dev This method will add a new Rule to the indicated RuleSet /// @notice Currently, a Rule can only belong to one RuleSet function addRule(address ruler, bytes32 ruleSetId, bytes32 ruleName, bytes32 attrName, uint rType, string memory rVal, bool notFlag, bool passiveFlag) public onlyEngineOwnerOrTreeOwner(ruler) override { wonkaRuleSets.addRule(ruler, ruleSetId, ruleName, attrName, rType, rVal, notFlag, passiveFlag); ruletrees[ruler].totalRuleCount += 1; } /// @dev This method will supply the args to the last rule added (of type Custom Operator) /// @notice Currently, a Rule can only belong to one RuleSet function addRuleCustomOpArgs(address ruler, bytes32 ruleSetId, bytes32 arg1, bytes32 arg2, bytes32 arg3, bytes32 arg4) public onlyEngineOwnerOrTreeOwner(ruler) { wonkaRuleSets.addRuleCustomOpArgs(ruler, ruleSetId, arg1, arg2, arg3, arg4); } /// @dev This method will add a new source to the mapping cache. /// @notice function addSource(bytes32 srcName, bytes32 sts, address cntrtAddr, bytes32 methName, bytes32 setMethName) public onlyEngineOwner { wonkaRuleSets.addSource(srcName, sts, cntrtAddr, methName, setMethName); } /// @dev This method will invoke the ruler's RuleTree in order to validate their stored record. This method should be invoked via a call() and not a transaction(). /// @notice This method will only return a boolean function executeRuleTree(address ruler) public onlyEngineOwnerOrTreeOwner(ruler) override returns (bool executeSuccess) { executeSuccess = true; require(ruletrees[ruler].allRuleSetList.length > 0, "Empty RT"); // NOTE: Unnecessary and commented out in order to save deployment costs (in terms of gas) // require(ruletrees[ruler].rootRuleSetName != "", "The specified RuleTree has an invalid root."); // NOTE: USE WHEN DEBUGGING IS NEEDED emit WonkaLibrary.CallRuleTree(ruler); lastSenderAddressProvided = ruler; WonkaLibrary.WonkaRuleReport memory report = WonkaLibrary.WonkaRuleReport({ ruleFailCount: 0, ruleSetIds: new bytes32[](ruletrees[ruler].totalRuleCount), ruleIds: new bytes32[](ruletrees[ruler].totalRuleCount) }); wonkaRuleSets.executeWithReport(ruler, ruletrees[ruler].rootRuleSetName, report); executeSuccess = lastTransactionSuccess = (report.ruleFailCount == 0); } /// @dev This method will return the default source function getDefaultSource() public view returns(bytes32) { return wonkaRuleSets.getDefaultSource(); } /// @dev This method will return the indicator of whether or not the last execuction of the engine was a validation success function getLastTransactionSuccess() public view returns(bool) { return lastTransactionSuccess; } /// @dev This method will return the data that composes a particular Rule function getRuleProps(address ruler, bytes32 rsId, bool evalRuleFlag, uint ruleIdx) public view override returns (bytes32, uint, bytes32, string memory, bool, bytes32[] memory) { require(ruletrees[ruler].isValue == true, "No RT"); return wonkaRuleSets.getRuleProps(ruler, rsId, evalRuleFlag, ruleIdx); } /// @dev This method will return the ID of a RuleSet that is the child of a parent RuleSet function getRuleSetChildId(address ruler, bytes32 rsId, uint rsChildIdx) public view returns (bytes32) { require(ruletrees[ruler].isValue == true, "No RT"); return wonkaRuleSets.getRuleSetChildId(ruler, rsId, rsChildIdx); } /// @dev This method will return the data that composes a particular RuleSet function getRuleSetProps(address ruler, bytes32 rsId) public view override returns (string memory, bool, bool, uint, uint, uint) { require(ruletrees[ruler].isValue == true, "No RT"); return wonkaRuleSets.getRuleSetProps(ruler, rsId); } /// @dev This method will return the data that composes a particular RuleTree function getRuleTreeProps(address ruler) public view override returns (bytes32, string memory, bytes32, uint) { require(ruletrees[ruler].isValue == true, "No RT"); return (ruletrees[ruler].ruleTreeId, ruletrees[ruler].description, ruletrees[ruler].rootRuleSetName, ruletrees[ruler].totalRuleCount); } /// @dev This method will indicate whether or not a particular source exists /// @notice This method should only be used for debugging purposes. function getIsSourceMapped(bytes32 key) public view returns(bool) { return wonkaRuleSets.getIsSourceMapped(key); } /// @dev This method will return the current number of Attributes in the cache /// @notice This method should only be used for debugging purposes. function getNumberOfAttributes() public view returns(uint) { return wonkaMetadata.getNumberOfAttributes(); } /// @dev This method will indicate whether or not the Orchestration mode has been enabled /// @notice This method should only be used for debugging purposes. function getOrchestrationMode() public view returns(bool) { return wonkaRuleSets.getOrchestrationMode(); } /// @dev This method will return the value for an Attribute that is currently stored within the ruler's record /// @notice This method should only be used for debugging purposes. function getValueOnRecord(address ruler, bytes32 key) public override returns(string memory) { return wonkaRuleSets.getValueOnRecord(ruler, key); } /// @dev This method will indicate whether or not the provided address/account has a RuleTree associated with it /// @notice This method should only be used for debugging purposes. function hasRuleTree(address ruler) public view returns(bool) { return (ruletrees[ruler].isValue == true); } function removeRuleTree(address /*_owner*/) public pure override returns (bool) { // NOTE: Does nothing currently return true; } /// @dev This method will set the flag as to whether or not the engine should run in Orchestration mode (i.e., use the sourceMap) function setOrchestrationMode(bool orchMode, bytes32 defSource) public onlyEngineOwner { wonkaRuleSets.setOrchestrationMode(orchMode, defSource); } /// @dev This method will set the transaction state to be used by a RuleTree function setTransactionState(address ruler, address transStateAddr) public { transStateInd[ruletrees[ruler].ruleTreeId] = true; transStateMap[ruletrees[ruler].ruleTreeId] = TransactionStateInterface(transStateAddr); } /// @dev This method will set an Attribute value on the record associated with the provided address/account /// @notice We do not currently check here to see if the value qualifies according to the Attribute's definition function setValueOnRecord(address ruler, bytes32 key, string memory value) public override returns(string memory) { return wonkaRuleSets.setValueOnRecord(ruler, key, value); } }
@dev This method will set an Attribute value on the record associated with the provided address/account @notice We do not currently check here to see if the value qualifies according to the Attribute's definition
function setValueOnRecord(address ruler, bytes32 key, string memory value) public override returns(string memory) { return wonkaRuleSets.setValueOnRecord(ruler, key, value); }
2,479,035
[ 1, 2503, 707, 903, 444, 392, 3601, 460, 603, 326, 1409, 3627, 598, 326, 2112, 1758, 19, 4631, 225, 1660, 741, 486, 4551, 866, 2674, 358, 2621, 309, 326, 460, 4544, 5032, 4888, 358, 326, 3601, 1807, 2379, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 5524, 1398, 2115, 12, 2867, 436, 17040, 16, 1731, 1578, 498, 16, 533, 3778, 460, 13, 1071, 3849, 1135, 12, 1080, 3778, 13, 288, 7010, 203, 3639, 327, 8462, 7282, 2175, 2785, 18, 542, 620, 1398, 2115, 12, 86, 17040, 16, 498, 16, 460, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.5; import {InitializedProxy} from "./InitializedProxy.sol"; import {PartyBid} from "./PartyBid.sol"; /** * @title PartyBid Factory * @author Anna Carroll * * WARNING: A malicious MarketWrapper contract could be used to steal user funds; * A poorly implemented MarketWrapper contract could permanently lose access to the NFT. * When deploying a PartyBid, exercise extreme caution. * Only use MarketWrapper contracts that have been audited and tested. */ contract PartyBidFactory { //======== Events ======== event PartyBidDeployed( address partyBidProxy, address creator, address nftContract, uint256 tokenId, address marketWrapper, uint256 auctionId, address splitRecipient, uint256 splitBasisPoints, string name, string symbol ); //======== Immutable storage ========= address public immutable logic; address public immutable partyDAOMultisig; address public immutable tokenVaultFactory; address public immutable weth; //======== Mutable storage ========= // PartyBid proxy => block number deployed at mapping(address => uint256) public deployedAt; //======== Constructor ========= constructor( address _partyDAOMultisig, address _tokenVaultFactory, address _weth, address _logicMarketWrapper, address _logicNftContract, uint256 _logicTokenId, uint256 _logicAuctionId ) { partyDAOMultisig = _partyDAOMultisig; tokenVaultFactory = _tokenVaultFactory; weth = _weth; // deploy logic contract PartyBid _logicContract = new PartyBid(_partyDAOMultisig, _tokenVaultFactory, _weth); // initialize logic contract _logicContract.initialize( _logicMarketWrapper, _logicNftContract, _logicTokenId, _logicAuctionId, address(0), 0, "PartyBid", "BID" ); // store logic contract address logic = address(_logicContract); } //======== Deploy function ========= function startParty( address _marketWrapper, address _nftContract, uint256 _tokenId, uint256 _auctionId, address _splitRecipient, uint256 _splitBasisPoints, string memory _name, string memory _symbol ) external returns (address partyBidProxy) { bytes memory _initializationCalldata = abi.encodeWithSignature( "initialize(address,address,uint256,uint256,address,uint256,string,string)", _marketWrapper, _nftContract, _tokenId, _auctionId, _splitRecipient, _splitBasisPoints, _name, _symbol ); partyBidProxy = address( new InitializedProxy( logic, _initializationCalldata ) ); deployedAt[partyBidProxy] = block.number; emit PartyBidDeployed( partyBidProxy, msg.sender, _nftContract, _tokenId, _marketWrapper, _auctionId, _splitRecipient, _splitBasisPoints, _name, _symbol ); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.5; /** * @title InitializedProxy * @author Anna Carroll */ contract InitializedProxy { // address of logic contract address public immutable logic; // ======== Constructor ========= constructor( address _logic, bytes memory _initializationCalldata ) { logic = _logic; // Delegatecall into the logic contract, supplying initialization calldata (bool _ok, bytes memory returnData) = _logic.delegatecall(_initializationCalldata); // Revert if delegatecall to implementation reverts require(_ok, string(returnData)); } // ======== Fallback ========= fallback() external payable { address _impl = logic; assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } // ======== Receive ========= receive() external payable {} // solhint-disable-line no-empty-blocks } /* ___ ___ ___ ___ ___ ___ ___ /\ \ /\ \ /\ \ /\ \ |\__\ /\ \ ___ /\ \ /::\ \ /::\ \ /::\ \ \:\ \ |:| | /::\ \ /\ \ /::\ \ /:/\:\ \ /:/\:\ \ /:/\:\ \ \:\ \ |:| | /:/\:\ \ \:\ \ /:/\:\ \ /::\~\:\ \ /::\~\:\ \ /::\~\:\ \ /::\ \ |:|__|__ /::\~\:\__\ /::\__\ /:/ \:\__\ /:/\:\ \:\__\ /:/\:\ \:\__\ /:/\:\ \:\__\ /:/\:\__\ /::::\__\ /:/\:\ \:|__| __/:/\/__/ /:/__/ \:|__| \/__\:\/:/ / \/__\:\/:/ / \/_|::\/:/ / /:/ \/__/ /:/~~/~ \:\~\:\/:/ / /\/:/ / \:\ \ /:/ / \::/ / \::/ / |:|::/ / /:/ / /:/ / \:\ \::/ / \::/__/ \:\ /:/ / \/__/ /:/ / |:|\/__/ \/__/ \/__/ \:\/:/ / \:\__\ \:\/:/ / /:/ / |:| | \::/__/ \/__/ \::/__/ \/__/ \|__| ~~ ~~ PartyBid v1 Anna Carroll for PartyDAO */ // SPDX-License-Identifier: MIT pragma solidity 0.8.5; // ============ External Imports: Inherited Contracts ============ // NOTE: we inherit from OpenZeppelin upgradeable contracts // because of the proxy structure used for cheaper deploys // (the proxies are NOT actually upgradeable) import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import { ERC721HolderUpgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol"; // ============ External Imports: External Contracts & Contract Interfaces ============ import { IERC721VaultFactory } from "./external/interfaces/IERC721VaultFactory.sol"; import {ITokenVault} from "./external/interfaces/ITokenVault.sol"; import { IERC721Metadata } from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import {IWETH} from "./external/interfaces/IWETH.sol"; // ============ Internal Imports ============ import {IMarketWrapper} from "./market-wrapper/IMarketWrapper.sol"; contract PartyBid is ReentrancyGuardUpgradeable, ERC721HolderUpgradeable { // ============ Enums ============ // State Transitions: // (1) AUCTION_ACTIVE on deploy // (2) AUCTION_WON or AUCTION_LOST on finalize() enum PartyStatus {AUCTION_ACTIVE, AUCTION_WON, AUCTION_LOST} // ============ Structs ============ struct Contribution { uint256 amount; uint256 previousTotalContributedToParty; } // ============ Internal Constants ============ // PartyBid version 2 uint16 public constant VERSION = 2; // tokens are minted at a rate of 1 ETH : 1000 tokens uint16 internal constant TOKEN_SCALE = 1000; // PartyDAO receives an ETH fee equal to 2.5% of the winning bid uint16 internal constant ETH_FEE_BASIS_POINTS = 250; // PartyDAO receives a token fee equal to 2.5% of the total token supply uint16 internal constant TOKEN_FEE_BASIS_POINTS = 250; // token is relisted on Fractional with an // initial reserve price equal to 2x the winning bid uint8 internal constant RESALE_MULTIPLIER = 2; // ============ Immutables ============ address public immutable partyDAOMultisig; IERC721VaultFactory public immutable tokenVaultFactory; IWETH public immutable weth; // ============ Public Not-Mutated Storage ============ // market wrapper contract exposing interface for // market auctioning the NFT IMarketWrapper public marketWrapper; // NFT contract IERC721Metadata public nftContract; // Fractionalized NFT vault responsible for post-auction value capture ITokenVault public tokenVault; // ID of auction within market contract uint256 public auctionId; // ID of token within NFT contract uint256 public tokenId; // the address that will receive a portion of the tokens // if the PartyBid wins the auction address public splitRecipient; // percent of the total token supply // taken by the splitRecipient uint256 public splitBasisPoints; // ERC-20 name and symbol for fractional tokens string public name; string public symbol; // ============ Public Mutable Storage ============ // state of the contract PartyStatus public partyStatus; // total ETH deposited by all contributors uint256 public totalContributedToParty; // the highest bid submitted by PartyBid uint256 public highestBid; // the total spent by PartyBid on the auction; // 0 if the NFT is lost; highest bid + 2.5% PartyDAO fee if NFT is won uint256 public totalSpent; // contributor => array of Contributions mapping(address => Contribution[]) public contributions; // contributor => total amount contributed mapping(address => uint256) public totalContributed; // contributor => true if contribution has been claimed mapping(address => bool) public claimed; // ============ Events ============ event Contributed( address indexed contributor, uint256 amount, uint256 previousTotalContributedToParty, uint256 totalFromContributor ); event Bid(uint256 amount); event Finalized(PartyStatus result, uint256 totalSpent, uint256 fee, uint256 totalContributed); event Claimed( address indexed contributor, uint256 totalContributed, uint256 excessContribution, uint256 tokenAmount ); // ======== Modifiers ========= modifier onlyPartyDAO() { require( msg.sender == partyDAOMultisig, "PartyBid:: only PartyDAO multisig" ); _; } // ======== Constructor ========= constructor( address _partyDAOMultisig, address _tokenVaultFactory, address _weth ) { partyDAOMultisig = _partyDAOMultisig; tokenVaultFactory = IERC721VaultFactory(_tokenVaultFactory); weth = IWETH(_weth); } // ======== Initializer ========= function initialize( address _marketWrapper, address _nftContract, uint256 _tokenId, uint256 _auctionId, address _splitRecipient, uint256 _splitBasisPoints, string memory _name, string memory _symbol ) external initializer { // initialize ReentrancyGuard and ERC721Holder __ReentrancyGuard_init(); __ERC721Holder_init(); // set storage variables marketWrapper = IMarketWrapper(_marketWrapper); nftContract = IERC721Metadata(_nftContract); tokenId = _tokenId; auctionId = _auctionId; name = _name; symbol = _symbol; // validate that party split won't retain the total token supply uint256 _remainingBasisPoints = 10000 - TOKEN_FEE_BASIS_POINTS; require(_splitBasisPoints < _remainingBasisPoints, "PartyBid::initialize: basis points can't take 100%"); // validate that a portion of the token supply is not being burned if (_splitRecipient == address(0)) { require(_splitBasisPoints == 0, "PartyBid::initialize: can't send tokens to burn addr"); } splitBasisPoints = _splitBasisPoints; splitRecipient = _splitRecipient; // validate token exists require(_getOwner() != address(0), "PartyBid::initialize: NFT getOwner failed"); // validate auction exists require( marketWrapper.auctionIdMatchesToken( _auctionId, _nftContract, _tokenId ), "PartyBid::initialize: auctionId doesn't match token" ); } // ======== External: Contribute ========= /** * @notice Contribute to the PartyBid's treasury * while the auction is still open * @dev Emits a Contributed event upon success; callable by anyone */ function contribute() external payable nonReentrant { require( partyStatus == PartyStatus.AUCTION_ACTIVE, "PartyBid::contribute: auction not active" ); address _contributor = msg.sender; uint256 _amount = msg.value; require(_amount > 0, "PartyBid::contribute: must contribute more than 0"); // get the current contract balance uint256 _previousTotalContributedToParty = totalContributedToParty; // add contribution to contributor's array of contributions Contribution memory _contribution = Contribution({ amount: _amount, previousTotalContributedToParty: _previousTotalContributedToParty }); contributions[_contributor].push(_contribution); // add to contributor's total contribution totalContributed[_contributor] = totalContributed[_contributor] + _amount; // add to party's total contribution & emit event totalContributedToParty = totalContributedToParty + _amount; emit Contributed( _contributor, _amount, _previousTotalContributedToParty, totalContributed[_contributor] ); } // ======== External: Bid ========= /** * @notice Submit a bid to the Market * @dev Reverts if insufficient funds to place the bid and pay PartyDAO fees, * or if any external auction checks fail (including if PartyBid is current high bidder) * Emits a Bid event upon success. * Callable by any contributor */ function bid() external nonReentrant { require( partyStatus == PartyStatus.AUCTION_ACTIVE, "PartyBid::bid: auction not active" ); require( totalContributed[msg.sender] > 0, "PartyBid::bid: only contributors can bid" ); require( address(this) != marketWrapper.getCurrentHighestBidder( auctionId ), "PartyBid::bid: already highest bidder" ); require( !marketWrapper.isFinalized(auctionId), "PartyBid::bid: auction already finalized" ); // get the minimum next bid for the auction uint256 _bid = marketWrapper.getMinimumBid(auctionId); // ensure there is enough ETH to place the bid including PartyDAO fee require( _bid <= getMaximumBid(), "PartyBid::bid: insufficient funds to bid" ); // submit bid to Auction contract using delegatecall (bool success, bytes memory returnData) = address(marketWrapper).delegatecall( abi.encodeWithSignature("bid(uint256,uint256)", auctionId, _bid) ); require( success, string( abi.encodePacked( "PartyBid::bid: place bid failed: ", returnData ) ) ); // update highest bid submitted & emit success event highestBid = _bid; emit Bid(_bid); } // ======== External: Finalize ========= /** * @notice Finalize the state of the auction * @dev Emits a Finalized event upon success; callable by anyone */ function finalize() external nonReentrant { require( partyStatus == PartyStatus.AUCTION_ACTIVE, "PartyBid::finalize: auction not active" ); // finalize auction if it hasn't already been done if (!marketWrapper.isFinalized(auctionId)) { marketWrapper.finalize(auctionId); } // after the auction has been finalized, // if the NFT is owned by the PartyBid, then the PartyBid won the auction address _owner = _getOwner(); partyStatus = _owner == address(this) ? PartyStatus.AUCTION_WON : PartyStatus.AUCTION_LOST; uint256 _ethFee; // if the auction was won, if (partyStatus == PartyStatus.AUCTION_WON) { // calculate PartyDAO fee & record total spent _ethFee = _getEthFee(highestBid); totalSpent = highestBid + _ethFee; // transfer ETH fee to PartyDAO _transferETHOrWETH(partyDAOMultisig, _ethFee); // deploy fractionalized NFT vault // and mint fractional ERC-20 tokens _fractionalizeNFT(); } // set the contract status & emit result emit Finalized(partyStatus, totalSpent, _ethFee, totalContributedToParty); } // ======== External: Claim ========= /** * @notice Claim the tokens and excess ETH owed * to a single contributor after the auction has ended * @dev Emits a Claimed event upon success * callable by anyone (doesn't have to be the contributor) * @param _contributor the address of the contributor */ function claim(address _contributor) external nonReentrant { // ensure auction has finalized require( partyStatus != PartyStatus.AUCTION_ACTIVE, "PartyBid::claim: auction not finalized" ); // ensure contributor submitted some ETH require( totalContributed[_contributor] != 0, "PartyBid::claim: not a contributor" ); // ensure the contributor hasn't already claimed require( !claimed[_contributor], "PartyBid::claim: contribution already claimed" ); // mark the contribution as claimed claimed[_contributor] = true; // calculate the amount of fractional NFT tokens owed to the user // based on how much ETH they contributed towards the auction, // and the amount of excess ETH owed to the user (uint256 _tokenAmount, uint256 _ethAmount) = getClaimAmounts(_contributor); // transfer tokens to contributor for their portion of ETH used _transferTokens(_contributor, _tokenAmount); // if there is excess ETH, send it back to the contributor _transferETHOrWETH(_contributor, _ethAmount); emit Claimed( _contributor, totalContributed[_contributor], _ethAmount, _tokenAmount ); } // ======== External: Emergency Escape Hatches (PartyDAO Multisig Only) ========= /** * @notice Escape hatch: in case of emergency, * PartyDAO can use emergencyWithdrawEth to withdraw * ETH stuck in the contract */ function emergencyWithdrawEth(uint256 _value) external onlyPartyDAO { _transferETHOrWETH(partyDAOMultisig, _value); } /** * @notice Escape hatch: in case of emergency, * PartyDAO can use emergencyCall to call an external contract * (e.g. to withdraw a stuck NFT or stuck ERC-20s) */ function emergencyCall(address _contract, bytes memory _calldata) external onlyPartyDAO returns (bool _success, bytes memory _returnData) { (_success, _returnData) = _contract.call(_calldata); require(_success, string(_returnData)); } /** * @notice Escape hatch: in case of emergency, * PartyDAO can force the PartyBid to finalize with status LOST * (e.g. if finalize is not callable) */ function emergencyForceLost() external onlyPartyDAO { // set partyStatus to LOST partyStatus = PartyStatus.AUCTION_LOST; // emit Finalized event emit Finalized(partyStatus, 0, 0, totalContributedToParty); } // ======== Public: Utility Calculations ========= /** * @notice Convert ETH value to equivalent token amount */ function valueToTokens(uint256 _value) public pure returns (uint256 _tokens) { _tokens = _value * TOKEN_SCALE; } /** * @notice The maximum bid that can be submitted * while paying the ETH fee to PartyDAO * @return _maxBid the maximum bid */ function getMaximumBid() public view returns (uint256 _maxBid) { _maxBid = (totalContributedToParty * 10000) / (10000 + ETH_FEE_BASIS_POINTS); } /** * @notice Calculate the amount of fractional NFT tokens owed to the contributor * based on how much ETH they contributed towards the auction, * and the amount of excess ETH owed to the contributor * based on how much ETH they contributed *not* used towards the auction * @param _contributor the address of the contributor * @return _tokenAmount the amount of fractional NFT tokens owed to the contributor * @return _ethAmount the amount of excess ETH owed to the contributor */ function getClaimAmounts(address _contributor) public view returns (uint256 _tokenAmount, uint256 _ethAmount) { require(partyStatus != PartyStatus.AUCTION_ACTIVE, "PartyBid::getClaimAmounts: party still active; amounts undetermined"); uint256 _totalContributed = totalContributed[_contributor]; if (partyStatus == PartyStatus.AUCTION_WON) { // calculate the amount of this contributor's ETH // that was used for the winning bid uint256 _totalUsedForBid = totalEthUsedForBid(_contributor); if (_totalUsedForBid > 0) { _tokenAmount = valueToTokens(_totalUsedForBid); } // the rest of the contributor's ETH should be returned _ethAmount = _totalContributed - _totalUsedForBid; } else { // if the auction was lost, no ETH was spent; // all of the contributor's ETH should be returned _ethAmount = _totalContributed; } } /** * @notice Calculate the total amount of a contributor's funds * that were used towards the winning auction bid * @dev always returns 0 until the auction has been finalized * @param _contributor the address of the contributor * @return _total the sum of the contributor's funds that were * used towards the winning auction bid */ function totalEthUsedForBid(address _contributor) public view returns (uint256 _total) { require(partyStatus != PartyStatus.AUCTION_ACTIVE, "PartyBid::totalEthUsedForBid: party still active; amounts undetermined"); // load total amount spent once from storage uint256 _totalSpent = totalSpent; // get all of the contributor's contributions Contribution[] memory _contributions = contributions[_contributor]; for (uint256 i = 0; i < _contributions.length; i++) { // calculate how much was used from this individual contribution uint256 _amount = _ethUsedForBid(_totalSpent, _contributions[i]); // if we reach a contribution that was not used, // no subsequent contributions will have been used either, // so we can stop calculating to save some gas if (_amount == 0) break; _total = _total + _amount; } } // ============ Internal: Bid ============ /** * @notice Calculate ETH fee for PartyDAO * NOTE: Remove this fee causes a critical vulnerability * allowing anyone to exploit a PartyBid via price manipulation. * See Security Review in README for more info. * @return _fee the portion of _amount represented by scaling to ETH_FEE_BASIS_POINTS */ function _getEthFee(uint256 _winningBid) internal pure returns (uint256 _fee) { _fee = (_winningBid * ETH_FEE_BASIS_POINTS) / 10000; } /** * @notice Calculate token amount for specified token recipient * @return _totalSupply the total token supply * @return _partyDAOAmount the amount of tokens for partyDAO fee, * which is equivalent to TOKEN_FEE_BASIS_POINTS of total supply * @return _splitRecipientAmount the amount of tokens for the token recipient, * which is equivalent to splitBasisPoints of total supply */ function _getTokenInflationAmounts(uint256 _winningBid) internal view returns (uint256 _totalSupply, uint256 _partyDAOAmount, uint256 _splitRecipientAmount) { // the token supply will be inflated to provide a portion of the // total supply for PartyDAO, and a portion for the splitRecipient uint256 inflationBasisPoints = TOKEN_FEE_BASIS_POINTS + splitBasisPoints; _totalSupply = valueToTokens((_winningBid * 10000) / (10000 - inflationBasisPoints)); // PartyDAO receives TOKEN_FEE_BASIS_POINTS of the total supply _partyDAOAmount = (_totalSupply * TOKEN_FEE_BASIS_POINTS) / 10000; // splitRecipient receives splitBasisPoints of the total supply _splitRecipientAmount = (_totalSupply * splitBasisPoints) / 10000; } // ============ Internal: Finalize ============ /** * @notice Query the NFT contract to get the token owner * @dev nftContract must implement the ERC-721 token standard exactly: * function ownerOf(uint256 _tokenId) external view returns (address); * See https://eips.ethereum.org/EIPS/eip-721 * @dev Returns address(0) if NFT token or NFT contract * no longer exists (token burned or contract self-destructed) * @return _owner the owner of the NFT */ function _getOwner() internal view returns (address _owner) { (bool success, bytes memory returnData) = address(nftContract).staticcall( abi.encodeWithSignature( "ownerOf(uint256)", tokenId ) ); if (success && returnData.length > 0) { _owner = abi.decode(returnData, (address)); } } /** * @notice Upon winning the auction, transfer the NFT * to fractional.art vault & mint fractional ERC-20 tokens */ function _fractionalizeNFT() internal { // approve fractionalized NFT Factory to withdraw NFT nftContract.approve(address(tokenVaultFactory), tokenId); // PartyBid "votes" for a reserve price on Fractional // equal to 2x the winning bid uint256 _listPrice = RESALE_MULTIPLIER * highestBid; // users receive tokens at a rate of 1:TOKEN_SCALE for each ETH they contributed that was ultimately spent // partyDAO receives a percentage of the total token supply equivalent to TOKEN_FEE_BASIS_POINTS // splitRecipient receives a percentage of the total token supply equivalent to splitBasisPoints (uint256 _tokenSupply, uint256 _partyDAOAmount, uint256 _splitRecipientAmount) = _getTokenInflationAmounts(totalSpent); // deploy fractionalized NFT vault uint256 vaultNumber = tokenVaultFactory.mint( name, symbol, address(nftContract), tokenId, _tokenSupply, _listPrice, 0 ); // store token vault address to storage tokenVault = ITokenVault(tokenVaultFactory.vaults(vaultNumber)); // transfer curator to null address (burn the curator role) tokenVault.updateCurator(address(0)); // transfer tokens to PartyDAO multisig _transferTokens(partyDAOMultisig, _partyDAOAmount); // transfer tokens to token recipient if (splitRecipient != address(0)) { _transferTokens(splitRecipient, _splitRecipientAmount); } } // ============ Internal: Claim ============ /** * @notice Calculate the amount that was used towards * the winning auction bid from a single Contribution * @param _contribution the Contribution struct * @return the amount of funds from this contribution * that were used towards the winning auction bid */ function _ethUsedForBid(uint256 _totalSpent, Contribution memory _contribution) internal view returns (uint256) { if ( _contribution.previousTotalContributedToParty + _contribution.amount <= _totalSpent ) { // contribution was fully used return _contribution.amount; } else if ( _contribution.previousTotalContributedToParty < _totalSpent ) { // contribution was partially used return _totalSpent - _contribution.previousTotalContributedToParty; } // contribution was not used return 0; } // ============ Internal: TransferTokens ============ /** * @notice Transfer tokens to a recipient * @param _to recipient of tokens * @param _value amount of tokens */ function _transferTokens(address _to, uint256 _value) internal { // skip if attempting to send 0 tokens if (_value == 0) { return; } // guard against rounding errors; // if token amount to send is greater than contract balance, // send full contract balance uint256 _partyBidBalance = tokenVault.balanceOf(address(this)); if (_value > _partyBidBalance) { _value = _partyBidBalance; } tokenVault.transfer(_to, _value); } // ============ Internal: TransferEthOrWeth ============ /** * @notice Attempt to transfer ETH to a recipient; * if transferring ETH fails, transfer WETH insteads * @param _to recipient of ETH or WETH * @param _value amount of ETH or WETH */ function _transferETHOrWETH(address _to, uint256 _value) internal { // skip if attempting to send 0 ETH if (_value == 0) { return; } // guard against rounding errors; // if ETH amount to send is greater than contract balance, // send full contract balance if (_value > address(this).balance) { _value = address(this).balance; } // Try to transfer ETH to the given recipient. if (!_attemptETHTransfer(_to, _value)) { // If the transfer fails, wrap and send as WETH weth.deposit{value: _value}(); weth.transfer(_to, _value); // At this point, the recipient can unwrap WETH. } } /** * @notice Attempt to transfer ETH to a recipient * @dev Sending ETH is not guaranteed to succeed * this method will return false if it fails. * We will limit the gas used in transfers, and handle failure cases. * @param _to recipient of ETH * @param _value amount of ETH */ function _attemptETHTransfer(address _to, uint256 _value) internal returns (bool) { // Here increase the gas limit a reasonable amount above the default, and try // to send ETH to the recipient. // NOTE: This might allow the recipient to attempt a limited reentrancy attack. (bool success, ) = _to.call{value: _value, gas: 30000}(""); return success; } } // 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 "../IERC721ReceiverUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable { function __ERC721Holder_init() internal initializer { __ERC721Holder_init_unchained(); } function __ERC721Holder_init_unchained() internal initializer { } /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } uint256[50] private __gap; } //SPDX-License-Identifier: MIT pragma solidity 0.8.5; interface IERC721VaultFactory { /// @notice the mapping of vault number to vault address function vaults(uint256) external returns (address); /// @notice the function to mint a new vault /// @param _name the desired name of the vault /// @param _symbol the desired sumbol of the vault /// @param _token the ERC721 token address fo the NFT /// @param _id the uint256 ID of the token /// @param _listPrice the initial price of the NFT /// @return the ID of the vault function mint(string memory _name, string memory _symbol, address _token, uint256 _id, uint256 _supply, uint256 _listPrice, uint256 _fee) external returns(uint256); } //SPDX-License-Identifier: MIT pragma solidity 0.8.5; interface ITokenVault { /// @notice allow curator to update the curator address /// @param _curator the new curator function updateCurator(address _curator) external; /** * @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) external returns (bool); /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) external view returns (uint256); } // 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.5; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.5; /** * @title IMarketWrapper * @author Anna Carroll * @notice IMarketWrapper provides a common interface for * interacting with NFT auction markets. * Contracts can abstract their interactions with * different NFT markets using IMarketWrapper. * NFT markets can become compatible with any contract * using IMarketWrapper by deploying a MarketWrapper contract * that implements this interface using the logic of their Market. * * WARNING: MarketWrapper contracts should NEVER write to storage! * When implementing a MarketWrapper, exercise caution; a poorly implemented * MarketWrapper contract could permanently lose access to the NFT or user funds. */ interface IMarketWrapper { /** * @notice Given the auctionId, nftContract, and tokenId, check that: * 1. the auction ID matches the token * referred to by tokenId + nftContract * 2. the auctionId refers to an *ACTIVE* auction * (e.g. an auction that will accept bids) * within this market contract * 3. any additional validation to ensure that * a PartyBid can bid on this auction * (ex: if the market allows arbitrary bidding currencies, * check that the auction currency is ETH) * Note: This function probably should have been named "isValidAuction" * @dev Called in PartyBid.sol in `initialize` at line 174 * @return TRUE if the auction is valid */ function auctionIdMatchesToken( uint256 auctionId, address nftContract, uint256 tokenId ) external view returns (bool); /** * @notice Calculate the minimum next bid for this auction. * PartyBid contracts always submit the minimum possible * bid that will be accepted by the Market contract. * usually, this is either the reserve price (if there are no bids) * or a certain percentage increase above the current highest bid * @dev Called in PartyBid.sol in `bid` at line 251 * @return minimum bid amount */ function getMinimumBid(uint256 auctionId) external view returns (uint256); /** * @notice Query the current highest bidder for this auction * It is assumed that there is always 1 winning highest bidder for an auction * This is used to ensure that PartyBid cannot outbid itself if it is already winning * @dev Called in PartyBid.sol in `bid` at line 241 * @return highest bidder */ function getCurrentHighestBidder(uint256 auctionId) external view returns (address); /** * @notice Submit bid to Market contract * @dev Called in PartyBid.sol in `bid` at line 259 */ function bid(uint256 auctionId, uint256 bidAmount) external; /** * @notice Determine whether the auction has been finalized * Used to check if it is still possible to bid * And to determine whether the PartyBid should finalize the auction * @dev Called in PartyBid.sol in `bid` at line 247 * @dev and in `finalize` at line 288 * @return TRUE if the auction has been finalized */ function isFinalized(uint256 auctionId) external view returns (bool); /** * @notice Finalize the results of the auction * on the Market contract * It is assumed that this operation is performed once for each auction, * that after it is done the auction is over and the NFT has been * transferred to the auction winner. * @dev Called in PartyBid.sol in `finalize` at line 289 */ function finalize(uint256 auctionId) external; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../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); }
============ External Imports: External Contracts & Contract Interfaces ============
import { IERC721VaultFactory } from "./external/interfaces/IERC721VaultFactory.sol";
102,668
[ 1, 14468, 11352, 2221, 4363, 30, 11352, 30131, 473, 13456, 27152, 422, 1432, 631, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5666, 288, 203, 565, 467, 654, 39, 27, 5340, 12003, 1733, 203, 97, 628, 25165, 9375, 19, 15898, 19, 45, 654, 39, 27, 5340, 12003, 1733, 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 ]
pragma solidity 0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } interface TokenInterface { function totalSupply() external constant returns (uint); function balanceOf(address tokenOwner) external constant returns (uint balance); function allowance(address tokenOwner, address spender) external constant 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 burn(uint256 _value) external; event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Burn(address indexed burner, uint256 value); } contract PVCCrowdsale is Ownable{ using SafeMath for uint256; // The token being sold TokenInterface public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // how many token units a buyer gets per wei uint256 public ratePerWei = 1000; // amount of raised money in wei uint256 public weiRaised; uint256 public TOKENS_SOLD; uint256 maxTokensToSale; uint256 TokensForTeamVesting; uint256 TokensForAdvisorVesting; uint256 bonusInPreSalePhase1; uint256 bonusInPreSalePhase2; uint256 bonusInPublicSalePhase1; uint256 bonusInPublicSalePhase2; uint256 bonusInPublicSalePhase3; bool isCrowdsalePaused = false; uint256 totalDurationInDays = 75 days; mapping(address=>bool) isAddressWhiteListed; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function PVCCrowdsale(uint256 _startTime, address _wallet, address _tokenAddress) public { require(_wallet != 0x0); //TODO: Uncomment the following before deployment on main network require(_startTime >=now); startTime = _startTime; //TODO: Comment the following when deploying on main network //startTime = now; endTime = startTime + totalDurationInDays; require(endTime >= startTime); owner = _wallet; maxTokensToSale = 32500000 * 10 ** 18; bonusInPreSalePhase1 = 30; bonusInPreSalePhase2 = 25; bonusInPublicSalePhase1 = 20; bonusInPreSalePhase2 = 10; bonusInPublicSalePhase3 = 5; TokensForTeamVesting = 7000000 * 10 ** 18; TokensForAdvisorVesting = 3000000 * 10 ** 18; token = TokenInterface(_tokenAddress); } // fallback function can be used to buy tokens function () public payable { buyTokens(msg.sender); } function determineBonus(uint tokens) internal view returns (uint256 bonus) { uint256 timeElapsed = now - startTime; uint256 timeElapsedInDays = timeElapsed.div(1 days); //Closed pre-sale phase 1 (8 days) if (timeElapsedInDays <8) { bonus = tokens.mul(bonusInPreSalePhase1); bonus = bonus.div(100); require (TOKENS_SOLD.add(tokens.add(bonus)) <= maxTokensToSale); } //Closed pre-sale phase 2 (8 days) else if (timeElapsedInDays >=8 && timeElapsedInDays <16) { bonus = tokens.mul(bonusInPreSalePhase2); bonus = bonus.div(100); require (TOKENS_SOLD.add(tokens.add(bonus)) <= maxTokensToSale); } //Public sale phase 1 (30 days) else if (timeElapsedInDays >=16 && timeElapsedInDays <46) { bonus = tokens.mul(bonusInPublicSalePhase1); bonus = bonus.div(100); require (TOKENS_SOLD.add(tokens.add(bonus)) <= maxTokensToSale); } //Public sale phase 2 (11 days) else if (timeElapsedInDays >=46 && timeElapsedInDays <57) { bonus = tokens.mul(bonusInPublicSalePhase2); bonus = bonus.div(100); require (TOKENS_SOLD.add(tokens.add(bonus)) <= maxTokensToSale); } //Public sale phase 3 (6 days) else if (timeElapsedInDays >=57 && timeElapsedInDays <63) { bonus = tokens.mul(bonusInPublicSalePhase3); bonus = bonus.div(100); require (TOKENS_SOLD.add(tokens.add(bonus)) <= maxTokensToSale); } //Public sale phase 4 (11 days) else { bonus = 0; } } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != 0x0); require(isCrowdsalePaused == false); require(isAddressWhiteListed[beneficiary] == true); require(validPurchase()); require(TOKENS_SOLD<maxTokensToSale); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(ratePerWei); uint256 bonus = determineBonus(tokens); tokens = tokens.add(bonus); // update state weiRaised = weiRaised.add(weiAmount); token.transfer(beneficiary,tokens); emit TokenPurchase(owner, beneficiary, weiAmount, tokens); TOKENS_SOLD = TOKENS_SOLD.add(tokens); forwardFunds(); } // send ether to the fund collection wallet function forwardFunds() internal { owner.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > endTime; } /** * function to change the end timestamp of the ico * can only be called by owner wallet **/ function changeEndDate(uint256 endTimeUnixTimestamp) public onlyOwner{ endTime = endTimeUnixTimestamp; } /** * function to change the start timestamp of the ico * can only be called by owner wallet **/ function changeStartDate(uint256 startTimeUnixTimestamp) public onlyOwner{ startTime = startTimeUnixTimestamp; } /** * function to change the rate of tokens * can only be called by owner wallet **/ function setPriceRate(uint256 newPrice) public onlyOwner { ratePerWei = newPrice; } /** * function to pause the crowdsale * can only be called from owner wallet **/ function pauseCrowdsale() public onlyOwner { isCrowdsalePaused = true; } /** * function to resume the crowdsale if it is paused * can only be called from owner wallet **/ function resumeCrowdsale() public onlyOwner { isCrowdsalePaused = false; } /** * function through which owner can remove an address from whitelisting **/ function addAddressToWhitelist(address _whitelist) public onlyOwner { isAddressWhiteListed[_whitelist]= true; } /** * function through which owner can whitelist an address **/ function removeAddressToWhitelist(address _whitelist) public onlyOwner { isAddressWhiteListed[_whitelist]= false; } /** * function through which owner can take back the tokens from the contract **/ function takeTokensBack() public onlyOwner { uint remainingTokensInTheContract = token.balanceOf(address(this)); token.transfer(owner,remainingTokensInTheContract); } /** * once the ICO has ended, owner can send all the unsold tokens to treasury address **/ function sendUnsoldTokensToTreasury(address treasury) public onlyOwner { require(hasEnded()); uint remainingTokensInTheContract = token.balanceOf(address(this)); token.transfer(treasury,remainingTokensInTheContract); } }
* event for token purchase logging @param purchaser who paid for the tokens @param beneficiary who got the tokens @param value weis paid for purchase @param amount amount of tokens purchased/TODO: Uncomment the following before deployment on main networkTODO: Comment the following when deploying on main networkstartTime = now;
{ require(_wallet != 0x0); require(_startTime >=now); startTime = _startTime; endTime = startTime + totalDurationInDays; require(endTime >= startTime); owner = _wallet; maxTokensToSale = 32500000 * 10 ** 18; bonusInPreSalePhase1 = 30; bonusInPreSalePhase2 = 25; bonusInPublicSalePhase1 = 20; bonusInPreSalePhase2 = 10; bonusInPublicSalePhase3 = 5; TokensForTeamVesting = 7000000 * 10 ** 18; TokensForAdvisorVesting = 3000000 * 10 ** 18; token = TokenInterface(_tokenAddress); }
2,261,312
[ 1, 2575, 364, 1147, 23701, 2907, 225, 5405, 343, 14558, 10354, 30591, 364, 326, 2430, 225, 27641, 74, 14463, 814, 10354, 2363, 326, 2430, 225, 460, 732, 291, 30591, 364, 23701, 225, 3844, 3844, 434, 2430, 5405, 343, 8905, 19, 6241, 30, 1351, 3469, 326, 3751, 1865, 6314, 603, 2774, 2483, 6241, 30, 9821, 326, 3751, 1347, 7286, 310, 603, 2774, 2483, 1937, 950, 273, 2037, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 288, 203, 377, 203, 565, 2583, 24899, 19177, 480, 374, 92, 20, 1769, 203, 565, 2583, 24899, 1937, 950, 1545, 3338, 1769, 203, 565, 8657, 273, 389, 1937, 950, 31, 21281, 377, 203, 565, 13859, 273, 8657, 397, 2078, 5326, 382, 9384, 31, 203, 565, 2583, 12, 409, 950, 1545, 8657, 1769, 203, 27699, 565, 3410, 273, 389, 19177, 31, 203, 377, 203, 565, 943, 5157, 774, 30746, 273, 890, 2947, 11706, 380, 1728, 2826, 6549, 31, 203, 377, 203, 565, 324, 22889, 382, 1386, 30746, 11406, 21, 273, 5196, 31, 203, 565, 324, 22889, 382, 1386, 30746, 11406, 22, 273, 6969, 31, 203, 565, 324, 22889, 382, 4782, 30746, 11406, 21, 273, 4200, 31, 203, 565, 324, 22889, 382, 1386, 30746, 11406, 22, 273, 1728, 31, 203, 565, 324, 22889, 382, 4782, 30746, 11406, 23, 273, 1381, 31, 203, 377, 203, 565, 13899, 1290, 8689, 58, 10100, 273, 2371, 9449, 380, 1728, 2826, 6549, 31, 203, 565, 13899, 1290, 28087, 58, 10100, 273, 890, 9449, 380, 1728, 2826, 6549, 31, 203, 565, 1147, 273, 29938, 24899, 2316, 1887, 1769, 203, 225, 289, 203, 21281, 21281, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x499f3911aeEE63aB82c6979Fa27Af3AD0e6EACf4/sources/MasterEgyptian.sol
Safe anubis transfer function, just in case if rounding error causes pool to not have enough ANUBISs.
function safeAnubisTransfer(address _to, uint256 _amount) internal { uint256 anubisBal = anubis.balanceOf(address(this)); if (_amount > anubisBal) { anubis.transfer(_to, anubisBal); anubis.transfer(_to, _amount); } }
16,043,221
[ 1, 9890, 392, 373, 291, 7412, 445, 16, 2537, 316, 648, 309, 13885, 555, 14119, 2845, 358, 486, 1240, 7304, 8175, 3457, 5127, 87, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 979, 373, 291, 5912, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 2713, 288, 203, 3639, 2254, 5034, 392, 373, 291, 38, 287, 273, 392, 373, 291, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 67, 8949, 405, 392, 373, 291, 38, 287, 13, 288, 203, 5411, 392, 373, 291, 18, 13866, 24899, 869, 16, 392, 373, 291, 38, 287, 1769, 203, 5411, 392, 373, 291, 18, 13866, 24899, 869, 16, 389, 8949, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); } contract KyberInterface { function trade( address src, uint srcAmount, address dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId ) public payable returns (uint); function getExpectedRate( address src, address dest, uint srcQty ) public view returns (uint, uint); } contract Helper { /** * @dev get ethereum address for trade */ function getAddressETH() public pure returns (address eth) { eth = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } /** * @dev get kyber proxy address */ function getAddressKyber() public pure returns (address kyber) { kyber = 0x818E6FECD516Ecc3849DAf6845e3EC868087B755; } /** * @dev get admin address */ function getAddressAdmin() public pure returns (address admin) { admin = 0x7284a8451d9a0e7Dc62B3a71C0593eA2eC5c5638; } /** * @dev gets ETH & token balance * @param src is the token being sold * @return ethBal - if not erc20, eth balance * @return tknBal - if not eth, erc20 balance */ function getBal(address src, address _owner) public view returns (uint, uint) { uint tknBal; if (src != getAddressETH()) { tknBal = IERC20(src).balanceOf(address(_owner)); } return (address(_owner).balance, tknBal); } /** * @dev getting rates from Kyber * @param src is the token being sold * @param dest is the token being bought * @param srcAmt is the amount of token being sold * @return expectedRate - the current rate * @return slippageRate - rate with 3% slippage */ function getExpectedRate( address src, address dest, uint srcAmt ) public view returns ( uint expectedRate, uint slippageRate ) { (expectedRate,) = KyberInterface(getAddressKyber()).getExpectedRate(src, dest, srcAmt); slippageRate = (expectedRate / 100) * 99; // changing slippage rate upto 99% } /** * @dev fetching token from the trader if ERC20 * @param trader is the trader * @param src is the token which is being sold * @param srcAmt is the amount of token being sold */ function getToken(address trader, address src, uint srcAmt) internal returns (uint ethQty) { if (src == getAddressETH()) { require(msg.value == srcAmt, "not-enough-src"); ethQty = srcAmt; } else { IERC20 tknContract = IERC20(src); setApproval(tknContract, srcAmt); tknContract.transferFrom(trader, address(this), srcAmt); } } /** * @dev setting allowance to kyber for the "user proxy" if required * @param token is the token * @param srcAmt is the amount of token to sell */ function setApproval(IERC20 tknContract, uint srcAmt) internal returns (uint) { uint tokenAllowance = tknContract.allowance(address(this), getAddressKyber()); if (srcAmt > tokenAllowance) { tknContract.approve(getAddressKyber(), 2**255); } } } contract Swap is Helper { /** * @param what 0 for BUY & 1 for SELL */ event LogTrade( uint what, // 0 for BUY & 1 for SELL address src, uint srcAmt, address dest, uint destAmt, address beneficiary, uint minConversionRate, address affiliate ); /** * @dev buying token where destAmt is fixed * @param src - token to sell * @param dest - token to buy * @param srcAmt - token amount to sell * @param maxDestAmt is the max amount of token to be bought */ function buy( address src, address dest, uint srcAmt, uint maxDestAmt, uint slippageRate ) public payable returns (uint destAmt) { uint ethQty = getToken(msg.sender, src, srcAmt); destAmt = KyberInterface(getAddressKyber()).trade.value(ethQty)( src, srcAmt, dest, msg.sender, maxDestAmt, slippageRate, getAddressAdmin() ); // maxDestAmt usecase implementated on user proxy if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } else if (src != getAddressETH()) { IERC20 srcTkn = IERC20(src); uint srcBal = srcTkn.balanceOf(address(this)); if (srcBal > 0) { srcTkn.transfer(msg.sender, srcBal); } } emit LogTrade( 0, src, srcAmt, dest, destAmt, msg.sender, slippageRate, getAddressAdmin() ); } /** * @dev selling token where srcAmt is fixed * @param src - token to sell * @param dest - token to buy * @param srcAmt - token amount to sell */ function sell( address src, address dest, uint srcAmt, uint slippageRate ) public payable returns (uint destAmt) { uint ethQty = getToken(msg.sender, src, srcAmt); destAmt = KyberInterface(getAddressKyber()).trade.value(ethQty)( src, srcAmt, dest, msg.sender, 2**255, slippageRate, getAddressAdmin() ); emit LogTrade( 1, src, srcAmt, dest, destAmt, msg.sender, slippageRate, getAddressAdmin() ); } } contract InstaTrade is Swap { uint public version; /** * @dev setting up variables on deployment * 1...2...3 versioning in each subsequent deployments */ constructor(uint _version) public { version = _version; } }
* @dev getting rates from Kyber @param src is the token being sold @param dest is the token being bought @param srcAmt is the amount of token being sold @return expectedRate - the current rate @return slippageRate - rate with 3% slippage/
function getExpectedRate( address src, address dest, uint srcAmt ) public view returns ( uint expectedRate, uint slippageRate ) { (expectedRate,) = KyberInterface(getAddressKyber()).getExpectedRate(src, dest, srcAmt); }
5,444,621
[ 1, 588, 1787, 17544, 628, 1475, 93, 744, 225, 1705, 353, 326, 1147, 3832, 272, 1673, 225, 1570, 353, 326, 1147, 3832, 800, 9540, 225, 1705, 31787, 353, 326, 3844, 434, 1147, 3832, 272, 1673, 327, 2665, 4727, 300, 326, 783, 4993, 327, 272, 3169, 2433, 4727, 300, 4993, 598, 890, 9, 272, 3169, 2433, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 6861, 4727, 12, 203, 3639, 1758, 1705, 16, 203, 3639, 1758, 1570, 16, 203, 3639, 2254, 1705, 31787, 203, 565, 262, 1071, 1476, 1135, 261, 203, 3639, 2254, 2665, 4727, 16, 203, 3639, 2254, 272, 3169, 2433, 4727, 203, 565, 262, 203, 565, 288, 203, 3639, 261, 3825, 4727, 16, 13, 273, 1475, 93, 744, 1358, 12, 588, 1887, 47, 93, 744, 1435, 2934, 588, 6861, 4727, 12, 4816, 16, 1570, 16, 1705, 31787, 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 ]
./partial_match/1/0x43e967c68D00C5670382D2C00689400a107f7178/sources/CoffeeWars.sol
This function is external because it will only be called from outside of this contractThis function returns a booleanCall the internal _burn function making sure to pass in true to make sure owner or approved checks are enforcedReturn true
function burn(uint256 _tokenId) external returns(bool){ _burn(_tokenId,true); return true; }
4,274,153
[ 1, 2503, 445, 353, 3903, 2724, 518, 903, 1338, 506, 2566, 628, 8220, 434, 333, 6835, 2503, 445, 1135, 279, 1250, 1477, 326, 2713, 389, 70, 321, 445, 10480, 3071, 358, 1342, 316, 638, 358, 1221, 3071, 3410, 578, 20412, 4271, 854, 570, 19778, 990, 638, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18305, 12, 11890, 5034, 389, 2316, 548, 13, 3903, 1135, 12, 6430, 15329, 203, 540, 203, 3639, 389, 70, 321, 24899, 2316, 548, 16, 3767, 1769, 203, 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 ]
//SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import '../Tree/TreeLib.sol'; import '../Array/ArrayLibUInt32.sol'; /** * @dev An optimized uint32 min/max heap * * Heap are efficient in keeping track of the min/max of a set of elements. The * root of the heap is always the min/max and this applies recursively, meaning any parent * MUST be less/greater than its children. * * The HeapLibUInt32 uses TreeLib for computing indices for traversal within the tree * and ArrayLibUInt32 as a storage medium. * * See https://en.wikipedia.org/wiki/Heap_(data_structure) * * Note: While HeapLibUInt32 stores uint32, it accepts a custom comparator function that * it calls using staticall(). For example, one can encode the compare value in the lower * 8 bits, store a custom value in the upper 24 bits, and only compare the lower 8bits when * determining sort order within the heap. * */ library HeapLibUInt32 { using ArrayLibUInt32 for bytes32; /** * @dev Call comparator function returning true/false. * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * @return result * * Note: The compareSelector MUST be implemented in the parent contract using * the library. The heap invariant is compare(parent,child) = true. So for a min-heap * use a < b. * * Potential improvements: * - Replace staticall with jumpcall (internal) */ function compare( uint32 a, uint32 b, bytes4 compareSelector ) internal view returns (bool result) { (, bytes memory compareBytes) = address(this).staticcall(abi.encodeWithSelector(compareSelector, a, b)); assembly { result := mload(add(compareBytes, 32)) } } /** * @dev Length of heap. * @param slot storage * @return length */ function len(bytes32 slot) internal view returns (uint256 length) { length = slot.len(); } /** * @dev Height of heap tree. * @param slot storage * @param a items per slot * @param b leaves * @return height */ function height( bytes32 slot, uint256 a, uint256 b ) internal view returns (uint256) { uint256 length = slot.len(); return TreeLib.height(a, b, length); } /** * @dev Max items heap can hold before a height increase. * @param slot storage * @param a items per slot * @param b leaves * @return maxLength * * Note: This function is used to estimate SSTORE costs since gas cost increases * with tree height. */ function maxLength( bytes32 slot, uint256 a, uint256 b ) internal view returns (uint256) { uint256 h = height(slot, a, b); return TreeLib.maxLength(a, b, h); } /** * @dev Get item at tree[i] * @param slot storage slot * @param i index * @return value * * Note: Values are NOT sorted, but heap-sorted meaning the only guarantee * is that get(slot,0) will be the min/max. */ function get(bytes32 slot, uint256 i) internal view returns (uint32 value) { value = slot.get(i); } /** * @dev Get heap root * @param slot storage slot * @return value */ function root(bytes32 slot) internal view returns (uint32 value) { value = slot.get(0); } /** * @dev Get parent node index * @param a items per slot * @param b leaves * @param i, node index * @return parentIdx */ function parentIdx( uint256 a, uint256 b, uint256 i ) internal pure returns (uint256) { return TreeLib.parentIdx(a, b, i); } /** * @dev Get children node indices * @param a items per slot * @param b leaves * @param i, node index * @return leavesIdx[] */ function leavesIdx( uint256 a, uint256 b, uint256 i ) internal pure returns (uint256[] memory) { return TreeLib.leavesIdx(a, b, i); } /** * @dev Get parent node value * @param slot storage * @param a items per slot * @param b leaves * @param i, node index * @return parent */ function parent( bytes32 slot, uint256 a, uint256 b, uint256 i ) internal view returns (uint32) { uint256 pIdx = TreeLib.parentIdx(a, b, i); return slot.get(pIdx); } /** * @dev Get children node values * @param slot storage * @param a items per slot * @param b leaves * @param i, node index * @return leaves[] */ function leaves( bytes32 slot, uint256 a, uint256 b, uint256 i ) internal view returns (uint32[] memory) { uint256[] memory lIdx = TreeLib.leavesIdx(a, b, i); uint32[] memory le = new uint32[](lIdx.length); for (uint256 j; j < lIdx.length; j++) { le[j] = slot.get(lIdx[j]); } return le; } /** * @dev Overite a value at an index, and heapify with new value * @param slot storage * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * @param i index * @param val value * * Note: This is a niche use case for the heap as it replaces an existing value. * Developers should favor push(), remove(). */ function set( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector, uint256 i, uint32 val ) internal { slot.set(i, val); if (compare(slot.get(i), slot.get(TreeLib.parentIdx(a, b, i)), compareSelector)) { // a < parent, heapifyUp heapifyUp(slot, a, b, compareSelector, i); } else { heapifyDown(slot, a, b, compareSelector, i); } } /** * @dev Push a new value and heapify. * @param slot storage * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * @param val value */ function push( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector, uint32 val ) internal { slot.push(val); heapifyUp(slot, a, b, compareSelector, slot.len() - 1); } /** * @dev Remove value at index and heapify. * @param slot storage * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * @param i index * @return v */ function remove( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector, uint256 i ) internal returns (uint32 v) { v = slot.get(i); slot.set(i, 0); //clear slot uint256 length; assembly { length := sload(slot) sstore(slot, sub(length, 1)) //decrease length } slot.swap(i, length - 1); //Replace with last element heapifyDown(slot, a, b, compareSelector, i); //Heapify down } /** * @dev Remove heap root and heapify. * @param slot storage * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * @return v */ function removeRoot( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector ) internal returns (uint32 v) { return remove(slot, a, b, compareSelector, 0); } /** * @dev Search heap for first occurrence. * @param slot storage * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * @param v search value * @param idx index hint * @return index * * Note: We use the index hint as a starting point for our search. Instead * of doing a breadth-first search from the root, we start at our hint and * recurse parents or leaves from there. */ function search( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector, uint32 v, uint256 idx ) internal view returns (uint256) { //Check hint index if (v == slot.get(idx)) { return idx; } //Check parent index idx = searchUp(slot, a, b, compareSelector, v, idx); if (v == slot.get(idx)) { return idx; } //Check leaf indices uint256[] memory startLeafIndices = TreeLib.leavesIdx(a, b, idx); // leaf indices in sorted order idx = searchDown(slot, a, b, compareSelector, v, startLeafIndices); // reverts if not found return idx; } /** * @dev Search heap depth-first recusing up parents nodes * @param slot storage * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * @param v search value * @param idx start index * @return index * * Note: This does not search based on equality but rather continues recursing * until the parent node would correctly be the search value's parent. In * a min-heap, this would equate to recursing up to the first root less than the * search value. Base case returns the root with idx=0. * */ function searchUp( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector, uint32 v, uint256 idx ) internal view returns (uint256) { uint256 length = slot.len(); require(idx < length, 'HeapLibUInt32.searchUp: idx out of bounds.'); while (compare(v, slot.get(idx), compareSelector) && idx != 0) { // v < heap[i] (min-heap), recurse parents idx = TreeLib.parentIdx(a, b, idx); } return idx; } /** * @dev Search heap breadth-first recursing down leaves * @param slot storage * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * @param v search value * @param idxList list of start indices in sorted order * @return index * * Note: Stops searching leaves that cannot be parents of the search value. * Base case reverts upon reaching bottom of tree. */ function searchDown( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector, uint32 v, uint256[] memory idxList ) internal view returns (uint256) { uint256 length = slot.len(); while (idxList.length > 0) { uint256 recIdxLength; uint256[] memory recIdxList = new uint256[](idxList.length); for (uint256 li = 0; li < idxList.length; li++) { uint256 idx = idxList[li]; if (idx < length) { if (v == slot.get(idx)) { return idx; } if (!compare(v, slot.get(idx), compareSelector)) { // v > heap[i] (min-heap), recurse leaves recIdxList[recIdxLength++] = idx; } } } //Overwrite array length assembly { mstore(recIdxList, recIdxLength) } //Recurse leaves of leaves idxList = TreeLib.leavesIdxList(a, b, recIdxList); } revert('HeapLibUInt32.searchDown: v not found.'); //No more leaves to search. These get removed recursively as they are either out of bounds or cannot be parents to the search value. } /** * @dev Search heap from root. * @param slot storage * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * @param v search value * @return index * * Note: This is very inefficient O(n). Recommended use is to call off-chain and * use result as hint, optimizing the efficiency of the search when it is actually * used during contract execution. */ function searchRoot( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector, uint32 v ) internal view returns (uint256) { return search(slot, a, b, compareSelector, v, 0); } /** * @dev Swap up to heapify from i * @param slot storage * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * @param i index * Used for after push() to update from leaf to root */ function heapifyUp( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector, uint256 i ) internal { // a < b while (i > 0 && compare(slot.get(i), slot.get(TreeLib.parentIdx(a, b, i)), compareSelector)) { // compare(i, parent), we swap them uint256 pIdx = TreeLib.parentIdx(a, b, i); slot.swap(i, pIdx); i = pIdx; //Set current index to parent } } /** * @dev Swap down to heapify from i * @param slot storage * @param a items per slot * @param b leaves * @param compareSelector comparison function 4byte selector * Used for after remove() to update from root to leaf */ function heapifyDown( bytes32 slot, uint256 a, uint256 b, bytes4 compareSelector, uint256 i ) internal returns (uint32 iVal) { //Find children minimum and swap uint256 length = slot.len(); iVal = slot.get(i); while (true) { uint256 minIdx; uint32 minVal; if (i % a == 0) { minIdx = i + 1; if (minIdx >= length) { break; //Null pointer, done heapifyDown } //Adjacent leaves, use batch reads uint256[] memory idxList = new uint256[](8); idxList[0] = i; idxList[1] = i + 1; idxList[2] = i + 2; idxList[3] = i + 3; idxList[4] = i + 4; idxList[5] = i + 5; idxList[6] = i + 6; idxList[7] = i + 7; uint256[] memory valList = slot.getBatch(idxList); minVal = uint32(valList[1]); // Find min leaf for (uint256 j = 2; j < valList.length; j++) { uint256 cmpIdx = i + j; if (cmpIdx >= length) { break; //Null pointer, done find minLeaf } uint32 cmpVal = uint32(valList[j]); //cached value bool c = compare(minVal, cmpVal, compareSelector); // a <= b minIdx = c ? minIdx : cmpIdx; minVal = c ? minVal : cmpVal; } } else { uint256[] memory lIdx = TreeLib.leavesIdx(a, b, i); // leaf indices in sorted order minIdx = lIdx[0]; if (minIdx >= length) { break; //Null pointer, done heapifyDown } minVal = slot.get(minIdx); // Find min leaf for (uint256 j = 1; j < lIdx.length; j++) { uint256 cmpIdx = lIdx[j]; if (cmpIdx >= length) { break; //Null pointer, done find minLeaf } uint32 cmpVal = slot.get(cmpIdx); bool c = compare(minVal, cmpVal, compareSelector); // a <= b minIdx = c ? minIdx : cmpIdx; minVal = c ? minVal : cmpVal; } } // Swap with min leaf if (compare(minVal, iVal, compareSelector)) { //minVal <= iVal slot.swap(i, minIdx); i = minIdx; } else { break; // iVal < minVal, min heap invariant preserved } } } }
* @dev Get heap root @param slot storage slot @return value/
function root(bytes32 slot) internal view returns (uint32 value) { value = slot.get(0); }
7,272,007
[ 1, 967, 10500, 1365, 225, 4694, 2502, 4694, 327, 460, 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, 1365, 12, 3890, 1578, 4694, 13, 2713, 1476, 1135, 261, 11890, 1578, 460, 13, 288, 203, 3639, 460, 273, 4694, 18, 588, 12, 20, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x89b581b51CB252D5cFcb933B748d9237bCf894AD/sources/contracts/interfaces/ICrosschain.sol
* @notice Defines functions and events for receiving and tracking crosschain claims/
interface ICrosschain is IDistributor, IXReceiver { event CrosschainClaim( bytes32 indexed id, address indexed beneficiary, address indexed recipient, uint32 recipientDomain, uint256 amount ); pragma solidity 0.8.16; import { IDistributor } from './IDistributor.sol'; import { IXReceiver } from './IXReceiver.sol'; }
11,613,584
[ 1, 15109, 4186, 471, 2641, 364, 15847, 471, 11093, 6828, 5639, 11955, 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, 5831, 467, 13941, 5639, 353, 1599, 291, 19293, 16, 467, 60, 12952, 288, 203, 225, 871, 19742, 5639, 9762, 12, 203, 565, 1731, 1578, 8808, 612, 16, 203, 565, 1758, 8808, 27641, 74, 14463, 814, 16, 203, 565, 1758, 8808, 8027, 16, 203, 565, 2254, 1578, 8027, 3748, 16, 203, 565, 2254, 5034, 3844, 203, 225, 11272, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 2313, 31, 203, 5666, 288, 1599, 291, 19293, 289, 628, 12871, 734, 291, 19293, 18, 18281, 13506, 203, 5666, 288, 467, 60, 12952, 289, 628, 12871, 12507, 12952, 18, 18281, 13506, 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 ]
./full_match/80001/0x463cB80b48c526ACb869c2C94bd691316c54e6a8/sources/contracts/GetVotedToEarn.sol
default: one unique value in the array
uint256 uniqueCounter = 1;
874,164
[ 1, 1886, 30, 1245, 3089, 460, 316, 326, 526, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 10792, 2254, 5034, 3089, 4789, 273, 404, 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 ]
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.9; import "@uma/core/contracts/financial-templates/common/financial-product-libraries/long-short-pair-libraries/LongShortPairFinancialProductLibrary.sol"; import "@uma/core/contracts/common/implementation/Lockable.sol"; /** * @title Linear Long Short Pair Financial Product Library. * @notice Adds settlement logic to create linear LSPs that have a capped percentage payable to the long (& short) token to * make market making both the long and short tokens easier in a v2 style AMM. */ contract ReserveLSPL is LongShortPairFinancialProductLibrary, Lockable { struct ReserveLinearLongShortPairParameters { uint256 upperBound; uint256 pctLongCap; } mapping(address => ReserveLinearLongShortPairParameters) public longShortPairParameters; /// `longShortPair` is not a valid LSP address. /// @param longShortPair The address of the LSP contract. error InvalidLSPAddress(address longShortPair); /// `upperBound` has to be greater than zero. /// @param upperBound The upper price that the LSP will operate within. error InvalidBound(uint256 upperBound); /// `pctLongCap` has to be less than 1 ether. /// @param pctLongCap The cap on the percentage that can be allocated to the long token - enforced for improving MM on v2 AMMs for both L&S tokens. error InvalidCap(uint256 pctLongCap); /// @notice Parameters already set for calling LSP. error ParametersSet(); /// @notice Parameters not set for calling LSP. error ParametersNotSet(); /** * @notice Enables any address to set the parameters for an associated financial product. * @param longShortPair The address of the LSP contract. * @param upperBound The upper price that the LSP will operate within. * @param pctLongCap The cap on the percentage that can be allocated to the long token - enforced for improving MM on v2 AMMs for both L&S tokens. * @dev Note: * a) Any address can set these parameters * b) existing LSP parameters for address not set. * c) upperBound > 0. * d) parameters can only be set once to prevent the deployer from changing the parameters after the fact. * e) For safety, parameters should be set before depositing any synthetic tokens in a liquidity pool. * f) longShortPair must expose an expirationTimestamp method to validate it is correctly deployed. */ function setLongShortPairParameters( address longShortPair, uint256 upperBound, uint256 pctLongCap ) public nonReentrant { if (ExpiringContractInterface(longShortPair).expirationTimestamp() == 0) revert InvalidLSPAddress(longShortPair); // upperBound at 0 would cause a division by 0 if (upperBound <= 0) revert InvalidBound(upperBound); if (pctLongCap >= 1 ether) revert InvalidCap(pctLongCap); ReserveLinearLongShortPairParameters memory params = longShortPairParameters[longShortPair]; if (params.upperBound != 0) revert ParametersSet(); longShortPairParameters[longShortPair] = ReserveLinearLongShortPairParameters({ upperBound: upperBound, pctLongCap: pctLongCap }); } /** * @notice Returns a number between 0 and 1e18 to indicate how much collateral each long and short token is entitled * to per collateralPerPair. * @param expiryPrice The price from the optimistic oracle for the LSP price identifier. * @return expiryPercentLong to indicate how much collateral should be sent between long and short tokens. */ function percentageLongCollateralAtExpiry(int256 expiryPrice) public view override nonReentrantView returns (uint256) { ReserveLinearLongShortPairParameters memory params = longShortPairParameters[msg.sender]; if (params.upperBound == 0) revert ParametersNotSet(); uint256 positivePrice = expiryPrice < 0 ? 0 : uint256(expiryPrice); uint256 effectiveUpperBound = (params.upperBound * params.pctLongCap) / 1 ether; uint256 effectiveLowerBound = (params.upperBound * (1 ether - params.pctLongCap)) / 1 ether; if (positivePrice <= effectiveLowerBound) return (1 ether - params.pctLongCap); if (positivePrice >= effectiveUpperBound) return params.pctLongCap; return (positivePrice * 1 ether) / params.upperBound; } }
@notice Parameters already set for calling LSP.
error ParametersSet();
6,357,301
[ 1, 2402, 1818, 444, 364, 4440, 511, 3118, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 555, 7012, 694, 5621, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x894F99E775E350a6A5Ac0714D98C18F1826D9F83/sources/contracts/v2/s54basicERC1155.sol
uint256 needed = amount - inExistance;mint(from, amount - inExistance, tokenId);_tokenData[tokenId][from].forSale += amount - inExistance;
function buy( address from, address to, uint256 tokenId, uint256 amount, int256 maxSupply, uint256 royalties, string memory ipfs, bool outsideSell, uint256 nounce, bytes memory data if(tokenId > 0){ if(verifyTransac(nft[0].creator, from, to, tokenId, amount, nounce, msg.value, data) == false){ o_s_m_check(tokenId); } uint256 inExistance = _tokenData[tokenId][from].amount; if(inExistance > 0){ if(amount - inExistance > 0){ if(from == nft[tokenId].creator){ doMint(from, amount - inExistance, tokenId); } } require(from == nft[tokenId].creator, str0); } return tokenId; require(amount <= uint256(maxSupply), "Max Supply exceeded"); require(verifyTransac(nft[0].creator, from, to, tokenId, amount, nounce, msg.value, data) || nft[0].creator == msg.sender, "Not approved"); _safeTransferFrom(from, to, newId, amount, "");
17,105,140
[ 1, 11890, 5034, 3577, 273, 3844, 300, 316, 4786, 1359, 31, 81, 474, 12, 2080, 16, 3844, 300, 316, 4786, 1359, 16, 1147, 548, 1769, 67, 2316, 751, 63, 2316, 548, 6362, 2080, 8009, 1884, 30746, 1011, 3844, 300, 316, 4786, 1359, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 30143, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 509, 5034, 225, 943, 3088, 1283, 16, 203, 3639, 2254, 5034, 721, 93, 2390, 606, 16, 203, 3639, 533, 3778, 2359, 2556, 16, 203, 3639, 1426, 8220, 55, 1165, 16, 203, 3639, 2254, 5034, 290, 8386, 16, 7010, 3639, 1731, 3778, 501, 203, 3639, 309, 12, 2316, 548, 405, 374, 15329, 203, 5411, 309, 12, 8705, 1429, 1077, 12, 82, 1222, 63, 20, 8009, 20394, 16, 628, 16, 358, 16, 1147, 548, 16, 3844, 16, 290, 8386, 16, 1234, 18, 1132, 16, 501, 13, 422, 629, 15329, 203, 7734, 320, 67, 87, 67, 81, 67, 1893, 12, 2316, 548, 1769, 203, 5411, 289, 203, 5411, 2254, 5034, 316, 4786, 1359, 273, 389, 2316, 751, 63, 2316, 548, 6362, 2080, 8009, 8949, 31, 203, 5411, 309, 12, 267, 4786, 1359, 405, 374, 15329, 203, 7734, 309, 12, 8949, 300, 316, 4786, 1359, 405, 374, 15329, 203, 10792, 309, 12, 2080, 422, 290, 1222, 63, 2316, 548, 8009, 20394, 15329, 203, 13491, 741, 49, 474, 12, 2080, 16, 3844, 300, 316, 4786, 1359, 16, 1147, 548, 1769, 203, 10792, 289, 203, 7734, 289, 203, 7734, 2583, 12, 2080, 422, 290, 1222, 63, 2316, 548, 8009, 20394, 16, 609, 20, 1769, 203, 5411, 289, 203, 5411, 327, 1147, 548, 31, 203, 7734, 2583, 12, 8949, 1648, 2254, 5034, 12, 1896, 3088, 1283, 3631, 315, 2747, 3425, 1283, 12428, 2 ]
./full_match/1/0x82a7b5842085f434c6584A8c44b6A1C15c25a512/sources/contracts/filters/SetCollectionCollateralFilter.sol
*************************************************************************/ State */*************************************************************************/* @notice Supported token/* @notice Set of supported token IDs/*************************************************************************/ Initializer */*************************************************************************/* @notice SetCollectionCollateralFilter initializer/ Validate root and node count */ Set supported token */ Add each token ID to set of token IDs */
function _initialize(address token, uint256[] memory tokenIds_) internal { if (tokenIds_.length == 0) revert InvalidCollateralFilterParameters(); _token = token; for (uint256 i; i < tokenIds_.length; i++) { _tokenIds.add(tokenIds_[i]); } }
9,659,643
[ 1, 19, 3287, 368, 225, 19503, 1147, 19, 225, 1000, 434, 3260, 1147, 7115, 759, 4378, 3926, 368, 225, 1000, 2532, 13535, 2045, 287, 1586, 12562, 19, 3554, 1365, 471, 756, 1056, 342, 1000, 3260, 1147, 342, 1436, 1517, 1147, 1599, 358, 444, 434, 1147, 7115, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 11160, 12, 2867, 1147, 16, 2254, 5034, 8526, 3778, 1147, 2673, 67, 13, 2713, 288, 203, 3639, 309, 261, 2316, 2673, 27799, 2469, 422, 374, 13, 15226, 1962, 13535, 2045, 287, 1586, 2402, 5621, 203, 203, 3639, 389, 2316, 273, 1147, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 1147, 2673, 27799, 2469, 31, 277, 27245, 288, 203, 5411, 389, 2316, 2673, 18, 1289, 12, 2316, 2673, 67, 63, 77, 19226, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; interface IUniswapV2Factory { event PAIRCREATED765(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO173() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER947() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR540(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS330(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH28() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR870(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO87(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER308(address) external; //inject NONSTANDARD NAMING } interface IUniswapV2Pair { event APPROVAL174(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER306(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME472() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL588() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS125() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY849() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF412(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE690(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE763(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER680(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM721(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR798() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH5() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES780(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT824(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT900(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN945(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP468( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC111(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY386() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY86() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0481() external view returns (address); //inject NONSTANDARD NAMING function TOKEN1550() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES473() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST512() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST431() external view returns (uint); //inject NONSTANDARD NAMING function KLAST25() external view returns (uint); //inject NONSTANDARD NAMING function MINT371(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN742(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP14(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM245(address to) external; //inject NONSTANDARD NAMING function SYNC404() external; //inject NONSTANDARD NAMING function INITIALIZE744(address, address) external; //inject NONSTANDARD NAMING } // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant resolution65 = 112; //inject NONSTANDARD NAMING // encode a uint112 as a UQ112x112 function ENCODE953(uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING return uq112x112(uint224(x) << resolution65); } // encodes a uint144 as a UQ144x112 function ENCODE144474(uint144 x) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING return uq144x112(uint256(x) << resolution65); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function DIV758(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function MUL709(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function FRACTION20(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << resolution65) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function DECODE642(uq112x112 memory self) internal pure returns (uint112) { //inject NONSTANDARD NAMING return uint112(self._x >> resolution65); } // decode a UQ144x112 into a uint144 by truncating after the radix point function DECODE144805(uq144x112 memory self) internal pure returns (uint144) { //inject NONSTANDARD NAMING return uint144(self._x >> resolution65); } } // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function CURRENTBLOCKTIMESTAMP616() internal view returns (uint32) { //inject NONSTANDARD NAMING return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function CURRENTCUMULATIVEPRICES565( //inject NONSTANDARD NAMING address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = CURRENTBLOCKTIMESTAMP616(); price0Cumulative = IUniswapV2Pair(pair).PRICE0CUMULATIVELAST512(); price1Cumulative = IUniswapV2Pair(pair).PRICE1CUMULATIVELAST431(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).GETRESERVES473(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.FRACTION20(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.FRACTION20(reserve0, reserve1)._x) * timeElapsed; } } } // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function ADD508(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function ADD508(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, errorMessage); return c; } function SUB277(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB277(a, b, "SafeMath: subtraction underflow"); } function SUB277(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL709(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function MUL709(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function DIV758(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV758(a, b, "SafeMath: division by zero"); } function DIV758(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function MOD92(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD92(a, b, "SafeMath: modulo by zero"); } function MOD92(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function SORTTOKENS379(address tokenA, address tokenB) internal pure returns (address token0, address token1) { //inject NONSTANDARD NAMING require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function PAIRFOR87(address factory, address tokenA, address tokenB) internal pure returns (address pair) { //inject NONSTANDARD NAMING (address token0, address token1) = SORTTOKENS379(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function GETRESERVES473(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { //inject NONSTANDARD NAMING (address token0,) = SORTTOKENS379(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(PAIRFOR87(factory, tokenA, tokenB)).GETRESERVES473(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function QUOTE2(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { //inject NONSTANDARD NAMING require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.MUL709(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function GETAMOUNTOUT789(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { //inject NONSTANDARD NAMING require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.MUL709(997); uint numerator = amountInWithFee.MUL709(reserveOut); uint denominator = reserveIn.MUL709(1000).ADD508(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function GETAMOUNTIN163(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { //inject NONSTANDARD NAMING require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.MUL709(amountOut).MUL709(1000); uint denominator = reserveOut.SUB277(amountOut).MUL709(997); amountIn = (numerator / denominator).ADD508(1); } // performs chained getAmountOut calculations on any number of pairs function GETAMOUNTSOUT330(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = GETRESERVES473(factory, path[i], path[i + 1]); amounts[i + 1] = GETAMOUNTOUT789(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function GETAMOUNTSIN267(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = GETRESERVES473(factory, path[i - 1], path[i]); amounts[i - 1] = GETAMOUNTIN163(amounts[i], reserveIn, reserveOut); } } } interface WETH9 { function WITHDRAW840(uint wad) external; //inject NONSTANDARD NAMING } interface IUniswapV2Router { function SWAPEXACTTOKENSFORTOKENS109( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } interface IKeep3rV1 { function ISMINKEEPER913(address keeper, uint minBond, uint earned, uint age) external returns (bool); //inject NONSTANDARD NAMING function RECEIPT100(address credit, address keeper, uint amount) external; //inject NONSTANDARD NAMING function UNBOND169(address bonding, uint amount) external; //inject NONSTANDARD NAMING function WITHDRAW840(address bonding) external; //inject NONSTANDARD NAMING function BONDS570(address keeper, address credit) external view returns (uint); //inject NONSTANDARD NAMING function UNBONDINGS996(address keeper, address credit) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE763(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING function JOBS817(address job) external view returns (bool); //inject NONSTANDARD NAMING function BALANCEOF412(address account) external view returns (uint256); //inject NONSTANDARD NAMING function WORKED219(address keeper) external; //inject NONSTANDARD NAMING function KPRH771() external view returns (IKeep3rV1Helper); //inject NONSTANDARD NAMING } interface IKeep3rV1Helper { function GETQUOTELIMIT880(uint gasUsed) external view returns (uint); //inject NONSTANDARD NAMING } // sliding oracle that uses observations collected to provide moving price averages in the past contract YearnV2Oracle { using FixedPoint for *; using SafeMath for uint; struct Observation { uint timestamp; uint price0Cumulative; uint price1Cumulative; } uint public minKeep = 200e18; modifier KEEPER983() { //inject NONSTANDARD NAMING require(kp3r674.ISMINKEEPER913(msg.sender, minKeep, 0, 0), "::isKeeper: keeper is not registered"); _; } modifier UPKEEP664() { //inject NONSTANDARD NAMING uint _gasUsed = gasleft(); require(kp3r674.ISMINKEEPER913(msg.sender, minKeep, 0, 0), "::isKeeper: keeper is not registered"); _; uint _received = kp3r674.KPRH771().GETQUOTELIMIT880(_gasUsed.SUB277(gasleft())); kp3r674.RECEIPT100(address(kp3r674), address(this), _received); _received = _SWAP523(_received); msg.sender.transfer(_received); } address public governance; address public pendingGovernance; function SETMINKEEP842(uint _keep) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "setGovernance: !gov"); minKeep = _keep; } function SETGOVERNANCE949(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "setGovernance: !gov"); pendingGovernance = _governance; } function ACCEPTGOVERNANCE56() external { //inject NONSTANDARD NAMING require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov"); governance = pendingGovernance; } IKeep3rV1 public constant kp3r674 = IKeep3rV1(0x1cEB5cB57C4D4E2b2433641b95Dd330A33185A44); //inject NONSTANDARD NAMING WETH9 public constant weth411 = WETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING IUniswapV2Router public constant uni703 = IUniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //inject NONSTANDARD NAMING address public constant factory868 = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; //inject NONSTANDARD NAMING // this is redundant with granularity and windowSize, but stored for gas savings & informational purposes. uint public constant periodsize934 = 1800; //inject NONSTANDARD NAMING address[] internal _pairs; mapping(address => bool) internal _known; function PAIRS458() external view returns (address[] memory) { //inject NONSTANDARD NAMING return _pairs; } mapping(address => Observation[]) public observations; function OBSERVATIONLENGTH959(address pair) external view returns (uint) { //inject NONSTANDARD NAMING return observations[pair].length; } function PAIRFOR87(address tokenA, address tokenB) external pure returns (address) { //inject NONSTANDARD NAMING return UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB); } function PAIRFORWETH375(address tokenA) external pure returns (address) { //inject NONSTANDARD NAMING return UniswapV2Library.PAIRFOR87(factory868, tokenA, address(weth411)); } constructor() public { governance = msg.sender; } function UPDATEPAIR621(address pair) external KEEPER983 returns (bool) { //inject NONSTANDARD NAMING return _UPDATE639(pair); } function UPDATE182(address tokenA, address tokenB) external KEEPER983 returns (bool) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB); return _UPDATE639(pair); } function ADD508(address tokenA, address tokenB) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "UniswapV2Oracle::add: !gov"); address pair = UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB); require(!_known[pair], "known"); _known[pair] = true; _pairs.push(pair); (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair); observations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative)); } function WORK476() public UPKEEP664 { //inject NONSTANDARD NAMING bool worked = _UPDATEALL128(); require(worked, "UniswapV2Oracle: !work"); } function WORKFORFREE492() public KEEPER983 { //inject NONSTANDARD NAMING bool worked = _UPDATEALL128(); require(worked, "UniswapV2Oracle: !work"); } function LASTOBSERVATION770(address pair) public view returns (Observation memory) { //inject NONSTANDARD NAMING return observations[pair][observations[pair].length-1]; } function _UPDATEALL128() internal returns (bool updated) { //inject NONSTANDARD NAMING for (uint i = 0; i < _pairs.length; i++) { if (_UPDATE639(_pairs[i])) { updated = true; } } } function UPDATEFOR106(uint i, uint length) external KEEPER983 returns (bool updated) { //inject NONSTANDARD NAMING for (; i < length; i++) { if (_UPDATE639(_pairs[i])) { updated = true; } } } function WORKABLE40(address pair) public view returns (bool) { //inject NONSTANDARD NAMING return (block.timestamp - LASTOBSERVATION770(pair).timestamp) > periodsize934; } function WORKABLE40() external view returns (bool) { //inject NONSTANDARD NAMING for (uint i = 0; i < _pairs.length; i++) { if (WORKABLE40(_pairs[i])) { return true; } } return false; } function _UPDATE639(address pair) internal returns (bool) { //inject NONSTANDARD NAMING // we only want to commit updates once per period (i.e. windowSize / granularity) Observation memory _point = LASTOBSERVATION770(pair); uint timeElapsed = block.timestamp - _point.timestamp; if (timeElapsed > periodsize934) { (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair); observations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative)); return true; } return false; } function COMPUTEAMOUNTOUT732( //inject NONSTANDARD NAMING uint priceCumulativeStart, uint priceCumulativeEnd, uint timeElapsed, uint amountIn ) private pure returns (uint amountOut) { // overflow is desired. FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed) ); amountOut = priceAverage.MUL709(amountIn).DECODE144805(); } function _VALID458(address pair, uint age) internal view returns (bool) { //inject NONSTANDARD NAMING return (block.timestamp - LASTOBSERVATION770(pair).timestamp) <= age; } function CURRENT334(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); require(_VALID458(pair, periodsize934.MUL709(2)), "UniswapV2Oracle::quote: stale prices"); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); Observation memory _observation = LASTOBSERVATION770(pair); (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair); if (block.timestamp == _observation.timestamp) { _observation = observations[pair][observations[pair].length-2]; } uint timeElapsed = block.timestamp - _observation.timestamp; timeElapsed = timeElapsed == 0 ? 1 : timeElapsed; if (token0 == tokenIn) { return COMPUTEAMOUNTOUT732(_observation.price0Cumulative, price0Cumulative, timeElapsed, amountIn); } else { return COMPUTEAMOUNTOUT732(_observation.price1Cumulative, price1Cumulative, timeElapsed, amountIn); } } function QUOTE2(address tokenIn, uint amountIn, address tokenOut, uint granularity) external view returns (uint amountOut) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); require(_VALID458(pair, periodsize934.MUL709(granularity)), "UniswapV2Oracle::quote: stale prices"); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint priceAverageCumulative = 0; uint length = observations[pair].length-1; uint i = length.SUB277(granularity); uint nextIndex = 0; if (token0 == tokenIn) { for (; i < length; i++) { nextIndex = i+1; priceAverageCumulative += COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); } } else { for (; i < length; i++) { nextIndex = i+1; priceAverageCumulative += COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); } } return priceAverageCumulative.DIV758(granularity); } function PRICES199(address tokenIn, uint amountIn, address tokenOut, uint points) external view returns (uint[] memory) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint length = observations[pair].length-1; uint i = length.SUB277(points); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i++) { nextIndex = i+1; _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } else { for (; i < length; i++) { nextIndex = i+1; _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } return _prices; } function HOURLY603(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint _len = observations[pair].length-1; uint length = _len.SUB277(2); uint i = _len.SUB277(points.MUL709(2)); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i.ADD508(2)) { nextIndex = i.ADD508(2); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } else { for (; i < length; i++) { nextIndex = i.ADD508(2); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } return _prices; } function DAILY468(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint _len = observations[pair].length-1; uint length = _len.SUB277(48); uint i = _len.SUB277(points.MUL709(48)); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i.ADD508(48)) { nextIndex = i.ADD508(48); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } else { for (; i < length; i++) { nextIndex = i.ADD508(48); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } return _prices; } function WEEKLY904(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint _len = observations[pair].length-1; uint length = _len.SUB277(336); uint i = _len.SUB277(points.MUL709(336)); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i.ADD508(336)) { nextIndex = i.ADD508(336); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } else { for (; i < length; i++) { nextIndex = i.ADD508(336); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } return _prices; } function IMPLIEDVOLATILITYHOURLY328(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING return STDDEV946(HOURLY603(tokenIn, amountIn, tokenOut, 1)); } function IMPLIEDVOLATILITYDAILY500(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING return STDDEV946(DAILY468(tokenIn, amountIn, tokenOut, 1)); } function IMPLIEDVOLATILITYWEEKLY55(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING return STDDEV946(WEEKLY904(tokenIn, amountIn, tokenOut, 1)); } function SQRT123(uint256 x) public pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = (x + 1) / 2; uint256 b = x; while (c < b) { b = c; c = (x / c + c) / 2; } return b; } function STDDEV946(uint[] memory numbers) public pure returns (uint256 sd) { //inject NONSTANDARD NAMING uint sum = 0; for(uint i = 0; i < numbers.length; i++) { sum += numbers[i]; } uint256 mean = sum / numbers.length; // Integral value; float not supported in Solidity sum = 0; uint i; for(i = 0; i < numbers.length; i++) { sum += (numbers[i] - mean) ** 2; } sd = SQRT123(sum / (numbers.length - 1)); //Integral value; float not supported in Solidity return sd; } function BLACKSCHOLESESTIMATE503( //inject NONSTANDARD NAMING uint256 _vol, uint256 _underlying, uint256 _time ) public pure returns (uint256 estimate) { estimate = 40 * _vol * _underlying * SQRT123(_time); return estimate; } function RETBASEDBLACKSCHOLESESTIMATE765( //inject NONSTANDARD NAMING uint256[] memory _numbers, uint256 _underlying, uint256 _time ) public pure { uint _vol = STDDEV946(_numbers); BLACKSCHOLESESTIMATE503(_vol, _underlying, _time); } receive() external payable {} function _SWAP523(uint _amount) internal returns (uint) { //inject NONSTANDARD NAMING kp3r674.APPROVE763(address(uni703), _amount); address[] memory path = new address[](2); path[0] = address(kp3r674); path[1] = address(weth411); uint[] memory amounts = uni703.SWAPEXACTTOKENSFORTOKENS109(_amount, uint256(0), path, address(this), now.ADD508(1800)); weth411.WITHDRAW840(amounts[1]); return amounts[1]; } }
inject NONSTANDARD NAMING
function GETQUOTELIMIT880(uint gasUsed) external view returns (uint);
12,917,704
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4978, 18980, 8283, 28, 3672, 12, 11890, 16189, 6668, 13, 3903, 1476, 1135, 261, 11890, 1769, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; // OpenZeppelin v4 import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { StorageSlot } from "@openzeppelin/contracts/utils/StorageSlot.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { SNARK_SCALAR_FIELD, TokenType, WithdrawType, TokenData, CommitmentCiphertext, CommitmentPreimage, Transaction } from "./Globals.sol"; import { Verifier } from "./Verifier.sol"; import { Commitments } from "./Commitments.sol"; import { TokenBlacklist } from "./TokenBlacklist.sol"; import { PoseidonT4 } from "./Poseidon.sol"; /** * @title Railgun Logic * @author Railgun Contributors * @notice Functions to interact with the railgun contract * @dev Wallets for Railgun will only need to interact with functions specified in this contract. * This contract is written to be run behind a ERC1967-like proxy. Upon deployment of proxy the _data parameter should * call the initializeRailgunLogic function. */ contract RailgunLogic is Initializable, OwnableUpgradeable, Commitments, TokenBlacklist, Verifier { using SafeERC20 for IERC20; // NOTE: The order of instantiation MUST stay the same across upgrades // add new variables to the bottom of the list // See https://docs.openzeppelin.com/learn/upgrading-smart-contracts#upgrading // Treasury variables address payable public treasury; // Treasury contract uint120 private constant BASIS_POINTS = 10000; // Number of basis points that equal 100% // % fee in 100ths of a %. 100 = 1%. uint120 public depositFee; uint120 public withdrawFee; // Flat fee in wei that applies to NFT transactions uint256 public nftFee; // Safety vectors mapping(uint256 => bool) public snarkSafetyVector; // Treasury events event TreasuryChange(address treasury); event FeeChange(uint256 depositFee, uint256 withdrawFee, uint256 nftFee); // Transaction events event CommitmentBatch( uint256 treeNumber, uint256 startPosition, uint256[] hash, CommitmentCiphertext[] ciphertext ); event GeneratedCommitmentBatch( uint256 treeNumber, uint256 startPosition, CommitmentPreimage[] commitments, uint256[2][] encryptedRandom ); event Nullifiers(uint256 treeNumber, uint256[] nullifier); /** * @notice Initialize Railgun contract * @dev OpenZeppelin initializer ensures this can only be called once * This function also calls initializers on inherited contracts * @param _treasury - address to send usage fees to * @param _depositFee - Deposit fee * @param _withdrawFee - Withdraw fee * @param _nftFee - Flat fee in wei that applies to NFT transactions * @param _owner - governance contract */ function initializeRailgunLogic( address payable _treasury, uint120 _depositFee, uint120 _withdrawFee, uint256 _nftFee, address _owner ) external initializer { // Call initializers OwnableUpgradeable.__Ownable_init(); Commitments.initializeCommitments(); // Set treasury and fee changeTreasury(_treasury); changeFee(_depositFee, _withdrawFee, _nftFee); // Change Owner OwnableUpgradeable.transferOwnership(_owner); // Set safety vectors snarkSafetyVector[11991246288605609459798790887503763024866871101] = true; snarkSafetyVector[135932600361240492381964832893378343190771392134] = true; snarkSafetyVector[1165567609304106638376634163822860648671860889162] = true; } /** * @notice Change treasury address, only callable by owner (governance contract) * @dev This will change the address of the contract we're sending the fees to in the future * it won't transfer tokens already in the treasury * @param _treasury - Address of new treasury contract */ function changeTreasury(address payable _treasury) public onlyOwner { // Do nothing if the new treasury address is same as the old if (treasury != _treasury) { // Change treasury treasury = _treasury; // Emit treasury change event emit TreasuryChange(_treasury); } } /** * @notice Change fee rate for future transactions * @param _depositFee - Deposit fee * @param _withdrawFee - Withdraw fee * @param _nftFee - Flat fee in wei that applies to NFT transactions */ function changeFee( uint120 _depositFee, uint120 _withdrawFee, uint256 _nftFee ) public onlyOwner { if ( _depositFee != depositFee || _withdrawFee != withdrawFee || nftFee != _nftFee ) { require(_depositFee <= BASIS_POINTS, "RailgunLogic: Deposit Fee exceeds 100%"); require(_withdrawFee <= BASIS_POINTS, "RailgunLogic: Withdraw Fee exceeds 100%"); // Change fee depositFee = _depositFee; withdrawFee = _withdrawFee; nftFee = _nftFee; // Emit fee change event emit FeeChange(_depositFee, _withdrawFee, _nftFee); } } /** * @notice Get base and fee amount * @param _amount - Amount to calculate for * @param _isInclusive - Whether the amount passed in is inclusive of the fee * @param _feeBP - Fee basis points * @return base, fee */ function getFee(uint136 _amount, bool _isInclusive, uint120 _feeBP) public pure returns (uint120, uint120) { // Expand width of amount to uint136 to accomodate full size of (2**120-1)*BASIS_POINTS uint136 amountExpanded = _amount; // Base is the amount deposited into the railgun contract or withdrawn to the target eth address // for deposits and withdraws respectively uint136 base; // Fee is the amount sent to the treasury uint136 fee; if (_isInclusive) { base = amountExpanded - (amountExpanded * _feeBP) / BASIS_POINTS; fee = amountExpanded - base; } else { base = amountExpanded; fee = (BASIS_POINTS * base) / (BASIS_POINTS - _feeBP) - base; } return (uint120(base), uint120(fee)); } /** * @notice Gets token field value from tokenData * @param _tokenData - tokenData to calculate token field from * @return token field */ function getTokenField(TokenData memory _tokenData) public pure returns (uint256) { if (_tokenData.tokenType == TokenType.ERC20) { return uint256(uint160(_tokenData.tokenAddress)); } else if (_tokenData.tokenType == TokenType.ERC721) { revert("RailgunLogic: ERC721 not yet supported"); } else if (_tokenData.tokenType == TokenType.ERC1155) { revert("RailgunLogic: ERC1155 not yet supported"); } else { revert("RailgunLogic: Unknown token type"); } } /** * @notice Hashes a commitment * @param _commitmentPreimage - commitment to hash * @return commitment hash */ function hashCommitment(CommitmentPreimage memory _commitmentPreimage) public pure returns (uint256) { return PoseidonT4.poseidon([ _commitmentPreimage.npk, getTokenField(_commitmentPreimage.token), _commitmentPreimage.value ]); } /** * @notice Deposits requested amount and token, creates a commitment hash from supplied values and adds to tree * @param _notes - list of commitments to deposit */ function generateDeposit(CommitmentPreimage[] calldata _notes, uint256[2][] calldata _encryptedRandom) external { // Get notes length uint256 notesLength = _notes.length; // Insertion and event arrays uint256[] memory insertionLeaves = new uint256[](notesLength); CommitmentPreimage[] memory generatedCommitments = new CommitmentPreimage[](notesLength); require(_notes.length == _encryptedRandom.length, "RailgunLogic: notes and encrypted random length doesn't match"); for (uint256 notesIter = 0; notesIter < notesLength; notesIter++) { // Retrieve note CommitmentPreimage calldata note = _notes[notesIter]; // Check deposit amount is not 0 require(note.value > 0, "RailgunLogic: Cannot deposit 0 tokens"); // Check if token is on the blacklist require( !TokenBlacklist.tokenBlacklist[note.token.tokenAddress], "RailgunLogic: Token is blacklisted" ); // Check ypubkey is in snark scalar field require(note.npk < SNARK_SCALAR_FIELD, "RailgunLogic: npk out of range"); // Process deposit request if (note.token.tokenType == TokenType.ERC20) { // ERC20 // Get ERC20 interface IERC20 token = IERC20(address(uint160(note.token.tokenAddress))); // Get base and fee amounts (uint120 base, uint120 fee) = getFee(note.value, true, depositFee); // Add GeneratedCommitment to event array generatedCommitments[notesIter] = CommitmentPreimage({ npk: note.npk, value: base, token: note.token }); // Calculate commitment hash uint256 hash = hashCommitment(generatedCommitments[notesIter]); // Add to insertion array insertionLeaves[notesIter] = hash; // Transfer base to output address token.safeTransferFrom( address(msg.sender), address(this), base ); // Transfer fee to treasury token.safeTransferFrom( address(msg.sender), treasury, fee ); } else if (note.token.tokenType == TokenType.ERC721) { // ERC721 token revert("RailgunLogic: ERC721 not yet supported"); } else if (note.token.tokenType == TokenType.ERC1155) { // ERC1155 token revert("RailgunLogic: ERC1155 not yet supported"); } else { // Invalid token type, revert revert("RailgunLogic: Unknown token type"); } } // Emit GeneratedCommitmentAdded events (for wallets) for the commitments emit GeneratedCommitmentBatch(Commitments.treeNumber, Commitments.nextLeafIndex, generatedCommitments, _encryptedRandom); // Push new commitments to merkle tree Commitments.insertLeaves(insertionLeaves); } /** * @notice Safety check for badly behaving code */ function checkSafetyVectors() external { // Set safety bit StorageSlot.getBooleanSlot(0x8dea8703c3cf94703383ce38a9c894669dccd4ca8e65ddb43267aa0248711450).value = true; // Setup behaviour check bool result = false; // Execute behaviour check // solhint-disable-next-line no-inline-assembly assembly { mstore(0, caller()) mstore(32, snarkSafetyVector.slot) let hash := keccak256(0, 64) result := sload(hash) } require(result, "RailgunLogic: Unsafe vectors"); } /** * @notice Adds safety vector */ function addVector(uint256 vector) external onlyOwner { snarkSafetyVector[vector] = true; } /** * @notice Removes safety vector */ function removeVector(uint256 vector) external onlyOwner { snarkSafetyVector[vector] = false; } /** * @notice Execute batch of Railgun snark transactions * @param _transactions - Transactions to execute */ function transact( Transaction[] calldata _transactions ) external { // Accumulate total number of insertion commitments uint256 insertionCommitmentCount = 0; // Loop through each transaction uint256 transactionLength = _transactions.length; for(uint256 transactionIter = 0; transactionIter < transactionLength; transactionIter++) { // Retrieve transaction Transaction calldata transaction = _transactions[transactionIter]; // If adaptContract is not zero check that it matches the caller require( transaction.boundParams.adaptContract == address (0) || transaction.boundParams.adaptContract == msg.sender, "AdaptID doesn't match caller contract" ); // Retrieve treeNumber uint256 treeNumber = transaction.boundParams.treeNumber; // Check merkle root is valid require(Commitments.rootHistory[treeNumber][transaction.merkleRoot], "RailgunLogic: Invalid Merkle Root"); // Loop through each nullifier uint256 nullifiersLength = transaction.nullifiers.length; for (uint256 nullifierIter = 0; nullifierIter < nullifiersLength; nullifierIter++) { // Retrieve nullifier uint256 nullifier = transaction.nullifiers[nullifierIter]; // Check if nullifier has been seen before require(!Commitments.nullifiers[treeNumber][nullifier], "RailgunLogic: Nullifier already seen"); // Push to nullifiers Commitments.nullifiers[treeNumber][nullifier] = true; } // Emit nullifiers event emit Nullifiers(treeNumber, transaction.nullifiers); // Verify proof require( Verifier.verify(transaction), "RailgunLogic: Invalid SNARK proof" ); if (transaction.boundParams.withdraw != WithdrawType.NONE) { // Last output is marked as withdraw, process // Hash the withdraw commitment preimage uint256 commitmentHash = hashCommitment(transaction.withdrawPreimage); // Make sure the commitment hash matches the withdraw transaction output require( commitmentHash == transaction.commitments[transaction.commitments.length - 1], "RailgunLogic: Withdraw commitment preimage is invalid" ); // Fetch output address address output = address(uint160(transaction.withdrawPreimage.npk)); // Check if we've been asked to override the withdraw destination if(transaction.overrideOutput != address(0)) { // Withdraw must == 2 and msg.sender must be the original recepient to change the output destination require( msg.sender == output && transaction.boundParams.withdraw == WithdrawType.REDIRECT, "RailgunLogic: Can't override destination address" ); // Override output address output = transaction.overrideOutput; } // Process withdrawal request if (transaction.withdrawPreimage.token.tokenType == TokenType.ERC20) { // ERC20 // Get ERC20 interface IERC20 token = IERC20(address(uint160(transaction.withdrawPreimage.token.tokenAddress))); // Get base and fee amounts (uint120 base, uint120 fee) = getFee(transaction.withdrawPreimage.value, true, withdrawFee); // Transfer base to output address token.safeTransfer( output, base ); // Transfer fee to treasury token.safeTransfer( treasury, fee ); } else if (transaction.withdrawPreimage.token.tokenType == TokenType.ERC721) { // ERC721 token revert("RailgunLogic: ERC721 not yet supported"); } else if (transaction.withdrawPreimage.token.tokenType == TokenType.ERC1155) { // ERC1155 token revert("RailgunLogic: ERC1155 not yet supported"); } else { // Invalid token type, revert revert("RailgunLogic: Unknown token type"); } // Ensure ciphertext length matches the commitments length (minus 1 for withdrawn output) require( transaction.boundParams.commitmentCiphertext.length == transaction.commitments.length - 1, "RailgunLogic: Ciphertexts and commitments count mismatch" ); // Increment insertion commitment count (minus 1 for withdrawn output) insertionCommitmentCount += transaction.commitments.length - 1; } else { // Ensure ciphertext length matches the commitments length require( transaction.boundParams.commitmentCiphertext.length == transaction.commitments.length, "RailgunLogic: Ciphertexts and commitments count mismatch" ); // Increment insertion commitment count insertionCommitmentCount += transaction.commitments.length; } } // Create insertion array uint256[] memory hashes = new uint256[](insertionCommitmentCount); // Create ciphertext array CommitmentCiphertext[] memory ciphertext = new CommitmentCiphertext[](insertionCommitmentCount); // Track insert position uint256 insertPosition = 0; // Loop through each transaction and accumulate commitments for(uint256 transactionIter = 0; transactionIter < _transactions.length; transactionIter++) { // Retrieve transaction Transaction calldata transaction = _transactions[transactionIter]; // Loop through commitments and push to array uint256 commitmentLength = transaction.boundParams.commitmentCiphertext.length; for(uint256 commitmentIter = 0; commitmentIter < commitmentLength; commitmentIter++) { // Push commitment hash to array hashes[insertPosition] = transaction.commitments[commitmentIter]; // Push ciphertext to array ciphertext[insertPosition] = transaction.boundParams.commitmentCiphertext[commitmentIter]; // Increment insert position insertPosition++; } } // Emit commitment state update emit CommitmentBatch(Commitments.treeNumber, Commitments.nextLeafIndex, hashes, ciphertext); // Push new commitments to merkle tree after event due to insertLeaves causing side effects Commitments.insertLeaves(hashes); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) 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 // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _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); } /** * This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; // Constants uint256 constant SNARK_SCALAR_FIELD = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint256 constant CIPHERTEXT_WORDS = 4; enum TokenType { ERC20, ERC721, ERC1155 } // Transaction token data struct TokenData { TokenType tokenType; address tokenAddress; uint256 tokenSubID; } // Commitment ciphertext struct CommitmentCiphertext { uint256[CIPHERTEXT_WORDS] ciphertext; // Ciphertext order: iv & tag (16 bytes each), recipient master public key (packedPoint) (uint256), packedField (uint256) {sign, random, amount}, token (uint256) uint256[2] ephemeralKeys; // Sender first, receipient second (packed points 32 bytes each) uint256[] memo; } enum WithdrawType { NONE, WITHDRAW, REDIRECT } // Transaction bound parameters struct BoundParams { uint16 treeNumber; WithdrawType withdraw; address adaptContract; bytes32 adaptParams; // For withdraws do not include an element in ciphertext array // Ciphertext array length = commitments - withdraws CommitmentCiphertext[] commitmentCiphertext; } // Transaction struct struct Transaction { SnarkProof proof; uint256 merkleRoot; uint256[] nullifiers; uint256[] commitments; BoundParams boundParams; CommitmentPreimage withdrawPreimage; address overrideOutput; // Only allowed if original destination == msg.sender & boundParams.withdraw == 2 } // Commitment hash preimage struct CommitmentPreimage { uint256 npk; // Poseidon(mpk, random), mpk = Poseidon(spending public key, nullifier) TokenData token; // Token field uint120 value; // Note value } struct G1Point { uint256 x; uint256 y; } // Encoding of field elements is: X[0] * z + X[1] struct G2Point { uint256[2] x; uint256[2] y; } // Verification key for SNARK struct VerifyingKey { string artifactsIPFSHash; G1Point alpha1; G2Point beta2; G2Point gamma2; G2Point delta2; G1Point[] ic; } // Snark proof for transaction struct SnarkProof { G1Point a; G2Point b; G1Point c; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; // OpenZeppelin v4 import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { SnarkProof, Transaction, BoundParams, VerifyingKey, SNARK_SCALAR_FIELD } from "./Globals.sol"; import { Snark } from "./Snark.sol"; /** * @title Verifier * @author Railgun Contributors * @notice Verifies snark proof * @dev Functions in this contract statelessly verify proofs, nullifiers and adaptID should be checked in RailgunLogic. */ contract Verifier is OwnableUpgradeable { // NOTE: The order of instantiation MUST stay the same across upgrades // add new variables to the bottom of the list and decrement __gap // See https://docs.openzeppelin.com/learn/upgrading-smart-contracts#upgrading // Snark bypass address, can't be address(0) as many burn prevention mechanisms will disallow transfers to 0 // Use 0x000000000000000000000000000000000000dEaD as an alternative address constant public SNARK_BYPASS = 0x000000000000000000000000000000000000dEaD; // Verifying key set event event VerifyingKeySet(uint256 nullifiers, uint256 commitments, VerifyingKey verifyingKey); // Nullifiers => Commitments => Verification Key mapping(uint256 => mapping(uint256 => VerifyingKey)) private verificationKeys; /** * @notice Sets verification key * @param _nullifiers - number of nullifiers this verification key is for * @param _commitments - number of commitmets out this verification key is for * @param _verifyingKey - verifyingKey to set */ function setVerificationKey( uint256 _nullifiers, uint256 _commitments, VerifyingKey calldata _verifyingKey ) public onlyOwner { verificationKeys[_nullifiers][_commitments] = _verifyingKey; emit VerifyingKeySet(_nullifiers, _commitments, _verifyingKey); } /** * @notice Gets verification key * @param _nullifiers - number of nullifiers this verification key is for * @param _commitments - number of commitmets out this verification key is for */ function getVerificationKey( uint256 _nullifiers, uint256 _commitments ) public view returns (VerifyingKey memory) { // Manually add getter so dynamic IC array is included in response return verificationKeys[_nullifiers][_commitments]; } /** * @notice Calculates hash of transaction bound params for snark verification * @param _boundParams - bound parameters * @return bound parameters hash */ function hashBoundParams(BoundParams calldata _boundParams) public pure returns (uint256) { return uint256(keccak256(abi.encode( _boundParams ))) % SNARK_SCALAR_FIELD; } /** * @notice Verifies inputs against a verification key * @param _verifyingKey - verifying key to verify with * @param _proof - proof to verify * @param _inputs - input to verify * @return proof validity */ function verifyProof( VerifyingKey memory _verifyingKey, SnarkProof calldata _proof, uint256[] memory _inputs ) public view returns (bool) { return Snark.verify( _verifyingKey, _proof, _inputs ); } /** * @notice Verifies a transaction * @param _transaction to verify * @return transaction validity */ function verify(Transaction calldata _transaction) public view returns (bool) { uint256 nullifiersLength = _transaction.nullifiers.length; uint256 commitmentsLength = _transaction.commitments.length; // Retrieve verification key VerifyingKey memory verifyingKey = verificationKeys [nullifiersLength] [commitmentsLength]; // Check if verifying key is set require(verifyingKey.alpha1.x != 0, "Verifier: Key not set"); // Calculate inputs uint256[] memory inputs = new uint256[](2 + nullifiersLength + commitmentsLength); inputs[0] = _transaction.merkleRoot; // Hash bound parameters inputs[1] = hashBoundParams(_transaction.boundParams); // Loop through nullifiers and add to inputs for (uint i = 0; i < nullifiersLength; i++) { inputs[2 + i] = _transaction.nullifiers[i]; } // Loop through commitments and add to inputs for (uint i = 0; i < commitmentsLength; i++) { inputs[2 + nullifiersLength + i] = _transaction.commitments[i]; } // Verify snark proof bool validity = verifyProof( verifyingKey, _transaction.proof, inputs ); // Always return true in gas estimation transaction // This is so relayer fees can be calculated without needing to compute a proof // solhint-disable-next-line avoid-tx-origin if (tx.origin == SNARK_BYPASS) { return true; } else { return validity; } } uint256[49] private __gap; } // SPDX-License-Identifier: UNLICENSED // Based on code from MACI (https://github.com/appliedzkp/maci/blob/7f36a915244a6e8f98bacfe255f8bd44193e7919/contracts/sol/IncrementalMerkleTree.sol) pragma solidity ^0.8.0; pragma abicoder v2; // OpenZeppelin v4 import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import { SNARK_SCALAR_FIELD } from "./Globals.sol"; import { PoseidonT3 } from "./Poseidon.sol"; /** * @title Commitments * @author Railgun Contributors * @notice Batch Incremental Merkle Tree for commitments * @dev Publically accessible functions to be put in RailgunLogic * Relevent external contract calls should be in those functions, not here */ contract Commitments is Initializable { // NOTE: The order of instantiation MUST stay the same across upgrades // add new variables to the bottom of the list and decrement the __gap // variable at the end of this file // See https://docs.openzeppelin.com/learn/upgrading-smart-contracts#upgrading // Commitment nullifiers (treenumber -> nullifier -> seen) mapping(uint256 => mapping(uint256 => bool)) public nullifiers; // The tree depth uint256 internal constant TREE_DEPTH = 16; // Tree zero value uint256 public constant ZERO_VALUE = uint256(keccak256("Railgun")) % SNARK_SCALAR_FIELD; // Next leaf index (number of inserted leaves in the current tree) uint256 internal nextLeafIndex; // The Merkle root uint256 public merkleRoot; // Store new tree root to quickly migrate to a new tree uint256 private newTreeRoot; // Tree number uint256 public treeNumber; // The Merkle path to the leftmost leaf upon initialisation. It *should // not* be modified after it has been set by the initialize function. // Caching these values is essential to efficient appends. uint256[TREE_DEPTH] public zeros; // Right-most elements at each level // Used for efficient upodates of the merkle tree uint256[TREE_DEPTH] private filledSubTrees; // Whether the contract has already seen a particular Merkle tree root // treeNumber -> root -> seen mapping(uint256 => mapping(uint256 => bool)) public rootHistory; /** * @notice Calculates initial values for Merkle Tree * @dev OpenZeppelin initializer ensures this can only be called once */ function initializeCommitments() internal onlyInitializing { /* To initialise the Merkle tree, we need to calculate the Merkle root assuming that each leaf is the zero value. H(H(a,b), H(c,d)) / \ H(a,b) H(c,d) / \ / \ a b c d `zeros` and `filledSubTrees` will come in handy later when we do inserts or updates. e.g when we insert a value in index 1, we will need to look up values from those arrays to recalculate the Merkle root. */ // Calculate zero values zeros[0] = ZERO_VALUE; // Store the current zero value for the level we just calculated it for uint256 currentZero = ZERO_VALUE; // Loop through each level for (uint256 i = 0; i < TREE_DEPTH; i++) { // Push it to zeros array zeros[i] = currentZero; // Calculate the zero value for this level currentZero = hashLeftRight(currentZero, currentZero); } // Set merkle root and store root to quickly retrieve later newTreeRoot = merkleRoot = currentZero; rootHistory[treeNumber][currentZero] = true; } /** * @notice Hash 2 uint256 values * @param _left - Left side of hash * @param _right - Right side of hash * @return hash result */ function hashLeftRight(uint256 _left, uint256 _right) public pure returns (uint256) { return PoseidonT3.poseidon([ _left, _right ]); } /** * @notice Calculates initial values for Merkle Tree * @dev Insert leaves into the current merkle tree * Note: this function INTENTIONALLY causes side effects to save on gas. * _leafHashes and _count should never be reused. * @param _leafHashes - array of leaf hashes to be added to the merkle tree */ function insertLeaves(uint256[] memory _leafHashes) internal { /* Loop through leafHashes at each level, if the leaf is on the left (index is even) then hash with zeros value and update subtree on this level, if the leaf is on the right (index is odd) then hash with subtree value. After calculating each hash push to relevent spot on leafHashes array. For gas efficiency we reuse the same array and use the count variable to loop to the right index each time. Example of updating a tree of depth 4 with elements 13, 14, and 15 [1,7,15] {1} 1 | [3,7,15] {1} 2-------------------3 | | [6,7,15] {2} 4---------5 6---------7 / \ / \ / \ / \ [13,14,15] {3} 08 09 10 11 12 13 14 15 [] = leafHashes array {} = count variable */ // Get initial count uint256 count = _leafHashes.length; // Create new tree if current one can't contain new leaves // We insert all new commitment into a new tree to ensure they can be spent in the same transaction if ((nextLeafIndex + count) >= (2 ** TREE_DEPTH)) { newTree(); } // Current index is the index at each level to insert the hash uint256 levelInsertionIndex = nextLeafIndex; // Update nextLeafIndex nextLeafIndex += count; // Variables for starting point at next tree level uint256 nextLevelHashIndex; uint256 nextLevelStartIndex; // Loop through each level of the merkle tree and update for (uint256 level = 0; level < TREE_DEPTH; level++) { // Calculate the index to start at for the next level // >> is equivilent to / 2 rounded down nextLevelStartIndex = levelInsertionIndex >> 1; uint256 insertionElement = 0; // If we're on the right, hash and increment to get on the left if (levelInsertionIndex % 2 == 1) { // Calculate index to insert hash into leafHashes[] // >> is equivilent to / 2 rounded down nextLevelHashIndex = (levelInsertionIndex >> 1) - nextLevelStartIndex; // Calculate the hash for the next level _leafHashes[nextLevelHashIndex] = hashLeftRight(filledSubTrees[level], _leafHashes[insertionElement]); // Increment insertionElement += 1; levelInsertionIndex += 1; } // We'll always be on the left side now for (insertionElement; insertionElement < count; insertionElement += 2) { uint256 right; // Calculate right value if (insertionElement < count - 1) { right = _leafHashes[insertionElement + 1]; } else { right = zeros[level]; } // If we've created a new subtree at this level, update if (insertionElement == count - 1 || insertionElement == count - 2) { filledSubTrees[level] = _leafHashes[insertionElement]; } // Calculate index to insert hash into leafHashes[] // >> is equivilent to / 2 rounded down nextLevelHashIndex = (levelInsertionIndex >> 1) - nextLevelStartIndex; // Calculate the hash for the next level _leafHashes[nextLevelHashIndex] = hashLeftRight(_leafHashes[insertionElement], right); // Increment level insertion index levelInsertionIndex += 2; } // Get starting levelInsertionIndex value for next level levelInsertionIndex = nextLevelStartIndex; // Get count of elements for next level count = nextLevelHashIndex + 1; } // Update the Merkle tree root merkleRoot = _leafHashes[0]; rootHistory[treeNumber][merkleRoot] = true; } /** * @notice Creates new merkle tree */ function newTree() private { // Restore merkleRoot to newTreeRoot merkleRoot = newTreeRoot; // Existing values in filledSubtrees will never be used so overwriting them is unnecessary // Reset next leaf index to 0 nextLeafIndex = 0; // Increment tree number treeNumber++; } uint256[10] private __gap; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; // OpenZeppelin v4 import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; /** * @title Token Blacklist * @author Railgun Contributors * @notice Blacklist of tokens that are incompatible with the protocol * @dev Tokens on this blacklist can't be deposited to railgun. * Tokens on this blacklist will still be transferrable * internally (as internal transactions have a shielded token ID) and * withdrawable (to prevent user funds from being locked) * THIS WILL ALWAYS BE A NON-EXHAUSTIVE LIST, DO NOT RELY ON IT BLOCKING ALL * INCOMPATIBLE TOKENS */ contract TokenBlacklist is OwnableUpgradeable { // Events for offchain building of blacklist index event AddToBlacklist(address indexed token); event RemoveFromBlacklist(address indexed token); // NOTE: The order of instantiation MUST stay the same across upgrades // add new variables to the bottom of the list and decrement the __gap // variable at the end of this file // See https://docs.openzeppelin.com/learn/upgrading-smart-contracts#upgrading mapping(address => bool) public tokenBlacklist; /** * @notice Adds tokens to blacklist, only callable by owner (governance contract) * @dev This function will ignore tokens that are already in the blacklist * no events will be emitted in this case * @param _tokens - List of tokens to add to blacklist */ function addToBlacklist(address[] calldata _tokens) external onlyOwner { // Loop through token array for (uint256 i = 0; i < _tokens.length; i++) { // Don't do anything if the token is already blacklisted if (!tokenBlacklist[_tokens[i]]) { // Set token address in blacklist map to true tokenBlacklist[_tokens[i]] = true; // Emit event for building index of blacklisted tokens offchain emit AddToBlacklist(_tokens[i]); } } } /** * @notice Removes token from blacklist, only callable by owner (governance contract) * @dev This function will ignore tokens that aren't in the blacklist * no events will be emitted in this case * @param _tokens - List of tokens to remove from blacklist */ function removeFromBlacklist(address[] calldata _tokens) external onlyOwner { // Loop through token array for (uint256 i = 0; i < _tokens.length; i++) { // Don't do anything if the token isn't blacklisted if (tokenBlacklist[_tokens[i]]) { // Set token address in blacklisted map to false (default value) delete tokenBlacklist[_tokens[i]]; // Emit event for building index of blacklisted tokens offchain emit RemoveFromBlacklist(_tokens[i]); } } } uint256[49] private __gap; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; /* Functions here are stubs for the solidity compiler to generate the right interface. The deployed library is generated bytecode from the circomlib toolchain */ library PoseidonT3 { // solhint-disable-next-line no-empty-blocks function poseidon(uint256[2] memory input) public pure returns (uint256) {} } library PoseidonT4 { // solhint-disable-next-line no-empty-blocks function poseidon(uint256[3] memory input) public pure returns (uint256) {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; import { G1Point, G2Point, VerifyingKey, SnarkProof, SNARK_SCALAR_FIELD } from "./Globals.sol"; library Snark { uint256 private constant PRIME_Q = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint256 private constant PAIRING_INPUT_SIZE = 24; uint256 private constant PAIRING_INPUT_WIDTH = 768; // PAIRING_INPUT_SIZE * 32 /** * @notice Computes the negation of point p * @dev The negation of p, i.e. p.plus(p.negate()) should be zero. * @return result */ function negate(G1Point memory p) internal pure returns (G1Point memory) { if (p.x == 0 && p.y == 0) return G1Point(0, 0); // check for valid points y^2 = x^3 +3 % PRIME_Q uint256 rh = mulmod(p.x, p.x, PRIME_Q); //x^2 rh = mulmod(rh, p.x, PRIME_Q); //x^3 rh = addmod(rh, 3, PRIME_Q); //x^3 + 3 uint256 lh = mulmod(p.y, p.y, PRIME_Q); //y^2 require(lh == rh, "Snark: Invalid negation"); return G1Point(p.x, PRIME_Q - (p.y % PRIME_Q)); } /** * @notice Adds 2 G1 points * @return result */ function add(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory) { // Format inputs uint256[4] memory input; input[0] = p1.x; input[1] = p1.y; input[2] = p2.x; input[3] = p2.y; // Setup output variables bool success; G1Point memory result; // Add points // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(sub(gas(), 2000), 6, input, 0x80, result, 0x40) } // Check if operation succeeded require(success, "Snark: Add Failed"); return result; } /** * @notice Scalar multiplies two G1 points p, s * @dev The product of a point on G1 and a scalar, i.e. * p == p.scalar_mul(1) and p.plus(p) == p.scalar_mul(2) for all * points p. * @return r - result */ function scalarMul(G1Point memory p, uint256 s) internal view returns (G1Point memory r) { uint256[3] memory input; input[0] = p.x; input[1] = p.y; input[2] = s; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(sub(gas(), 2000), 7, input, 0x60, r, 0x40) } // Check multiplication succeeded require(success, "Snark: Scalar Multiplication Failed"); } /** * @notice Performs pairing check on points * @dev The result of computing the pairing check * e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1 * For example, * pairing([P1(), P1().negate()], [P2(), P2()]) should return true. * @return if pairing check passed */ function pairing( G1Point memory _a1, G2Point memory _a2, G1Point memory _b1, G2Point memory _b2, G1Point memory _c1, G2Point memory _c2, G1Point memory _d1, G2Point memory _d2 ) internal view returns (bool) { uint256[PAIRING_INPUT_SIZE] memory input = [ _a1.x, _a1.y, _a2.x[0], _a2.x[1], _a2.y[0], _a2.y[1], _b1.x, _b1.y, _b2.x[0], _b2.x[1], _b2.y[0], _b2.y[1], _c1.x, _c1.y, _c2.x[0], _c2.x[1], _c2.y[0], _c2.y[1], _d1.x, _d1.y, _d2.x[0], _d2.x[1], _d2.y[0], _d2.y[1] ]; uint256[1] memory out; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall( sub(gas(), 2000), 8, input, PAIRING_INPUT_WIDTH, out, 0x20 ) } // Check if operation succeeded require(success, "Snark: Pairing Verification Failed"); return out[0] != 0; } /** * @notice Verifies snark proof against proving key * @param _vk - Verification Key * @param _proof - snark proof * @param _inputs - inputs */ function verify( VerifyingKey memory _vk, SnarkProof memory _proof, uint256[] memory _inputs ) internal view returns (bool) { // Compute the linear combination vkX G1Point memory vkX = G1Point(0, 0); // Loop through every input for (uint i = 0; i < _inputs.length; i++) { // Make sure inputs are less than SNARK_SCALAR_FIELD require(_inputs[i] < SNARK_SCALAR_FIELD, "Snark: Input > SNARK_SCALAR_FIELD"); // Add to vkX point vkX = add(vkX, scalarMul(_vk.ic[i + 1], _inputs[i])); } // Compute final vkX point vkX = add(vkX, _vk.ic[0]); // Verify pairing and return return pairing( negate(_proof.a), _proof.b, _vk.alpha1, _vk.beta2, vkX, _vk.gamma2, _proof.c, _vk.delta2 ); } }
Calculate commitment hash
uint256 hash = hashCommitment(generatedCommitments[notesIter]);
5,809,460
[ 1, 8695, 23274, 1651, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1651, 273, 1651, 5580, 475, 12, 11168, 5580, 1346, 63, 12903, 2360, 19226, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.4; import "@openzeppelin/contracts/access/Ownable.sol"; /** @title A Multi Sig Safe Contract @notice Implements a multi signature safe. Users are added to the safe when it is initialized. The number of required signatures is also set at that time. In order to send funds from the safe, a user must create a transaction which must by signed by the required number before it is executed. The user that created the trasnaction can't sign it. */ contract MultiSigSafe is Ownable { //mapping to determine if an address is an owner aker 1/0 mapping(address => bool) private safeUsers; uint256 private minSigsRequired; uint256 private txnIndex; enum TxnState { Pending, Completed } struct Transaction { address from; address to; uint256 amount; uint256 signatureCount; TxnState txnState; mapping (address => uint8) signatures; } //mapping txnIndex => transaction mapping (uint256 => Transaction) private transactions; //list of current transactions uint256[] private pendingTransactions; modifier validUser() { require(msg.sender == owner() || safeUsers[msg.sender], "Must be a valid owner of the multi sig safe"); _; } /// @notice An event that is emitted when a user is added to the safe. /// @param user The address of the added user. event SafeUserAdded(address indexed user); /// @notice An event that is emitted when funds are deposited into the safe. /// @param from The address of the . /// @param amount The amount deposited. /// @param balance The safe's balance event DepositFunds(address from, uint256 amount, uint256 balance); /// @notice An event that is emitted when a transaction is created. /// @param by The address of the user creating the transaction. /// @param to The address of the user who will receive the ETH if the transaction is completed. /// @param amount The amount of ETH that will be transfered from the safe to the recepient if the transaction is completed. /// @param transactionId The transaction Id. event TransactionCreated(address by, address to, uint256 amount, uint256 transactionId); /// @notice An event that us emitted when a trasnaction is sigend. /// @param by The address of the user who signed the transaction. /// @param transactionId The transaction Id. event TransactionSigned(address by, uint256 transactionId); /// @notice /// @param from The address of the user that created the transaction. /// @param to The address of the recepient. /// @param amount The amount sent to the recepient. /// @param transactionId The transaction Id. event TransactionCompleted(address from, address to, uint256 amount, uint256 transactionId); /** @notice Creates an instance of the multi sig safe. Assigns the users to the safe and sets the number of signatures required to complete a trasnaction. The constructor is payable so ETH can be sent to fund the safe. @param _safeUsers A list of user addresses to be added to the safe. Those will be considered the ownders of the safe. @param _sigsRequired The number of signatures required to complete a trasnaction. */ constructor(address[] memory _safeUsers, uint _sigsRequired) payable { require(_sigsRequired > 0, "Number of signatures required must be > 0"); require(_sigsRequired <= _safeUsers.length, "Number of signatures required must be less than or equal to the number of owners"); minSigsRequired = _sigsRequired; for (uint i = 0; i < _safeUsers.length; i++) { address _newUser = _safeUsers[i]; require(_newUser != address(0), "constructor - Zero address can not be a staker"); require(!safeUsers[_newUser], "constructor - is already a staker"); safeUsers[_newUser] = true; emit SafeUserAdded(_newUser); } emit DepositFunds(msg.sender, msg.value, address(this).balance); } /// @notice Returns the number of signatures required to complete a transaction. function getNumberOfSigsRequired() validUser public view returns (uint256) { return minSigsRequired; } /// @notice Returns a list pending transaction Id's function getPendingTransactions() validUser public view returns (uint256[] memory) { return pendingTransactions; } /// @notice Receives ETH receive() payable external { emit DepositFunds(msg.sender, msg.value, address(this).balance); } /// @notice Creates a trasanction and populates its fields. The transaction will need to be signed by the required number of signatures for it to be completed. /// @param to The address of the recepient. /// @param amount The amoount of ETH to be sent to the recepient. function transferTo(address payable to, uint amount) validUser public { //make sure the balance is >= the amount of the transaction require(address(this).balance >= amount, "Not enough balance in the safe"); uint txnId = txnIndex; Transaction storage transaction = transactions[txnId]; txnIndex++; transaction.from = msg.sender; transaction.to = to; transaction.amount = amount; transaction.signatureCount = 0; transaction.txnState = TxnState.Pending; pendingTransactions.push(txnId); emit TransactionCreated(msg.sender, to, amount, txnId); } /// @notice Signs a trasanction. If the number of required signatures is reached, the trasanction is executed and marked as complete. /// @param txnId The Id of the transaction to be signed. function signTransaction(uint txnId) validUser public { Transaction storage txn = transactions[txnId]; require(address(0) != txn.from, "Transaction does not exit"); require(msg.sender != txn.from, "Transaction creator can not sign it"); require(txn.signatures[msg.sender] != 1, "Transaction already signed"); require(txn.txnState != TxnState.Completed, "Transaction already completed"); txn.signatures[msg.sender] = 1; txn.signatureCount++; emit TransactionSigned(msg.sender, txnId); //if the transaction has a signature count >= the minimum signatures we can process the transaction //then we need to validate the transaction if (txn.signatureCount >= minSigsRequired) { //check balance require(address(this).balance >= txn.amount, "Not enough balance in the safe"); txn.txnState = TxnState.Completed; (bool success, bytes memory result) = txn.to.call{value: txn.amount}(""); require(success, "signTransaction: tx failed"); //emit an event emit TransactionCompleted(txn.from, txn.to, txn.amount, txnId); } } }
@notice @param from The address of the user that created the transaction. @param to The address of the recepient. @param amount The amount sent to the recepient. @param transactionId The transaction Id.
event TransactionCompleted(address from, address to, uint256 amount, uint256 transactionId);
12,962,550
[ 1, 2080, 1021, 1758, 434, 326, 729, 716, 2522, 326, 2492, 18, 225, 358, 1021, 1758, 434, 326, 2637, 84, 1979, 18, 225, 3844, 1021, 3844, 3271, 358, 326, 2637, 84, 1979, 18, 225, 24112, 1021, 2492, 3124, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 5947, 9556, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 3844, 16, 2254, 5034, 24112, 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 ]
//Address: 0xadb797366e36697dc9742a8c820d3dda931668d2 //Contract name: minter //Balance: 3.229862423516881406 Ether //Verification Date: 10/23/2017 //Transacion Count: 6 // CODE STARTS HERE pragma solidity ^0.4.16; /** @title owned. */ contract owned { address owner; function owned() { owner = msg.sender; } function changeOwner(address newOwner) onlyOwner { owner = newOwner; } modifier onlyOwner() { require(msg.sender==owner); _; } } /** @title mortal. */ contract mortal is owned() { function kill() onlyOwner { if (msg.sender == owner) selfdestruct(owner); } } /** @title DSMath. */ contract DSMath { // Copyright (C) 2015, 2016, 2017 DappHub, LLC // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // 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 (express or implied). // /* // uint128 functions (h is for half) // */ function hmore(uint128 x, uint128 y) constant internal returns (bool) { return x>y; } function hless(uint128 x, uint128 y) constant internal returns (bool) { return x<y; } function hadd(uint128 x, uint128 y) constant internal returns (uint128 z) { require((z = x + y) >= x); } function hsub(uint128 x, uint128 y) constant internal returns (uint128 z) { require((z = x - y) <= x); } function hmul(uint128 x, uint128 y) constant internal returns (uint128 z) { require(y == 0 ||(z = x * y)/ y == x); } function hdiv(uint128 x, uint128 y) constant internal returns (uint128 z) { z = x / y; } function hmin(uint128 x, uint128 y) constant internal returns (uint128 z) { return x <= y ? x : y; } function hmax(uint128 x, uint128 y) constant internal returns (uint128 z) { return x >= y ? x : y; } // /* // int256 functions // */ /* WAD math */ uint64 constant WAD_Dec=18; uint128 constant WAD = 10 ** 18; function wmore(uint128 x, uint128 y) constant internal returns (bool) { return hmore(x, y); } function wless(uint128 x, uint128 y) constant internal returns (bool) { return hless(x, y); } function wadd(uint128 x, uint128 y) constant returns (uint128) { return hadd(x, y); } function wsub(uint128 x, uint128 y) constant returns (uint128) { return hsub(x, y); } function wmul(uint128 x, uint128 y) constant returns (uint128 z) { z = cast((uint256(x) * y + WAD / 2) / WAD); } function wdiv(uint128 x, uint128 y) constant internal returns (uint128 z) { z = cast((uint256(x) * WAD + y / 2) / y); } function wmin(uint128 x, uint128 y) constant internal returns (uint128) { return hmin(x, y); } function wmax(uint128 x, uint128 y) constant internal returns (uint128) { return hmax(x, y); } function cast(uint256 x) constant internal returns (uint128 z) { assert((z = uint128(x)) == x); } } /** @title I_minter. */ contract I_minter { event EventCreateStatic(address indexed _from, uint128 _value, uint _transactionID, uint _Price); event EventRedeemStatic(address indexed _from, uint128 _value, uint _transactionID, uint _Price); event EventCreateRisk(address indexed _from, uint128 _value, uint _transactionID, uint _Price); event EventRedeemRisk(address indexed _from, uint128 _value, uint _transactionID, uint _Price); event EventBankrupt(); function Leverage() constant returns (uint128) {} function RiskPrice(uint128 _currentPrice,uint128 _StaticTotal,uint128 _RiskTotal, uint128 _ETHTotal) constant returns (uint128 price) {} function RiskPrice(uint128 _currentPrice) constant returns (uint128 price) {} function PriceReturn(uint _TransID,uint128 _Price) {} function NewStatic() external payable returns (uint _TransID) {} function NewStaticAdr(address _Risk) external payable returns (uint _TransID) {} function NewRisk() external payable returns (uint _TransID) {} function NewRiskAdr(address _Risk) external payable returns (uint _TransID) {} function RetRisk(uint128 _Quantity) external payable returns (uint _TransID) {} function RetStatic(uint128 _Quantity) external payable returns (uint _TransID) {} function Strike() constant returns (uint128) {} } /** @title I_Pricer. */ contract I_Pricer { uint128 public lastPrice; I_minter public mint; string public sURL; mapping (bytes32 => uint) RevTransaction; function __callback(bytes32 myid, string result) {} function queryCost() constant returns (uint128 _value) {} function QuickPrice() payable {} function requestPrice(uint _actionID) payable returns (uint _TrasID) {} function collectFee() returns(bool) {} function () { //if ether is sent to this address, send it back. revert(); } } /** @title I_coin. */ contract I_coin is mortal { event EventClear(); I_minter public mint; string public name; //fancy name: eg Simon Bucks uint8 public decimals=18; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = ''; //human 0.1 standard. Just an arbitrary versioning scheme. function mintCoin(address target, uint256 mintedAmount) returns (bool success) {} function meltCoin(address target, uint256 meltedAmount) returns (bool success) {} function approveAndCall(address _spender, uint256 _value, bytes _extraData){} function setMinter(address _minter) {} function increaseApproval (address _spender, uint256 _addedValue) returns (bool success) {} function decreaseApproval (address _spender, uint256 _subtractedValue) returns (bool success) {} // @param _owner The address from which the balance will be retrieved // @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} // @notice send `_value` token to `_to` from `msg.sender` // @param _to The address of the recipient // @param _value The amount of token to be transferred // @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} // @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` // @param _from The address of the sender // @param _to The address of the recipient // @param _value The amount of token to be transferred // @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} // @notice `msg.sender` approves `_addr` to spend `_value` tokens // @param _spender The address of the account able to transfer the tokens // @param _value The amount of wei to be approved for transfer // @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); // @param _owner The address of the account owning tokens // @param _spender The address of the account able to transfer the tokens // @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; // @return total amount of tokens uint256 public totalSupply; } /** @title DSBaseActor. */ contract DSBaseActor { /* Copyright 2016 Nexus Development, LLC 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. */ bool _ds_mutex; modifier mutex() { assert(!_ds_mutex); _ds_mutex = true; _; _ds_mutex = false; } function tryExec( address target, bytes calldata, uint256 value) mutex() internal returns (bool call_ret) { /** @dev Requests new StatiCoins be made for a given address * @param target where the ETH is sent to. * @param calldata * @param value * @return True if ETH is transfered */ return target.call.value(value)(calldata); } function exec( address target, bytes calldata, uint256 value) internal { assert(tryExec(target, calldata, value)); } } /** @title canFreeze. */ contract canFreeze is owned { //Copyright (c) 2017 GenkiFS //Basically a "break glass in case of emergency" bool public frozen=false; modifier LockIfFrozen() { if (!frozen){ _; } } function Freeze() onlyOwner { // fixes the price and allows everyone to redeem their coins at the current value // only becomes false when all ETH has been claimed or the pricer contract is changed frozen=true; } } /** @title oneWrite. */ contract oneWrite { // Adds modifies that allow one function to be called only once //Copyright (c) 2017 GenkiFS bool written = false; function oneWrite() { /** @dev Constuctor, make sure written=false initally */ written = false; } modifier LockIfUnwritten() { if (written){ _; } } modifier writeOnce() { if (!written){ written=true; _; } } } /** @title pricerControl. */ contract pricerControl is canFreeze { // Copyright (c) 2017 GenkiFS // Controls the Pricer contract for minter. Allows updates to be made in the future by swapping the pricer contract // Although this is not expected, web addresses, API's, new oracles could require adjusments to the pricer contract // A delay of 2 days is implemented to allow coinholders to redeem their coins if they do not agree with the new contract // A new pricer contract unfreezes the minter (allowing a live price to be used) I_Pricer public pricer; address public future; uint256 public releaseTime; uint public PRICER_DELAY = 2; // days updated when coins are set event EventAddressChange(address indexed _from, address indexed _to, uint _timeChange); function setPricer(address newAddress) onlyOwner { /** @dev Changes the Pricer contract, after a certain delay * @param newAddress Allows coins to be created and sent to other people * @return transaction ID which can be viewed in the pending mapping */ releaseTime = now + PRICER_DELAY; future = newAddress; EventAddressChange(pricer, future, releaseTime); } modifier updates() { if (now > releaseTime && pricer != future){ update(); //log0('Updating'); } _; } modifier onlyPricer() { require(msg.sender==address(pricer)); _; } function update() internal { pricer = I_Pricer(future); frozen = false; } } /** @title minter. */ contract minter is I_minter, DSBaseActor, oneWrite, pricerControl, DSMath{ // // Copyright (c) 2017 GenkiFS // This contract is the controller for the StatiCoin contracts. // Users have 4(+2) functions they can call to mint/melt Static/Risk coins which then calls the Pricer contract // after a delay the Pricer contract will call back to the PriceReturn() function // this will then call one of the functions ActionNewStatic, ActionNewRisk, ActionRetStatic, ActionRetRisk // which will then call the Static or Risk ERC20 contracts to mint/melt new tokens // Transfer of tokens is handled by the ERC20 contracts, ETH is stored here. enum Action {NewStatic, RetStatic, NewRisk, RetRisk} // Enum of what users can do struct Trans { // Struct uint128 amount; // Amount sent by the user (Can be either ETH or number of returned coins) address holder; // Address of the user Action action; // Type of action requested (mint/melt a Risk/StatiCoin) bytes32 pricerID; // ID for the pricer function } uint128 public lastPrice; //Storage of the last price returned by the Pricer contract uint128 public PendingETH; //Amount of eth to be added to the contract uint public TransID=0; // An increasing counter to keep track of transactions requested uint public TransCompleted; // Last transaction removed string public Currency; // Name of underlying base currency I_coin public Static; // ERC20 token interface for the StatiCoin I_coin public Risk; // ERC20 token interface for the Risk coin uint128 public Multiplier;//=15*10**(17); // default ratio for Risk price uint128 public levToll=5*10**(18-1);//0.5 // this plus the multiplier defines the maximum leverage uint128 public mintFee = 2*10**(18-3); //0.002 Used to pay oricalize and for marketing contract which is in both parties interest. mapping (uint => Trans[]) public pending; // A mapping of pending transactions event EventCreateStatic(address indexed _from, uint128 _value, uint _transactionID, uint _Price); event EventRedeemStatic(address indexed _from, uint128 _value, uint _transactionID, uint _Price); event EventCreateRisk(address indexed _from, uint128 _value, uint _transactionID, uint _Price); event EventRedeemRisk(address indexed _from, uint128 _value, uint _transactionID, uint _Price); event EventBankrupt(); //Called when no more ETH is in the contract and everything needs to be manually reset. function minter(string _currency, uint128 _Multiplier) { //,uint8 _DecimalPlaces // CONSTRUCTOR Currency=_currency; Multiplier = _Multiplier; // can't add new contracts here as it gives out of gas messages. Too much code. } function () { //if ETH is just sent to this address then we cannot determine if it's for StatiCoins or RiskCoins, so send it back. revert(); } function Bailout() external payable { /** @dev Allows extra ETH to be added to the benefit of both types of coin holders * @return nothing */ } function NewStatic() external payable returns (uint _TransID) { /** @dev Requests new StatiCoins be made for the sender. * This cannot be called by a contract. Only a simple wallet (with 0 codesize). * Contracts must use the Approve, transferFrom pattern and move coins from wallets * @return transaction ID which can be viewed in the pending mapping */ _TransID=NewCoinInternal(msg.sender,cast(msg.value),Action.NewStatic); //log0('NewStatic'); } function NewStaticAdr(address _user) external payable returns (uint _TransID) { /** @dev Requests new StatiCoins be made for a given address. * The address cannot be a contract, only a simple wallet (with 0 codesize). * Contracts must use the Approve, transferFrom pattern and move coins from wallets * @param _user Allows coins to be created and sent to other people * @return transaction ID which can be viewed in the pending mapping */ _TransID=NewCoinInternal(_user,cast(msg.value),Action.NewStatic); //log0('NewStatic'); } function NewRisk() external payable returns (uint _TransID) { /** @dev Requests new Riskcoins be made for the sender. * This cannot be called by a contract, only a simple wallet (with 0 codesize). * Contracts must use the Approve, transferFrom pattern and move coins from wallets * @return transaction ID which can be viewed in the pending mapping */ _TransID=NewCoinInternal(msg.sender,cast(msg.value),Action.NewRisk); //log0('NewRisk'); } function NewRiskAdr(address _user) external payable returns (uint _TransID) { /** @dev Requests new Riskcoins be made for a given address. * The address cannot be a contract, only a simple wallet (with 0 codesize). * Contracts must use the Approve, transferFrom pattern and move coins from wallets * @param _user Allows coins to be created and sent to other people * @return transaction ID which can be viewed in the pending mapping */ _TransID=NewCoinInternal(_user,cast(msg.value),Action.NewRisk); //log0('NewRisk'); } function RetRisk(uint128 _Quantity) external payable LockIfUnwritten returns (uint _TransID) { /** @dev Returns Riskcoins. Needs a bit of eth sent to pay the pricer contract and the excess is returned. * The address cannot be a contract, only a simple wallet (with 0 codesize). * @param _Quantity Amount of coins being returned * @return transaction ID which can be viewed in the pending mapping */ if(frozen){ //Skip the pricer contract TransID++; ActionRetRisk(Trans(_Quantity,msg.sender,Action.RetRisk,0),TransID,lastPrice); _TransID=TransID; } else { //Only returned when Risk price is positive _TransID=RetCoinInternal(_Quantity,cast(msg.value),msg.sender,Action.RetRisk); } //log0('RetRisk'); } function RetStatic(uint128 _Quantity) external payable LockIfUnwritten returns (uint _TransID) { /** @dev Returns StatiCoins, Needs a bit of eth sent to pay the pricer contract * @param _Quantity Amount of coins being returned * @return transaction ID which can be viewed in the pending mapping */ if(frozen){ //Skip the pricer contract TransID++; ActionRetStatic(Trans(_Quantity,msg.sender,Action.RetStatic,0),TransID,lastPrice); _TransID=TransID; } else { //Static can be returned at any time _TransID=RetCoinInternal(_Quantity,cast(msg.value),msg.sender,Action.RetStatic); } //log0('RetStatic'); } //****************************// // Constant functions (Ones that don't write to the blockchain) function StaticEthAvailable() constant returns (uint128) { /** @dev Returns the total amount of eth that can be sent to buy StatiCoins * @return amount of Eth */ return StaticEthAvailable(cast(Risk.totalSupply()), cast(this.balance)); } function StaticEthAvailable(uint128 _RiskTotal, uint128 _TotalETH) constant returns (uint128) { /** @dev Returns the total amount of eth that can be sent to buy StatiCoins allows users to test arbitrary amounts of RiskTotal and ETH contained in the contract * @param _RiskTotal Quantity of riskcoins * @param _TotalETH Total value of ETH in the contract * @return amount of Eth */ // (Multiplier+levToll)*_RiskTotal - _TotalETH uint128 temp = wmul(wadd(Multiplier,levToll),_RiskTotal); if(wless(_TotalETH,temp)){ return wsub(temp ,_TotalETH); } else { return 0; } } function RiskPrice(uint128 _currentPrice,uint128 _StaticTotal,uint128 _RiskTotal, uint128 _ETHTotal) constant returns (uint128 price) { /** @dev Allows users to query various hypothetical prices of RiskCoins in terms of base currency * @param _currentPrice Current price of ETH in Base currency. * @param _StaticTotal Total quantity of StatiCoins issued. * @param _RiskTotal Total quantity of invetor coins issued. * @param _ETHTotal Total quantity of ETH in the contract. * @return price of RiskCoins */ if(_ETHTotal == 0 || _RiskTotal==0){ //Return the default price of _currentPrice * Multiplier return wmul( _currentPrice , Multiplier); } else { if(hmore( wmul(_ETHTotal , _currentPrice),_StaticTotal)){ //_ETHTotal*_currentPrice>_StaticTotal //Risk price is positive return wdiv(wsub(wmul(_ETHTotal , _currentPrice) , _StaticTotal) , _RiskTotal); // (_ETHTotal * _currentPrice) - _StaticTotal) / _RiskTotal } else { //RiskPrice is negative return 0; } } } function RiskPrice(uint128 _currentPrice) constant returns (uint128 price) { /** @dev Allows users to query price of RiskCoins in terms of base currency, using current quantities of coins * @param _currentPrice Current price of ETH in Base currency. * @return price of RiskCoins */ return RiskPrice(_currentPrice,cast(Static.totalSupply()),cast(Risk.totalSupply()),wsub(cast(this.balance),PendingETH)); } function LastRiskPrice() constant returns (uint128 price) { /** @dev Allows users to query the last price of RiskCoins in terms of base currency * @return price of RiskCoins */ return RiskPrice(lastPrice); } function Leverage() public constant returns (uint128) { /** @dev Returns the ratio at which Riskcoin grows in value for the equivalent growth in ETH price * @return ratio */ if(Risk.totalSupply()>0){ return wdiv(cast(this.balance) , cast(Risk.totalSupply())); // this.balance/Risk.totalSupply }else{ return 0; } } function Strike() public constant returns (uint128) { /** @dev Returns the current price at which the Risk price goes negative * @return Risk price in underlying per ETH */ if(this.balance>0){ return wdiv(cast(Static.totalSupply()) , cast(this.balance)); //Static.totalSupply / this.balance }else{ return 0; } } //****************************// // Only owner can access the following functions function setFee(uint128 _newFee) onlyOwner { /** @dev Allows the minting fee to be changed, only owner can modify * @param _newFee Size of new fee * return nothing */ mintFee=_newFee; } function setCoins(address newRisk,address newStatic) updates onlyOwner writeOnce { /** @dev Allows the minting fee to be reduced, only owner can modify once, Triggers the pricer to be updated * @param newRisk Address of Riskcoin contract * @param newStatic Address of StatiCoin contract * return nothing */ Risk=I_coin(newRisk); Static=I_coin(newStatic); PRICER_DELAY = 2 days; } //****************************// // Only Pricer can access the following function function PriceReturn(uint _TransID,uint128 _Price) onlyPricer { /** @dev Return function for the Pricer contract only. Controls melting and minting of new coins. * @param _TransID Tranasction ID issued by the minter. * @param _Price Quantity of Base currency per ETH delivered by the Pricer contract * Nothing returned. One of 4 functions is implemented */ Trans memory details=pending[_TransID][0];//Get the details for this transaction. if(0==_Price||frozen){ //If there is an error in pricing or contract is frozen, use the old price _Price=lastPrice; } else { if(Static.totalSupply()>0 && Risk.totalSupply()>0) {// dont update if there are coins missing lastPrice=_Price; // otherwise update the last price } } //Mint some new StatiCoins if(Action.NewStatic==details.action){ ActionNewStatic(details,_TransID, _Price); } //Melt some old StatiCoins if(Action.RetStatic==details.action){ ActionRetStatic(details,_TransID, _Price); } //Mint some new Risk coins if(Action.NewRisk==details.action){ ActionNewRisk(details,_TransID, _Price); } //Melt some old Risk coin if(Action.RetRisk==details.action){ ActionRetRisk(details,_TransID, _Price); } //Remove the transaction from the blockchain (saving some gas) TransCompleted=_TransID; delete pending[_TransID]; } //****************************// // Only internal functions now function ActionNewStatic(Trans _details, uint _TransID, uint128 _Price) internal { /** @dev Internal function to create new StatiCoins based on transaction data in the Pending queue. If not enough spare StatiCoins are available then ETH is refunded. * @param _details Structure holding the amount sent (in ETH), the address of the person to sent to, and the type of request. * @param _TransID ID of the transaction (as stored in this contract). * @param _Price Current 24 hour average price as returned by the oracle in the pricer contract. * @return function returns nothing, but adds StatiCoins to the users address and events are created */ //log0('NewStatic'); //if(Action.NewStatic<>_details.action){revert();} //already checked uint128 CurRiskPrice=RiskPrice(_Price); uint128 AmountReturn; uint128 AmountMint; //Calculates the amount of ETH that can be added to create StatiCoins (excluding the amount already sent and stored in the contract) uint128 StaticAvail = StaticEthAvailable(cast(Risk.totalSupply()), wsub(cast(this.balance),PendingETH)); // If the amount sent is less than the Static amount available, everything is fine. Nothing needs to be returned. if (wless(_details.amount,StaticAvail)) { // restrictions do not hamper the creation of a StatiCoin AmountMint = _details.amount; AmountReturn = 0; } else { // Amount of Static is less than amount requested. // Take all the StatiCoins available. // Maybe there is zero Static available, so all will be returned. AmountMint = StaticAvail; AmountReturn = wsub(_details.amount , StaticAvail) ; } if(0 == CurRiskPrice){ // return all the ETH AmountReturn = _details.amount; //AmountMint = 0; //not required as Risk price = 0 } //Static can be added when Risk price is positive and leverage is below the limit if(CurRiskPrice > 0 && StaticAvail>0 ){ // Dont create if CurRiskPrice is 0 or there is no Static available (leverage is too high) //log0('leverageOK'); Static.mintCoin(_details.holder, uint256(wmul(AmountMint , _Price))); //request coins from the Static creator contract EventCreateStatic(_details.holder, wmul(AmountMint , _Price), _TransID, _Price); // Event giving the holder address, coins created, transaction id, and price PendingETH=wsub(PendingETH,AmountMint); } if (AmountReturn>0) { // return some money because not enough StatiCoins are available bytes memory calldata; // define a blank `bytes` exec(_details.holder,calldata, AmountReturn); //Refund ETH from this contract PendingETH=wsub(PendingETH,AmountReturn); } } function ActionNewRisk(Trans _details, uint _TransID,uint128 _Price) internal { /** @dev Internal function to create new Risk coins based on transaction data in the Pending queue. Risk coins can only be created if the price is above zero * @param _details Structure holding the amount sent (in ETH), the address of the person to sent to, and the type of request. * @param _TransID ID of the transaction (as stored in this contract). * @param _Price Current 24 hour average price as returned by the oracle in the pricer contract. * @return function returns nothing, but adds Riskcoins to the users address and events are created */ //log0('NewRisk'); //if(Action.NewRisk<>_details.action){revert();} //already checked // Get the Risk price using the amount of ETH in the contract before this transaction existed uint128 CurRiskPrice; if(wless(cast(this.balance),PendingETH)){ CurRiskPrice=0; } else { CurRiskPrice=RiskPrice(_Price,cast(Static.totalSupply()),cast(Risk.totalSupply()),wsub(cast(this.balance),PendingETH)); } if(CurRiskPrice>0){ uint128 quantity=wdiv(wmul(_details.amount , _Price),CurRiskPrice); // No of Riskcoins = _details.amount * _Price / CurRiskPrice Risk.mintCoin(_details.holder, uint256(quantity) ); //request coins from the Riskcoin creator contract EventCreateRisk(_details.holder, quantity, _TransID, _Price); // Event giving the holder address, coins created, transaction id, and price } else { // Don't create if CurRiskPrice is 0, Return all the ETH originally sent bytes memory calldata; // define a blank `bytes` exec(_details.holder,calldata, _details.amount); } PendingETH=wsub(PendingETH,_details.amount); } function ActionRetStatic(Trans _details, uint _TransID,uint128 _Price) internal { /** @dev Internal function to Return StatiCoins based on transaction data in the Pending queue. Static can be returned at any time. * @param _details Structure holding the amount sent (in ETH), the address of the person to sent to, and the type of request. * @param _TransID ID of the transaction (as stored in this contract). * @param _Price Current 24 hour average price as returned by the oracle in the pricer contract. * @return function returns nothing, but removes StatiCoins from the user's address, sends ETH and events are created */ //if(Action.RetStatic<>_details.action){revert();} //already checked //log0('RetStatic'); uint128 _ETHReturned; if(0==Risk.totalSupply()){_Price=lastPrice;} //No Risk coins for balance so use fixed price _ETHReturned = wdiv(_details.amount , _Price); //_details.amount / _Price if (Static.meltCoin(_details.holder,_details.amount)){ // deducted first, will add back if Returning ETH goes wrong. EventRedeemStatic(_details.holder,_details.amount ,_TransID, _Price); if (wless(cast(this.balance),_ETHReturned)) { _ETHReturned=cast(this.balance);//Not enough ETH available. Return all Eth in the contract } bytes memory calldata; // define a blank `bytes` if (tryExec(_details.holder, calldata, _ETHReturned)) { //ETH returned successfully } else { // there was an error, so add back the amount previously deducted Static.mintCoin(_details.holder,_details.amount); //Add back the amount requested EventCreateStatic(_details.holder,_details.amount ,_TransID, _Price); //redo the creation event } if ( 0==this.balance) { Bankrupt(); } } } function ActionRetRisk(Trans _details, uint _TransID,uint128 _Price) internal { /** @dev Internal function to Return Riskcoins based on transaction data in the Pending queue. Riskcoins can be returned so long as the Risk price is greater than 0. * @param _details Structure holding the amount sent (in ETH), the address of the person to sent to, and the type of request. * @param _TransID ID of the transaction (as stored in this contract). * @param _Price Current 24 hour average price as returned by the oracle in the Pricer contract. * @return function returns nothing, but removes StatiCoins from the users address, sends ETH and events are created */ //if(Action.RetRisk<>_details.action){revert();} //already checked //log0('RetRisk'); uint128 _ETHReturned; uint128 CurRiskPrice; //if(0==Static.totalSupply()){_Price=lastPrice};// no StatiCoins, so all Risk coins are worth the same. // _ETHReturned = _details.amount / _RiskTotal * _ETHTotal CurRiskPrice=RiskPrice(_Price); if(CurRiskPrice>0){ _ETHReturned = wdiv( wmul(_details.amount , CurRiskPrice) , _Price); // _details.amount * CurRiskPrice / _Price if (Risk.meltCoin(_details.holder,_details.amount )){ // Coins are deducted first, will add back if returning ETH goes wrong. EventRedeemRisk(_details.holder,_details.amount ,_TransID, _Price); if ( wless(cast(this.balance),_ETHReturned)) { // should never happen, but just in case _ETHReturned=cast(this.balance); } bytes memory calldata; // define a blank `bytes` if (tryExec(_details.holder, calldata, _ETHReturned)) { //Returning ETH went ok. } else { // there was an error, so add back the amount previously deducted from the Riskcoin contract Risk.mintCoin(_details.holder,_details.amount); EventCreateRisk(_details.holder,_details.amount ,_TransID, _Price); } } } else { // Risk price is zero so can't do anything. Call back and delete the transaction from the contract } } function IsWallet(address _address) internal returns(bool){ /** * @dev checks that _address is not a contract. * @param _address to check * @return True if not a contract, */ uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_address) } return(0==codeLength); } function RetCoinInternal(uint128 _Quantity, uint128 _AmountETH, address _user, Action _action) internal updates returns (uint _TransID) { /** @dev Requests coins be melted and ETH returned * @param _Quantity of Static or Risk coins to be melted0 * @param _AmountETH Amount of eth sent to this contract to cover oracle fee. Excess is returned. * @param _user Address to whom the returned ETH will be sent. * @param _action Allows Static or Risk coins to be returned * @return transaction ID which can be viewed in the Pending mapping */ require(IsWallet(_user)); uint128 refund; uint128 Fee=pricer.queryCost(); //Get the cost of querying the pricer contract if(wless(_AmountETH,Fee)){ revert(); //log0('Not enough ETH to mint'); } else { refund=wsub(_AmountETH,Fee);//Returning coins has had too much ETH sent, so return it. } if(0==_Quantity){revert();}// quantity has to be non zero TransID++; uint PricerID = pricer.requestPrice.value(uint256(Fee))(TransID); //Ask the pricer to get the price. The Fee also cover calling the function PriceReturn at a later time. pending[TransID].push(Trans(_Quantity,_user,_action,bytes32(PricerID))); //Add a transaction to the Pending queue. _TransID=TransID; //return the transaction ID to the user _user.transfer(uint256(refund)); //Return ETH if too much has been sent to cover the pricer } function NewCoinInternal(address _user, uint128 _amount, Action _action) internal updates LockIfUnwritten LockIfFrozen returns (uint _TransID) { /** @dev Requests new coins be made * @param _user Address for whom the coins are to be created * @param _amount Amount of eth sent to this contract * @param _action Allows Static or Risk coins to be minted * @return transaction ID which can be viewed in the pending mapping */ require(IsWallet(_user)); uint128 toCredit; uint128 Fee=wmax(wmul(_amount,mintFee),pricer.queryCost()); // fee is the maxium of the pricer query cost and a mintFee% of value sent if(wless(_amount,Fee)) revert(); //log0('Not enough ETH to mint'); TransID++; uint PricerID = pricer.requestPrice.value(uint256(Fee))(TransID); //Ask the pricer to return the price toCredit=wsub(_amount,Fee); pending[TransID].push(Trans(toCredit,_user,_action,bytes32(PricerID))); //Store the transaction ID and data ready for later recall PendingETH=wadd(PendingETH,toCredit); _TransID=TransID;//return the transaction ID for this contract to the user } function Bankrupt() internal { EventBankrupt(); // Reset the contract Static.kill(); //delete all current Static tokens Risk.kill(); //delete all current Risk tokens //need to create new coins externally, too much gas is used if done here. frozen=false; written=false; // Reset the writeOnce and LockIfUnwritten modifiers } }
_details.amount / _Price
_ETHReturned = wdiv(_details.amount , _Price);
13,108,936
[ 1, 67, 6395, 18, 8949, 342, 389, 5147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 1584, 44, 22360, 273, 341, 2892, 24899, 6395, 18, 8949, 269, 389, 5147, 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 ]
pragma solidity 0.4.18; // File: contracts/ERC20Interface.sol // https://github.com/ethereum/EIPs/issues/20 interface ERC20 { function totalSupply() public view returns (uint supply); function balanceOf(address _owner) public view returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint remaining); function decimals() public view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } // File: contracts/ConversionRatesInterface.sol interface ConversionRatesInterface { function recordImbalance( ERC20 token, int buyAmount, uint rateUpdateBlock, uint currentBlock ) public; function getRate(ERC20 token, uint currentBlockNumber, bool buy, uint qty) public view returns(uint); } // File: contracts/Utils.sol /// @title Kyber constants contract contract Utils { ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); uint constant internal PRECISION = (10**18); uint constant internal MAX_QTY = (10**28); // 10B tokens uint constant internal MAX_RATE = (PRECISION * 10**6); // up to 1M tokens per ETH uint constant internal MAX_DECIMALS = 18; uint constant internal ETH_DECIMALS = 18; mapping(address=>uint) internal decimals; function setDecimals(ERC20 token) internal { if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS; else decimals[token] = token.decimals(); } function getDecimals(ERC20 token) internal view returns(uint) { if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access uint tokenDecimals = decimals[token]; // technically, there might be token with decimals 0 // moreover, very possible that old tokens have decimals 0 // these tokens will just have higher gas fees. if(tokenDecimals == 0) return token.decimals(); return tokenDecimals; } function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) { require(srcQty <= MAX_QTY); require(rate <= MAX_RATE); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION; } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals))); } } function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) { require(dstQty <= MAX_QTY); require(rate <= MAX_RATE); //source quantity is rounded up. to avoid dest quantity being too low. uint numerator; uint denominator; if (srcDecimals >= dstDecimals) { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals))); denominator = rate; } else { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); numerator = (PRECISION * dstQty); denominator = (rate * (10**(dstDecimals - srcDecimals))); } return (numerator + denominator - 1) / denominator; //avoid rounding down errors } } // File: contracts/PermissionGroups.sol contract PermissionGroups { address public admin; address public pendingAdmin; mapping(address=>bool) internal operators; mapping(address=>bool) internal alerters; address[] internal operatorsGroup; address[] internal alertersGroup; uint constant internal MAX_GROUP_SIZE = 50; function PermissionGroups() public { admin = msg.sender; } modifier onlyAdmin() { require(msg.sender == admin); _; } modifier onlyOperator() { require(operators[msg.sender]); _; } modifier onlyAlerter() { require(alerters[msg.sender]); _; } function getOperators () external view returns(address[]) { return operatorsGroup; } function getAlerters () external view returns(address[]) { return alertersGroup; } event TransferAdminPending(address pendingAdmin); /** * @dev Allows the current admin to set the pendingAdmin address. * @param newAdmin The address to transfer ownership to. */ function transferAdmin(address newAdmin) public onlyAdmin { require(newAdmin != address(0)); TransferAdminPending(pendingAdmin); pendingAdmin = newAdmin; } /** * @dev Allows the current admin to set the admin in one tx. Useful initial deployment. * @param newAdmin The address to transfer ownership to. */ function transferAdminQuickly(address newAdmin) public onlyAdmin { require(newAdmin != address(0)); TransferAdminPending(newAdmin); AdminClaimed(newAdmin, admin); admin = newAdmin; } event AdminClaimed( address newAdmin, address previousAdmin); /** * @dev Allows the pendingAdmin address to finalize the change admin process. */ function claimAdmin() public { require(pendingAdmin == msg.sender); AdminClaimed(pendingAdmin, admin); admin = pendingAdmin; pendingAdmin = address(0); } event AlerterAdded (address newAlerter, bool isAdd); function addAlerter(address newAlerter) public onlyAdmin { require(!alerters[newAlerter]); // prevent duplicates. require(alertersGroup.length < MAX_GROUP_SIZE); AlerterAdded(newAlerter, true); alerters[newAlerter] = true; alertersGroup.push(newAlerter); } function removeAlerter (address alerter) public onlyAdmin { require(alerters[alerter]); alerters[alerter] = false; for (uint i = 0; i < alertersGroup.length; ++i) { if (alertersGroup[i] == alerter) { alertersGroup[i] = alertersGroup[alertersGroup.length - 1]; alertersGroup.length--; AlerterAdded(alerter, false); break; } } } event OperatorAdded(address newOperator, bool isAdd); function addOperator(address newOperator) public onlyAdmin { require(!operators[newOperator]); // prevent duplicates. require(operatorsGroup.length < MAX_GROUP_SIZE); OperatorAdded(newOperator, true); operators[newOperator] = true; operatorsGroup.push(newOperator); } function removeOperator (address operator) public onlyAdmin { require(operators[operator]); operators[operator] = false; for (uint i = 0; i < operatorsGroup.length; ++i) { if (operatorsGroup[i] == operator) { operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1]; operatorsGroup.length -= 1; OperatorAdded(operator, false); break; } } } } // File: contracts/Withdrawable.sol /** * @title Contracts that should be able to recover tokens or ethers * @author Ilan Doron * @dev This allows to recover any tokens or Ethers received in a contract. * This will prevent any accidental loss of tokens. */ contract Withdrawable is PermissionGroups { event TokenWithdraw(ERC20 token, uint amount, address sendTo); /** * @dev Withdraw all ERC20 compatible tokens * @param token ERC20 The address of the token contract */ function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin { require(token.transfer(sendTo, amount)); TokenWithdraw(token, amount, sendTo); } event EtherWithdraw(uint amount, address sendTo); /** * @dev Withdraw Ethers */ function withdrawEther(uint amount, address sendTo) external onlyAdmin { sendTo.transfer(amount); EtherWithdraw(amount, sendTo); } } // File: contracts/VolumeImbalanceRecorder.sol contract VolumeImbalanceRecorder is Withdrawable { uint constant internal SLIDING_WINDOW_SIZE = 5; uint constant internal POW_2_64 = 2 ** 64; struct TokenControlInfo { uint minimalRecordResolution; // can be roughly 1 cent uint maxPerBlockImbalance; // in twei resolution uint maxTotalImbalance; // max total imbalance (between rate updates) // before halting trade } mapping(address => TokenControlInfo) internal tokenControlInfo; struct TokenImbalanceData { int lastBlockBuyUnitsImbalance; uint lastBlock; int totalBuyUnitsImbalance; uint lastRateUpdateBlock; } mapping(address => mapping(uint=>uint)) public tokenImbalanceData; function VolumeImbalanceRecorder(address _admin) public { require(_admin != address(0)); admin = _admin; } function setTokenControlInfo( ERC20 token, uint minimalRecordResolution, uint maxPerBlockImbalance, uint maxTotalImbalance ) public onlyAdmin { tokenControlInfo[token] = TokenControlInfo( minimalRecordResolution, maxPerBlockImbalance, maxTotalImbalance ); } function getTokenControlInfo(ERC20 token) public view returns(uint, uint, uint) { return (tokenControlInfo[token].minimalRecordResolution, tokenControlInfo[token].maxPerBlockImbalance, tokenControlInfo[token].maxTotalImbalance); } function addImbalance( ERC20 token, int buyAmount, uint rateUpdateBlock, uint currentBlock ) internal { uint currentBlockIndex = currentBlock % SLIDING_WINDOW_SIZE; int recordedBuyAmount = int(buyAmount / int(tokenControlInfo[token].minimalRecordResolution)); int prevImbalance = 0; TokenImbalanceData memory currentBlockData = decodeTokenImbalanceData(tokenImbalanceData[token][currentBlockIndex]); // first scenario - this is not the first tx in the current block if (currentBlockData.lastBlock == currentBlock) { if (uint(currentBlockData.lastRateUpdateBlock) == rateUpdateBlock) { // just increase imbalance currentBlockData.lastBlockBuyUnitsImbalance += recordedBuyAmount; currentBlockData.totalBuyUnitsImbalance += recordedBuyAmount; } else { // imbalance was changed in the middle of the block prevImbalance = getImbalanceInRange(token, rateUpdateBlock, currentBlock); currentBlockData.totalBuyUnitsImbalance = int(prevImbalance) + recordedBuyAmount; currentBlockData.lastBlockBuyUnitsImbalance += recordedBuyAmount; currentBlockData.lastRateUpdateBlock = uint(rateUpdateBlock); } } else { // first tx in the current block int currentBlockImbalance; (prevImbalance, currentBlockImbalance) = getImbalanceSinceRateUpdate(token, rateUpdateBlock, currentBlock); currentBlockData.lastBlockBuyUnitsImbalance = recordedBuyAmount; currentBlockData.lastBlock = uint(currentBlock); currentBlockData.lastRateUpdateBlock = uint(rateUpdateBlock); currentBlockData.totalBuyUnitsImbalance = int(prevImbalance) + recordedBuyAmount; } tokenImbalanceData[token][currentBlockIndex] = encodeTokenImbalanceData(currentBlockData); } function setGarbageToVolumeRecorder(ERC20 token) internal { for (uint i = 0; i < SLIDING_WINDOW_SIZE; i++) { tokenImbalanceData[token][i] = 0x1; } } function getImbalanceInRange(ERC20 token, uint startBlock, uint endBlock) internal view returns(int buyImbalance) { // check the imbalance in the sliding window require(startBlock <= endBlock); buyImbalance = 0; for (uint windowInd = 0; windowInd < SLIDING_WINDOW_SIZE; windowInd++) { TokenImbalanceData memory perBlockData = decodeTokenImbalanceData(tokenImbalanceData[token][windowInd]); if (perBlockData.lastBlock <= endBlock && perBlockData.lastBlock >= startBlock) { buyImbalance += int(perBlockData.lastBlockBuyUnitsImbalance); } } } function getImbalanceSinceRateUpdate(ERC20 token, uint rateUpdateBlock, uint currentBlock) internal view returns(int buyImbalance, int currentBlockImbalance) { buyImbalance = 0; currentBlockImbalance = 0; uint latestBlock = 0; int imbalanceInRange = 0; uint startBlock = rateUpdateBlock; uint endBlock = currentBlock; for (uint windowInd = 0; windowInd < SLIDING_WINDOW_SIZE; windowInd++) { TokenImbalanceData memory perBlockData = decodeTokenImbalanceData(tokenImbalanceData[token][windowInd]); if (perBlockData.lastBlock <= endBlock && perBlockData.lastBlock >= startBlock) { imbalanceInRange += perBlockData.lastBlockBuyUnitsImbalance; } if (perBlockData.lastRateUpdateBlock != rateUpdateBlock) continue; if (perBlockData.lastBlock < latestBlock) continue; latestBlock = perBlockData.lastBlock; buyImbalance = perBlockData.totalBuyUnitsImbalance; if (uint(perBlockData.lastBlock) == currentBlock) { currentBlockImbalance = perBlockData.lastBlockBuyUnitsImbalance; } } if (buyImbalance == 0) { buyImbalance = imbalanceInRange; } } function getImbalance(ERC20 token, uint rateUpdateBlock, uint currentBlock) internal view returns(int totalImbalance, int currentBlockImbalance) { int resolution = int(tokenControlInfo[token].minimalRecordResolution); (totalImbalance, currentBlockImbalance) = getImbalanceSinceRateUpdate( token, rateUpdateBlock, currentBlock); totalImbalance *= resolution; currentBlockImbalance *= resolution; } function getMaxPerBlockImbalance(ERC20 token) internal view returns(uint) { return tokenControlInfo[token].maxPerBlockImbalance; } function getMaxTotalImbalance(ERC20 token) internal view returns(uint) { return tokenControlInfo[token].maxTotalImbalance; } function encodeTokenImbalanceData(TokenImbalanceData data) internal pure returns(uint) { // check for overflows require(data.lastBlockBuyUnitsImbalance < int(POW_2_64 / 2)); require(data.lastBlockBuyUnitsImbalance > int(-1 * int(POW_2_64) / 2)); require(data.lastBlock < POW_2_64); require(data.totalBuyUnitsImbalance < int(POW_2_64 / 2)); require(data.totalBuyUnitsImbalance > int(-1 * int(POW_2_64) / 2)); require(data.lastRateUpdateBlock < POW_2_64); // do encoding uint result = uint(data.lastBlockBuyUnitsImbalance) & (POW_2_64 - 1); result |= data.lastBlock * POW_2_64; result |= (uint(data.totalBuyUnitsImbalance) & (POW_2_64 - 1)) * POW_2_64 * POW_2_64; result |= data.lastRateUpdateBlock * POW_2_64 * POW_2_64 * POW_2_64; return result; } function decodeTokenImbalanceData(uint input) internal pure returns(TokenImbalanceData) { TokenImbalanceData memory data; data.lastBlockBuyUnitsImbalance = int(int64(input & (POW_2_64 - 1))); data.lastBlock = uint(uint64((input / POW_2_64) & (POW_2_64 - 1))); data.totalBuyUnitsImbalance = int(int64((input / (POW_2_64 * POW_2_64)) & (POW_2_64 - 1))); data.lastRateUpdateBlock = uint(uint64((input / (POW_2_64 * POW_2_64 * POW_2_64)))); return data; } } // File: contracts/ConversionRates.sol contract ConversionRates is ConversionRatesInterface, VolumeImbalanceRecorder, Utils { // bps - basic rate steps. one step is 1 / 10000 of the rate. struct StepFunction { int[] x; // quantity for each step. Quantity of each step includes previous steps. int[] y; // rate change per quantity step in bps. } struct TokenData { bool listed; // was added to reserve bool enabled; // whether trade is enabled // position in the compact data uint compactDataArrayIndex; uint compactDataFieldIndex; // rate data. base and changes according to quantity and reserve balance. // generally speaking. Sell rate is 1 / buy rate i.e. the buy in the other direction. uint baseBuyRate; // in PRECISION units. see KyberConstants uint baseSellRate; // PRECISION units. without (sell / buy) spread it is 1 / baseBuyRate StepFunction buyRateQtyStepFunction; // in bps. higher quantity - bigger the rate. StepFunction sellRateQtyStepFunction;// in bps. higher the qua StepFunction buyRateImbalanceStepFunction; // in BPS. higher reserve imbalance - bigger the rate. StepFunction sellRateImbalanceStepFunction; } /* this is the data for tokenRatesCompactData but solidity compiler optimizer is sub-optimal, and cannot write this structure in a single storage write so we represent it as bytes32 and do the byte tricks ourselves. struct TokenRatesCompactData { bytes14 buy; // change buy rate of token from baseBuyRate in 10 bps bytes14 sell; // change sell rate of token from baseSellRate in 10 bps uint32 blockNumber; } */ uint public validRateDurationInBlocks = 10; // rates are valid for this amount of blocks ERC20[] internal listedTokens; mapping(address=>TokenData) internal tokenData; bytes32[] internal tokenRatesCompactData; uint public numTokensInCurrentCompactData = 0; address public reserveContract; uint constant internal NUM_TOKENS_IN_COMPACT_DATA = 14; uint constant internal BYTES_14_OFFSET = (2 ** (8 * NUM_TOKENS_IN_COMPACT_DATA)); uint constant internal MAX_STEPS_IN_FUNCTION = 10; int constant internal MAX_BPS_ADJUSTMENT = 10 ** 11; // 1B % int constant internal MIN_BPS_ADJUSTMENT = -100 * 100; // cannot go down by more than 100% function ConversionRates(address _admin) public VolumeImbalanceRecorder(_admin) { } // solhint-disable-line no-empty-blocks function addToken(ERC20 token) public onlyAdmin { require(!tokenData[token].listed); tokenData[token].listed = true; listedTokens.push(token); if (numTokensInCurrentCompactData == 0) { tokenRatesCompactData.length++; // add new structure } tokenData[token].compactDataArrayIndex = tokenRatesCompactData.length - 1; tokenData[token].compactDataFieldIndex = numTokensInCurrentCompactData; numTokensInCurrentCompactData = (numTokensInCurrentCompactData + 1) % NUM_TOKENS_IN_COMPACT_DATA; setGarbageToVolumeRecorder(token); setDecimals(token); } function setCompactData(bytes14[] buy, bytes14[] sell, uint blockNumber, uint[] indices) public onlyOperator { require(buy.length == sell.length); require(indices.length == buy.length); require(blockNumber <= 0xFFFFFFFF); uint bytes14Offset = BYTES_14_OFFSET; for (uint i = 0; i < indices.length; i++) { require(indices[i] < tokenRatesCompactData.length); uint data = uint(buy[i]) | uint(sell[i]) * bytes14Offset | (blockNumber * (bytes14Offset * bytes14Offset)); tokenRatesCompactData[indices[i]] = bytes32(data); } } function setBaseRate( ERC20[] tokens, uint[] baseBuy, uint[] baseSell, bytes14[] buy, bytes14[] sell, uint blockNumber, uint[] indices ) public onlyOperator { require(tokens.length == baseBuy.length); require(tokens.length == baseSell.length); require(sell.length == buy.length); require(sell.length == indices.length); for (uint ind = 0; ind < tokens.length; ind++) { require(tokenData[tokens[ind]].listed); tokenData[tokens[ind]].baseBuyRate = baseBuy[ind]; tokenData[tokens[ind]].baseSellRate = baseSell[ind]; } setCompactData(buy, sell, blockNumber, indices); } function setQtyStepFunction( ERC20 token, int[] xBuy, int[] yBuy, int[] xSell, int[] ySell ) public onlyOperator { require(xBuy.length == yBuy.length); require(xSell.length == ySell.length); require(xBuy.length <= MAX_STEPS_IN_FUNCTION); require(xSell.length <= MAX_STEPS_IN_FUNCTION); require(tokenData[token].listed); tokenData[token].buyRateQtyStepFunction = StepFunction(xBuy, yBuy); tokenData[token].sellRateQtyStepFunction = StepFunction(xSell, ySell); } function setImbalanceStepFunction( ERC20 token, int[] xBuy, int[] yBuy, int[] xSell, int[] ySell ) public onlyOperator { require(xBuy.length == yBuy.length); require(xSell.length == ySell.length); require(xBuy.length <= MAX_STEPS_IN_FUNCTION); require(xSell.length <= MAX_STEPS_IN_FUNCTION); require(tokenData[token].listed); tokenData[token].buyRateImbalanceStepFunction = StepFunction(xBuy, yBuy); tokenData[token].sellRateImbalanceStepFunction = StepFunction(xSell, ySell); } function setValidRateDurationInBlocks(uint duration) public onlyAdmin { validRateDurationInBlocks = duration; } function enableTokenTrade(ERC20 token) public onlyAdmin { require(tokenData[token].listed); require(tokenControlInfo[token].minimalRecordResolution != 0); tokenData[token].enabled = true; } function disableTokenTrade(ERC20 token) public onlyAlerter { require(tokenData[token].listed); tokenData[token].enabled = false; } function setReserveAddress(address reserve) public onlyAdmin { reserveContract = reserve; } function recordImbalance( ERC20 token, int buyAmount, uint rateUpdateBlock, uint currentBlock ) public { require(msg.sender == reserveContract); if (rateUpdateBlock == 0) rateUpdateBlock = getRateUpdateBlock(token); return addImbalance(token, buyAmount, rateUpdateBlock, currentBlock); } /* solhint-disable function-max-lines */ function getRate(ERC20 token, uint currentBlockNumber, bool buy, uint qty) public view returns(uint) { // check if trade is enabled if (!tokenData[token].enabled) return 0; if (tokenControlInfo[token].minimalRecordResolution == 0) return 0; // token control info not set // get rate update block bytes32 compactData = tokenRatesCompactData[tokenData[token].compactDataArrayIndex]; uint updateRateBlock = getLast4Bytes(compactData); if (currentBlockNumber >= updateRateBlock + validRateDurationInBlocks) return 0; // rate is expired // check imbalance int totalImbalance; int blockImbalance; (totalImbalance, blockImbalance) = getImbalance(token, updateRateBlock, currentBlockNumber); // calculate actual rate int imbalanceQty; int extraBps; int8 rateUpdate; uint rate; if (buy) { // start with base rate rate = tokenData[token].baseBuyRate; // add rate update rateUpdate = getRateByteFromCompactData(compactData, token, true); extraBps = int(rateUpdate) * 10; rate = addBps(rate, extraBps); // compute token qty qty = getTokenQty(token, rate, qty); imbalanceQty = int(qty); totalImbalance += imbalanceQty; // add qty overhead extraBps = executeStepFunction(tokenData[token].buyRateQtyStepFunction, int(qty)); rate = addBps(rate, extraBps); // add imbalance overhead extraBps = executeStepFunction(tokenData[token].buyRateImbalanceStepFunction, totalImbalance); rate = addBps(rate, extraBps); } else { // start with base rate rate = tokenData[token].baseSellRate; // add rate update rateUpdate = getRateByteFromCompactData(compactData, token, false); extraBps = int(rateUpdate) * 10; rate = addBps(rate, extraBps); // compute token qty imbalanceQty = -1 * int(qty); totalImbalance += imbalanceQty; // add qty overhead extraBps = executeStepFunction(tokenData[token].sellRateQtyStepFunction, int(qty)); rate = addBps(rate, extraBps); // add imbalance overhead extraBps = executeStepFunction(tokenData[token].sellRateImbalanceStepFunction, totalImbalance); rate = addBps(rate, extraBps); } if (abs(totalImbalance) >= getMaxTotalImbalance(token)) return 0; if (abs(blockImbalance + imbalanceQty) >= getMaxPerBlockImbalance(token)) return 0; return rate; } /* solhint-enable function-max-lines */ function getBasicRate(ERC20 token, bool buy) public view returns(uint) { if (buy) return tokenData[token].baseBuyRate; else return tokenData[token].baseSellRate; } function getCompactData(ERC20 token) public view returns(uint, uint, byte, byte) { require(tokenData[token].listed); uint arrayIndex = tokenData[token].compactDataArrayIndex; uint fieldOffset = tokenData[token].compactDataFieldIndex; return ( arrayIndex, fieldOffset, byte(getRateByteFromCompactData(tokenRatesCompactData[arrayIndex], token, true)), byte(getRateByteFromCompactData(tokenRatesCompactData[arrayIndex], token, false)) ); } function getTokenBasicData(ERC20 token) public view returns(bool, bool) { return (tokenData[token].listed, tokenData[token].enabled); } /* solhint-disable code-complexity */ function getStepFunctionData(ERC20 token, uint command, uint param) public view returns(int) { if (command == 0) return int(tokenData[token].buyRateQtyStepFunction.x.length); if (command == 1) return tokenData[token].buyRateQtyStepFunction.x[param]; if (command == 2) return int(tokenData[token].buyRateQtyStepFunction.y.length); if (command == 3) return tokenData[token].buyRateQtyStepFunction.y[param]; if (command == 4) return int(tokenData[token].sellRateQtyStepFunction.x.length); if (command == 5) return tokenData[token].sellRateQtyStepFunction.x[param]; if (command == 6) return int(tokenData[token].sellRateQtyStepFunction.y.length); if (command == 7) return tokenData[token].sellRateQtyStepFunction.y[param]; if (command == 8) return int(tokenData[token].buyRateImbalanceStepFunction.x.length); if (command == 9) return tokenData[token].buyRateImbalanceStepFunction.x[param]; if (command == 10) return int(tokenData[token].buyRateImbalanceStepFunction.y.length); if (command == 11) return tokenData[token].buyRateImbalanceStepFunction.y[param]; if (command == 12) return int(tokenData[token].sellRateImbalanceStepFunction.x.length); if (command == 13) return tokenData[token].sellRateImbalanceStepFunction.x[param]; if (command == 14) return int(tokenData[token].sellRateImbalanceStepFunction.y.length); if (command == 15) return tokenData[token].sellRateImbalanceStepFunction.y[param]; revert(); } /* solhint-enable code-complexity */ function getRateUpdateBlock(ERC20 token) public view returns(uint) { bytes32 compactData = tokenRatesCompactData[tokenData[token].compactDataArrayIndex]; return getLast4Bytes(compactData); } function getListedTokens() public view returns(ERC20[]) { return listedTokens; } function getTokenQty(ERC20 token, uint ethQty, uint rate) internal view returns(uint) { uint dstDecimals = getDecimals(token); uint srcDecimals = ETH_DECIMALS; return calcDstQty(ethQty, srcDecimals, dstDecimals, rate); } function getLast4Bytes(bytes32 b) internal pure returns(uint) { // cannot trust compiler with not turning bit operations into EXP opcode return uint(b) / (BYTES_14_OFFSET * BYTES_14_OFFSET); } function getRateByteFromCompactData(bytes32 data, ERC20 token, bool buy) internal view returns(int8) { uint fieldOffset = tokenData[token].compactDataFieldIndex; uint byteOffset; if (buy) byteOffset = 32 - NUM_TOKENS_IN_COMPACT_DATA + fieldOffset; else byteOffset = 4 + fieldOffset; return int8(data[byteOffset]); } function executeStepFunction(StepFunction f, int x) internal pure returns(int) { uint len = f.y.length; for (uint ind = 0; ind < len; ind++) { if (x <= f.x[ind]) return f.y[ind]; } return f.y[len-1]; } function addBps(uint rate, int bps) internal pure returns(uint) { require(rate <= MAX_RATE); require(bps >= MIN_BPS_ADJUSTMENT); require(bps <= MAX_BPS_ADJUSTMENT); uint maxBps = 100 * 100; return (rate * uint(int(maxBps) + bps)) / maxBps; } function abs(int x) internal pure returns(uint) { if (x < 0) return uint(-1 * x); else return uint(x); } } // File: contracts/ExpectedRateInterface.sol interface ExpectedRateInterface { function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view returns (uint expectedRate, uint slippageRate); } // File: contracts/FeeBurnerInterface.sol interface FeeBurnerInterface { function handleFees (uint tradeWeiAmount, address reserve, address wallet) public returns(bool); } // File: contracts/KyberReserveInterface.sol /// @title Kyber Reserve contract interface KyberReserveInterface { function trade( ERC20 srcToken, uint srcAmount, ERC20 destToken, address destAddress, uint conversionRate, bool validate ) public payable returns(bool); function getConversionRate(ERC20 src, ERC20 dest, uint srcQty, uint blockNumber) public view returns(uint); } // File: contracts/WhiteListInterface.sol contract WhiteListInterface { function getUserCapInWei(address user) external view returns (uint userCapWei); } // File: contracts/KyberNetwork.sol //////////////////////////////////////////////////////////////////////////////////////////////////////// /// @title Kyber Network main contract contract KyberNetwork is Withdrawable, Utils { uint public negligibleRateDiff = 10; // basic rate steps will be in 0.01% KyberReserveInterface[] public reserves; mapping(address=>bool) public isReserve; WhiteListInterface public whiteListContract; ExpectedRateInterface public expectedRateContract; FeeBurnerInterface public feeBurnerContract; uint public maxGasPrice = 50 * 1000 * 1000 * 1000; // 50 gwei bool public enabled = false; // network is enabled mapping(bytes32=>uint) public info; // this is only a UI field for external app. mapping(address=>mapping(bytes32=>bool)) public perReserveListedPairs; function KyberNetwork(address _admin) public { require(_admin != address(0)); admin = _admin; } event EtherReceival(address indexed sender, uint amount); /* solhint-disable no-complex-fallback */ function() public payable { require(isReserve[msg.sender]); EtherReceival(msg.sender, msg.value); } /* solhint-enable no-complex-fallback */ event ExecuteTrade(address indexed sender, ERC20 src, ERC20 dest, uint actualSrcAmount, uint actualDestAmount); /// @notice use token address ETH_TOKEN_ADDRESS for ether /// @dev makes a trade between src and dest token and send dest token to destAddress /// @param src Src token /// @param srcAmount amount of src tokens /// @param dest Destination token /// @param destAddress Address to send tokens to /// @param maxDestAmount A limit on the amount of dest tokens /// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled. /// @param walletId is the wallet ID to send part of the fees /// @return amount of actual dest tokens function trade( ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId ) public payable returns(uint) { require(enabled); uint userSrcBalanceBefore; uint userSrcBalanceAfter; uint userDestBalanceBefore; uint userDestBalanceAfter; userSrcBalanceBefore = getBalance(src, msg.sender); if (src == ETH_TOKEN_ADDRESS) userSrcBalanceBefore += msg.value; userDestBalanceBefore = getBalance(dest, destAddress); uint actualDestAmount = doTrade(src, srcAmount, dest, destAddress, maxDestAmount, minConversionRate, walletId ); require(actualDestAmount > 0); userSrcBalanceAfter = getBalance(src, msg.sender); userDestBalanceAfter = getBalance(dest, destAddress); require(userSrcBalanceAfter <= userSrcBalanceBefore); require(userDestBalanceAfter >= userDestBalanceBefore); require((userDestBalanceAfter - userDestBalanceBefore) >= calcDstQty((userSrcBalanceBefore - userSrcBalanceAfter), getDecimals(src), getDecimals(dest), minConversionRate)); return actualDestAmount; } event AddReserveToNetwork(KyberReserveInterface reserve, bool add); /// @notice can be called only by admin /// @dev add or deletes a reserve to/from the network. /// @param reserve The reserve address. /// @param add If true, the add reserve. Otherwise delete reserve. function addReserve(KyberReserveInterface reserve, bool add) public onlyAdmin { if (add) { require(!isReserve[reserve]); reserves.push(reserve); isReserve[reserve] = true; AddReserveToNetwork(reserve, true); } else { isReserve[reserve] = false; // will have trouble if more than 50k reserves... for (uint i = 0; i < reserves.length; i++) { if (reserves[i] == reserve) { reserves[i] = reserves[reserves.length - 1]; reserves.length--; AddReserveToNetwork(reserve, false); break; } } } } event ListReservePairs(address reserve, ERC20 src, ERC20 dest, bool add); /// @notice can be called only by admin /// @dev allow or prevent a specific reserve to trade a pair of tokens /// @param reserve The reserve address. /// @param src Src token /// @param dest Destination token /// @param add If true then enable trade, otherwise delist pair. function listPairForReserve(address reserve, ERC20 src, ERC20 dest, bool add) public onlyAdmin { (perReserveListedPairs[reserve])[keccak256(src, dest)] = add; if (src != ETH_TOKEN_ADDRESS) { if (add) { src.approve(reserve, 2**255); // approve infinity } else { src.approve(reserve, 0); } } setDecimals(src); setDecimals(dest); ListReservePairs(reserve, src, dest, add); } function setParams( WhiteListInterface _whiteList, ExpectedRateInterface _expectedRate, FeeBurnerInterface _feeBurner, uint _maxGasPrice, uint _negligibleRateDiff ) public onlyAdmin { require(_whiteList != address(0)); require(_feeBurner != address(0)); require(_expectedRate != address(0)); require(_negligibleRateDiff <= 100 * 100); // at most 100% whiteListContract = _whiteList; expectedRateContract = _expectedRate; feeBurnerContract = _feeBurner; maxGasPrice = _maxGasPrice; negligibleRateDiff = _negligibleRateDiff; } function setEnable(bool _enable) public onlyAdmin { if (_enable) { require(whiteListContract != address(0)); require(feeBurnerContract != address(0)); require(expectedRateContract != address(0)); } enabled = _enable; } function setInfo(bytes32 field, uint value) public onlyOperator { info[field] = value; } /// @dev returns number of reserves /// @return number of reserves function getNumReserves() public view returns(uint) { return reserves.length; } /// @notice should be called off chain with as much gas as needed /// @dev get an array of all reserves /// @return An array of all reserves function getReserves() public view returns(KyberReserveInterface[]) { return reserves; } /// @dev get the balance of a user. /// @param token The token type /// @return The balance function getBalance(ERC20 token, address user) public view returns(uint) { if (token == ETH_TOKEN_ADDRESS) return user.balance; else return token.balanceOf(user); } /// @notice use token address ETH_TOKEN_ADDRESS for ether /// @dev best conversion rate for a pair of tokens, if number of reserves have small differences. randomize /// @param src Src token /// @param dest Destination token /* solhint-disable code-complexity */ function findBestRate(ERC20 src, ERC20 dest, uint srcQty) public view returns(uint, uint) { uint bestRate = 0; uint bestReserve = 0; uint numRelevantReserves = 0; uint numReserves = reserves.length; uint[] memory rates = new uint[](numReserves); uint[] memory reserveCandidates = new uint[](numReserves); for (uint i = 0; i < numReserves; i++) { //list all reserves that have this token. if (!(perReserveListedPairs[reserves[i]])[keccak256(src, dest)]) continue; rates[i] = reserves[i].getConversionRate(src, dest, srcQty, block.number); if (rates[i] > bestRate) { //best rate is highest rate bestRate = rates[i]; } } if (bestRate > 0) { uint random = 0; uint smallestRelevantRate = (bestRate * 10000) / (10000 + negligibleRateDiff); for (i = 0; i < numReserves; i++) { if (rates[i] >= smallestRelevantRate) { reserveCandidates[numRelevantReserves++] = i; } } if (numRelevantReserves > 1) { //when encountering small rate diff from bestRate. draw from relevant reserves random = uint(block.blockhash(block.number-1)) % numRelevantReserves; } bestReserve = reserveCandidates[random]; bestRate = rates[bestReserve]; } return (bestReserve, bestRate); } /* solhint-enable code-complexity */ function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view returns (uint expectedRate, uint slippageRate) { require(expectedRateContract != address(0)); return expectedRateContract.getExpectedRate(src, dest, srcQty); } function getUserCapInWei(address user) public view returns(uint) { return whiteListContract.getUserCapInWei(user); } function doTrade( ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId ) internal returns(uint) { require(tx.gasprice <= maxGasPrice); require(validateTradeInput(src, srcAmount, destAddress)); uint reserveInd; uint rate; (reserveInd, rate) = findBestRate(src, dest, srcAmount); KyberReserveInterface theReserve = reserves[reserveInd]; require(rate > 0); require(rate < MAX_RATE); require(rate >= minConversionRate); uint actualSrcAmount = srcAmount; uint actualDestAmount = calcDestAmount(src, dest, actualSrcAmount, rate); if (actualDestAmount > maxDestAmount) { actualDestAmount = maxDestAmount; actualSrcAmount = calcSrcAmount(src, dest, actualDestAmount, rate); require(actualSrcAmount <= srcAmount); } // do the trade // verify trade size is smaller than user cap uint ethAmount; if (src == ETH_TOKEN_ADDRESS) { ethAmount = actualSrcAmount; } else { ethAmount = actualDestAmount; } require(ethAmount <= getUserCapInWei(msg.sender)); require(doReserveTrade( src, actualSrcAmount, dest, destAddress, actualDestAmount, theReserve, rate, true)); if ((actualSrcAmount < srcAmount) && (src == ETH_TOKEN_ADDRESS)) { msg.sender.transfer(srcAmount - actualSrcAmount); } require(feeBurnerContract.handleFees(ethAmount, theReserve, walletId)); ExecuteTrade(msg.sender, src, dest, actualSrcAmount, actualDestAmount); return actualDestAmount; } /// @notice use token address ETH_TOKEN_ADDRESS for ether /// @dev do one trade with a reserve /// @param src Src token /// @param amount amount of src tokens /// @param dest Destination token /// @param destAddress Address to send tokens to /// @param reserve Reserve to use /// @param validate If true, additional validations are applicable /// @return true if trade is successful function doReserveTrade( ERC20 src, uint amount, ERC20 dest, address destAddress, uint expectedDestAmount, KyberReserveInterface reserve, uint conversionRate, bool validate ) internal returns(bool) { uint callValue = 0; if (src == ETH_TOKEN_ADDRESS) { callValue = amount; } else { // take src tokens to this contract src.transferFrom(msg.sender, this, amount); } // reserve sends tokens/eth to network. network sends it to destination require(reserve.trade.value(callValue)(src, amount, dest, this, conversionRate, validate)); if (dest == ETH_TOKEN_ADDRESS) { destAddress.transfer(expectedDestAmount); } else { require(dest.transfer(destAddress, expectedDestAmount)); } return true; } function calcDestAmount(ERC20 src, ERC20 dest, uint srcAmount, uint rate) internal view returns(uint) { return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate); } function calcSrcAmount(ERC20 src, ERC20 dest, uint destAmount, uint rate) internal view returns(uint) { return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate); } /// @notice use token address ETH_TOKEN_ADDRESS for ether /// @dev checks that user sent ether/tokens to contract before trade /// @param src Src token /// @param srcAmount amount of src tokens /// @return true if input is valid function validateTradeInput(ERC20 src, uint srcAmount, address destAddress) internal view returns(bool) { if ((srcAmount >= MAX_QTY) || (srcAmount == 0) || (destAddress == 0)) return false; if (src == ETH_TOKEN_ADDRESS) { if (msg.value != srcAmount) return false; } else { if ((msg.value != 0) || (src.allowance(msg.sender, this) < srcAmount)) return false; } return true; } } // File: contracts/SanityRatesInterface.sol interface SanityRatesInterface { function getSanityRate(ERC20 src, ERC20 dest) public view returns(uint); } // File: contracts/KyberReserve.sol /// @title Kyber Reserve contract contract KyberReserve is KyberReserveInterface, Withdrawable, Utils { address public kyberNetwork; bool public tradeEnabled; ConversionRatesInterface public conversionRatesContract; SanityRatesInterface public sanityRatesContract; mapping(bytes32=>bool) public approvedWithdrawAddresses; // sha3(token,address)=>bool function KyberReserve(address _kyberNetwork, ConversionRatesInterface _ratesContract, address _admin) public { require(_admin != address(0)); require(_ratesContract != address(0)); require(_kyberNetwork != address(0)); kyberNetwork = _kyberNetwork; conversionRatesContract = _ratesContract; admin = _admin; tradeEnabled = true; } event DepositToken(ERC20 token, uint amount); function() public payable { DepositToken(ETH_TOKEN_ADDRESS, msg.value); } event TradeExecute( address indexed origin, address src, uint srcAmount, address destToken, uint destAmount, address destAddress ); function trade( ERC20 srcToken, uint srcAmount, ERC20 destToken, address destAddress, uint conversionRate, bool validate ) public payable returns(bool) { require(tradeEnabled); require(msg.sender == kyberNetwork); require(doTrade(srcToken, srcAmount, destToken, destAddress, conversionRate, validate)); return true; } event TradeEnabled(bool enable); function enableTrade() public onlyAdmin returns(bool) { tradeEnabled = true; TradeEnabled(true); return true; } function disableTrade() public onlyAlerter returns(bool) { tradeEnabled = false; TradeEnabled(false); return true; } event WithdrawAddressApproved(ERC20 token, address addr, bool approve); function approveWithdrawAddress(ERC20 token, address addr, bool approve) public onlyAdmin { approvedWithdrawAddresses[keccak256(token, addr)] = approve; WithdrawAddressApproved(token, addr, approve); setDecimals(token); } event WithdrawFunds(ERC20 token, uint amount, address destination); function withdraw(ERC20 token, uint amount, address destination) public onlyOperator returns(bool) { require(approvedWithdrawAddresses[keccak256(token, destination)]); if (token == ETH_TOKEN_ADDRESS) { destination.transfer(amount); } else { require(token.transfer(destination, amount)); } WithdrawFunds(token, amount, destination); return true; } event SetContractAddresses(address network, address rate, address sanity); function setContracts(address _kyberNetwork, ConversionRatesInterface _conversionRates, SanityRatesInterface _sanityRates) public onlyAdmin { require(_kyberNetwork != address(0)); require(_conversionRates != address(0)); kyberNetwork = _kyberNetwork; conversionRatesContract = _conversionRates; sanityRatesContract = _sanityRates; SetContractAddresses(kyberNetwork, conversionRatesContract, sanityRatesContract); } //////////////////////////////////////////////////////////////////////////// /// status functions /////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// function getBalance(ERC20 token) public view returns(uint) { if (token == ETH_TOKEN_ADDRESS) return this.balance; else return token.balanceOf(this); } function getDestQty(ERC20 src, ERC20 dest, uint srcQty, uint rate) public view returns(uint) { uint dstDecimals = getDecimals(dest); uint srcDecimals = getDecimals(src); return calcDstQty(srcQty, srcDecimals, dstDecimals, rate); } function getSrcQty(ERC20 src, ERC20 dest, uint dstQty, uint rate) public view returns(uint) { uint dstDecimals = getDecimals(dest); uint srcDecimals = getDecimals(src); return calcSrcQty(dstQty, srcDecimals, dstDecimals, rate); } function getConversionRate(ERC20 src, ERC20 dest, uint srcQty, uint blockNumber) public view returns(uint) { ERC20 token; bool buy; if (!tradeEnabled) return 0; if (ETH_TOKEN_ADDRESS == src) { buy = true; token = dest; } else if (ETH_TOKEN_ADDRESS == dest) { buy = false; token = src; } else { return 0; // pair is not listed } uint rate = conversionRatesContract.getRate(token, blockNumber, buy, srcQty); uint destQty = getDestQty(src, dest, srcQty, rate); if (getBalance(dest) < destQty) return 0; if (sanityRatesContract != address(0)) { uint sanityRate = sanityRatesContract.getSanityRate(src, dest); if (rate > sanityRate) return 0; } return rate; } /// @dev do a trade /// @param srcToken Src token /// @param srcAmount Amount of src token /// @param destToken Destination token /// @param destAddress Destination address to send tokens to /// @param validate If true, additional validations are applicable /// @return true iff trade is successful function doTrade( ERC20 srcToken, uint srcAmount, ERC20 destToken, address destAddress, uint conversionRate, bool validate ) internal returns(bool) { // can skip validation if done at kyber network level if (validate) { require(conversionRate > 0); if (srcToken == ETH_TOKEN_ADDRESS) require(msg.value == srcAmount); else require(msg.value == 0); } uint destAmount = getDestQty(srcToken, destToken, srcAmount, conversionRate); // sanity check require(destAmount > 0); // add to imbalance ERC20 token; int buy; if (srcToken == ETH_TOKEN_ADDRESS) { buy = int(destAmount); token = destToken; } else { buy = -1 * int(srcAmount); token = srcToken; } conversionRatesContract.recordImbalance( token, buy, 0, block.number ); // collect src tokens if (srcToken != ETH_TOKEN_ADDRESS) { require(srcToken.transferFrom(msg.sender, this, srcAmount)); } // send dest tokens if (destToken == ETH_TOKEN_ADDRESS) { destAddress.transfer(destAmount); } else { require(destToken.transfer(destAddress, destAmount)); } TradeExecute(msg.sender, srcToken, srcAmount, destToken, destAmount, destAddress); return true; } } // File: contracts/mockContracts/Wrapper.sol contract Wrapper is Utils { function getBalances(address reserve, ERC20[] tokens) public view returns(uint[],uint) { uint[] memory result = new uint[](tokens.length); for (uint i = 0; i < tokens.length; i++) { uint balance = 0; if (tokens[i] == ETH_TOKEN_ADDRESS) { balance = reserve.balance; } else { balance = tokens[i].balanceOf(reserve); } result[i] = balance; } return (result,block.number); } function getByteFromBytes14(bytes14 x, uint byteInd) public pure returns(byte) { require(byteInd <= 13); return x[byteInd]; } function getInt8FromByte(bytes14 x, uint byteInd) public pure returns(int8) { require(byteInd <= 13); return int8(x[byteInd]); } function getCompactData(ConversionRates ratesContract, ERC20 token) internal view returns(int8,int8,uint) { uint bulkIndex; uint index; byte buy; byte sell; uint updateBlock; (bulkIndex, index, buy, sell) = ratesContract.getCompactData(token); updateBlock = ratesContract.getRateUpdateBlock(token); return (int8(buy), int8(sell), updateBlock); } function getTokenRates(ConversionRates ratesContract, ERC20[] tokenList) public view returns(uint[], uint[], int8[], int8[], uint[],uint) { uint[] memory buyBases = new uint[](tokenList.length); uint[] memory sellBases = new uint[](tokenList.length); int8[] memory compactBuy = new int8[](tokenList.length); int8[] memory compactSell = new int8[](tokenList.length); uint[] memory updateBlock = new uint[](tokenList.length); for (uint i = 0; i < tokenList.length; i++) { buyBases[i] = ratesContract.getBasicRate(tokenList[i], true); sellBases[i] = ratesContract.getBasicRate(tokenList[i], false); (compactBuy[i], compactSell[i], updateBlock[i]) = getCompactData(ratesContract, tokenList[i]); } return (buyBases, sellBases, compactBuy, compactSell, updateBlock,block.number); } function getTokenIndicies(ConversionRates ratesContract, ERC20[] tokenList) public view returns(uint[], uint[],uint) { uint[] memory bulkIndices = new uint[](tokenList.length); uint[] memory tokenIndexInBulk = new uint[](tokenList.length); for (uint i = 0; i < tokenList.length; i++) { uint bulkIndex; uint index; byte buy; byte sell; (bulkIndex, index, buy, sell) = ratesContract.getCompactData(tokenList[i]); bulkIndices[i] = bulkIndex; tokenIndexInBulk[i] = index; } return (bulkIndices,tokenIndexInBulk,block.number); } function getExpectedRates( KyberNetwork network, ERC20[] srcs, ERC20[] dests, uint[] qty) public view returns(uint[], uint[],uint) { require( srcs.length == dests.length ); require( srcs.length == qty.length ); uint[] memory rates = new uint[](srcs.length); uint[] memory slippage = new uint[](srcs.length); for ( uint i = 0; i < srcs.length; i++ ) { (rates[i],slippage[i]) = network.getExpectedRate(srcs[i],dests[i],qty[i]); } return (rates, slippage,block.number); } function getReserveRate(KyberReserve reserve, ERC20[] srcs, ERC20[] dests) public view returns(uint[], uint[],uint) { require( srcs.length == dests.length ); uint[] memory rates = new uint[](srcs.length); uint[] memory sanityRate = new uint[](srcs.length); for(uint i = 0 ; i < srcs.length ; i++) { if(reserve.sanityRatesContract() != address(0x0)){ sanityRate[i] = reserve.sanityRatesContract().getSanityRate(srcs[i], dests[i]); } rates[i] = reserve.getConversionRate(srcs[i], dests[i], 0, block.number); } return (rates,sanityRate,block.number); } }
@notice use token address ETH_TOKEN_ADDRESS for ether @dev do one trade with a reserve @param src Src token @param amount amount of src tokens @param dest Destination token @param destAddress Address to send tokens to @param reserve Reserve to use @param validate If true, additional validations are applicable @return true if trade is successful take src tokens to this contract
function doReserveTrade( ERC20 src, uint amount, ERC20 dest, address destAddress, uint expectedDestAmount, KyberReserveInterface reserve, uint conversionRate, bool validate ) internal returns(bool) { uint callValue = 0; if (src == ETH_TOKEN_ADDRESS) { callValue = amount; src.transferFrom(msg.sender, this, amount); } if (dest == ETH_TOKEN_ADDRESS) { destAddress.transfer(expectedDestAmount); require(dest.transfer(destAddress, expectedDestAmount)); } return true; }
509,360
[ 1, 1202, 1147, 1758, 512, 2455, 67, 8412, 67, 15140, 364, 225, 2437, 225, 741, 1245, 18542, 598, 279, 20501, 225, 1705, 26632, 1147, 225, 3844, 3844, 434, 1705, 2430, 225, 1570, 282, 10691, 1147, 225, 1570, 1887, 5267, 358, 1366, 2430, 358, 225, 20501, 1124, 6527, 358, 999, 225, 1954, 971, 638, 16, 3312, 20808, 854, 12008, 327, 638, 309, 18542, 353, 6873, 4862, 1705, 2430, 358, 333, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 741, 607, 6527, 22583, 12, 203, 3639, 4232, 39, 3462, 1705, 16, 203, 3639, 2254, 3844, 16, 203, 3639, 4232, 39, 3462, 1570, 16, 203, 3639, 1758, 1570, 1887, 16, 203, 3639, 2254, 2665, 9378, 6275, 16, 203, 3639, 1475, 93, 744, 607, 6527, 1358, 20501, 16, 203, 3639, 2254, 4105, 4727, 16, 203, 3639, 1426, 1954, 203, 565, 262, 203, 3639, 2713, 203, 3639, 1135, 12, 6430, 13, 203, 565, 288, 203, 3639, 2254, 745, 620, 273, 374, 31, 203, 203, 3639, 309, 261, 4816, 422, 512, 2455, 67, 8412, 67, 15140, 13, 288, 203, 5411, 745, 620, 273, 3844, 31, 203, 5411, 1705, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 333, 16, 3844, 1769, 203, 3639, 289, 203, 203, 203, 3639, 309, 261, 10488, 422, 512, 2455, 67, 8412, 67, 15140, 13, 288, 203, 5411, 1570, 1887, 18, 13866, 12, 3825, 9378, 6275, 1769, 203, 5411, 2583, 12, 10488, 18, 13866, 12, 10488, 1887, 16, 2665, 9378, 6275, 10019, 203, 3639, 289, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x28462739c3EB65a571Bf92689e8257c806bD275D/sources/contracts/A0K1Passport.sol
* @dev See {IERC1155Receiver-onERC1155Received}./
function onERC1155Received( address, address from, uint256 id, uint256 value, bytes calldata data ) external override nonReentrant returns(bytes4) { _onERC1155Received(from, id, value, data); return this.onERC1155Received.selector; }
2,965,404
[ 1, 9704, 288, 45, 654, 39, 2499, 2539, 12952, 17, 265, 654, 39, 2499, 2539, 8872, 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 ]
[ 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, 603, 654, 39, 2499, 2539, 8872, 12, 203, 3639, 1758, 16, 203, 3639, 1758, 628, 16, 203, 3639, 2254, 5034, 612, 16, 203, 3639, 2254, 5034, 460, 16, 203, 3639, 1731, 745, 892, 501, 203, 565, 262, 3903, 3849, 1661, 426, 8230, 970, 1135, 12, 3890, 24, 13, 288, 203, 203, 3639, 389, 265, 654, 39, 2499, 2539, 8872, 12, 2080, 16, 612, 16, 460, 16, 501, 1769, 203, 3639, 327, 333, 18, 265, 654, 39, 2499, 2539, 8872, 18, 9663, 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 ]
pragma solidity ^0.6.0; /** * @title Primitive's Exchange Contract * @notice A Decentralized Exchange to manage the buying and selling of Prime Option tokens. * @author Primitive */ /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal virtual { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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; } } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ abstract contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public virtual returns (bytes4); } contract ERC721Holder is IERC721Receiver { function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { bool private _notEntered; constructor () internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } /** * @title Primitive's Instruments * @author Primitive Finance */ library Instruments { struct Actors { uint[] mintedTokens; uint[] deactivatedTokens; } /** * @dev A Prime has these properties. * @param ace `msg.sender` of the createPrime function. * @param xis Quantity of collateral asset token. * @param yak Address of collateral asset token. * @param zed Purchase price of collateral, denominated in quantity of token z. * @param wax Address of purchase price asset token. * @param pow UNIX timestamp of valid time period. * @param gem Address of payment receiver of token z. */ struct Primes { address ace; uint256 xis; address yak; uint256 zed; address wax; uint256 pow; address gem; } /** * @dev A Prime has these properties. * @param chain Keccak256 hash of collateral * asset address, strike asset address, and expiration date. */ struct Chain { bytes4 chain; } } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } abstract contract IPool { function withdrawExercisedEth(address payable _receiver, uint256 _amount) external virtual returns (bool); function clearLiability(uint256 liability, address strike, uint256 short) external virtual returns (bool); function exercise(uint256 _long, uint256 _short, address _strike) external payable virtual returns (bool); function mintPrimeFromPool( uint256 _long, uint256 _short, address _strike, uint256 _expiration, address _primeReceiver ) external payable virtual returns (bool); function getAvailableAssets() public virtual returns (uint256); } abstract contract IPrime { function safeTransferFrom(address from, address to, uint256 tokenId) public virtual; function createPrime(uint256 _xis, address _yak, uint256 _zed, address _wax, uint256 _pow, address _gem) external virtual returns (bool); function exercise(uint256 _tokenId) external virtual returns (bool); function close(uint256 _collateralId, uint256 _burnId) external virtual returns (bool); function withdraw(uint256 _amount, address _asset) public virtual returns (bool); function getPrime(uint256 _tokenId) external view virtual returns( address ace, uint256 xis, address yak, uint256 zed, address wax, uint256 pow, address gem, bytes4 chain ); function _primeCompare(uint256 _collateralId, uint256 _burnId) public view virtual returns (bool burn); function getChain(uint256 _tokenId) external view virtual returns (bytes4 chain); function isTokenExpired(uint256 _tokenId) public view virtual returns(bool); } contract Exchange is ERC721Holder, ReentrancyGuard, Ownable, Pausable { using SafeMath for uint256; address public _owner; address private _primeAddress; address public _poolAddress; IPool public _poolInterface; uint256 public _feePool; uint256 constant _feeDenomination = 333; /* 0.30% = 0.003 = 1 / 333 */ uint256 constant _poolPremiumDenomination = 5; /* 20% = 0.2 = 1 / 5 - FIX */ event SellOrder(address _seller, uint256 _askPrice, uint256 _tokenId, bool _filled); event BuyOrder(address _buyer, uint256 _bidPrice, uint256 _tokenId, bool _filled); event BuyOrderUnfilled(address _buyer, uint256 _bidPrice, uint256 _nonce); event FillUnfilledBuyOrder(address _seller, uint256 _tokenId); event FillOrder(address _seller, address _buyer, uint256 _filledPrice, uint256 _tokenId); event FillOrderFromPool(address _buyer, uint256 _bidPrice, uint256 _amount); event CloseOrder(address _user, uint256 _tokenId, bool _buyOrder); event CloseUnfilledBuyOrder(address _user, bytes4 _chain, uint256 _buyOrderNonce); struct SellOrders { address payable seller; uint256 askPrice; uint256 tokenId; } struct BuyOrders { address payable buyer; uint256 bidPrice; uint256 tokenId; } struct BuyOrdersUnfilled { address payable buyer; uint256 bidPrice; bytes4 chain; uint256 xis; address yak; uint256 zed; address wax; uint256 pow; } /* MAPS TOKENIDS WITH SELL ORDER DETAILS */ mapping(uint256 => SellOrders) public _sellOrders; /* MAPS TOKENIDS WITH BUY ORDER DETAILS */ mapping(uint256 => BuyOrders) public _buyOrders; /* MAPS HASH OF PROPERTIES TO AN ORDER NONCE THAT RETURNS THE UNFILLED ORDER DETAILS */ mapping(bytes4 => mapping(uint256 => BuyOrdersUnfilled)) public _buyOrdersUnfilled; /* MAX HEIGHT OF UNFILLED ORDERS */ mapping(bytes4 => uint256) public _unfilledNonce; /* MAPS USERS TO ETHER BALANCES IN EXCHANGE */ mapping(address => uint256) public _etherBalance; /* Maps a user to added pool funds */ mapping(address => uint256) private _feePoolContribution; /* INTIALIZES TOKEN 0 -> ALL ORDERS ARE RESET TO THIS DEFAULT VALUE WHEN FILLED/CLOSED */ constructor(address primeAddress) public { _primeAddress = primeAddress; _owner = msg.sender; _feePool = 0; _buyOrders[0] = BuyOrders( address(0), 0, 0 ); _sellOrders[0] = SellOrders( address(0), 0, 0 ); _buyOrdersUnfilled[0][0] = BuyOrdersUnfilled( address(0), 0, 0, 0, address(0), 0, address(0), 0 ); } receive() external payable {} /* SET POOL ADDRESS */ function setPoolAddress(address poolAddress) external onlyOwner { _poolAddress = poolAddress; _poolInterface = IPool(poolAddress); } /* KILL SWITCH */ function killSwitch() external onlyOwner { _pause(); } /* REVIVE */ function unpause() external onlyOwner { _unpause(); } /* Prime Address */ function getPrimeAddress() public view returns (address) { return _primeAddress; } /** * @dev users withdraw ether rather than have it directly sent to them * @param _amount value of ether to withdraw */ function withdrawEther(uint256 _amount) external nonReentrant { require(_etherBalance[msg.sender] >= _amount, 'Bal < amount'); (bool success, ) = msg.sender.call.value(_amount)(""); require(success, "Transfer failed."); } /* CORE MUTATIVE FUNCTIONS */ /** * @dev List a valid Prime for sale * @param _tokenId the Prime's nonce when minted * @param _askPrice value in wei desired as payment * @return bool Whether or not the tx succeeded */ function sellOrder( uint256 _tokenId, uint256 _askPrice ) external whenNotPaused returns (bool) { IPrime _prime = IPrime(_primeAddress); /* CHECKS */ require(_tokenId > 0, 'Invalid Token'); require(_askPrice > 0, 'Ask < 0'); _prime.isTokenExpired(_tokenId); require(!isListed(_tokenId), 'Token listed already'); /* EFFECTS */ /* Gets a buy order request ID if _tokenId has matching properties and can fill order*/ uint256 fillable = checkUnfilledBuyOrders(_tokenId, _askPrice); /* INTERACTIONS */ /* If a buy order request matches a token's properties, and the bid price fulfills the order, fill it */ if(fillable > 0) { /* Unique hash of the Prime's key properties: Asset addresses & expiration date */ bytes4 chain = _prime.getChain(_tokenId); /* Buy order request of hash 'chain' at order request nonce */ BuyOrdersUnfilled memory _buyUnfilled = _buyOrdersUnfilled[chain][fillable]; return fillUnfilledBuyOrder( _tokenId, _buyUnfilled.bidPrice, _askPrice, _buyUnfilled.buyer, msg.sender, fillable, chain ); } /* * If a buy order for the _tokenId is available, fill it, * else, list it for sale and transfer it from user to the dex */ if(fillable == 0) { BuyOrders memory _buy = _buyOrders[_tokenId]; if(_buy.bidPrice >= _askPrice) { return fillOrder( false, _tokenId, _buy.bidPrice, _askPrice, _buy.buyer, msg.sender ); } else { /* Add sell order to state */ _sellOrders[_tokenId] = SellOrders( msg.sender, _askPrice, _tokenId ); /* Take prime from sender */ _prime.safeTransferFrom(msg.sender, address(this), _tokenId); emit SellOrder(msg.sender, _askPrice, _tokenId, false); return true; } } } /** * @dev offer a bid for a specific token * @param _tokenId nonce of token when minted * @param _bidPrice value offered to purchase Prime * @return bool whether the tx succeeds */ function buyOrder( uint256 _tokenId, uint256 _bidPrice ) public payable nonReentrant whenNotPaused returns (bool) { /* CHECKS */ require(_tokenId > 0, 'Invalid Token'); require(_bidPrice > 0, 'Bid < 0'); uint256 _fee = _bidPrice.div(_feeDenomination); uint256 _totalCost = _bidPrice.add(_fee); require(msg.value >= _totalCost, 'Val < cost'); /* Transfer remaining bid to Buyer */ if(msg.value > _totalCost) { (bool success, ) = msg.sender.call.value(msg.value.sub(_totalCost))(""); require(success, 'Transfer fail.'); } /* EFFECTS */ SellOrders memory _sell = _sellOrders[_tokenId]; /* INTERACTIONS */ /* * If the token is listed for sale, fill it * Else, submit an offer to buy a specific token */ if(isListed(_tokenId) && _bidPrice >= _sell.askPrice ) { return fillOrder( true, _tokenId, _bidPrice, _sell.askPrice, msg.sender, _sell.seller ); } else { _buyOrders[_tokenId] = BuyOrders( msg.sender, _bidPrice, _tokenId ); emit BuyOrder(msg.sender, _bidPrice, _tokenId, false); return true; } } /** * @dev fill an order * @param _buyOrder whether this order is a buy order * @param _tokenId nonce of Prime when minted * @param _bidPrice value offered to buy Prime * @param _askPrice value required to buy Prime * @param _buyer address of buying party * @param _seller address of selling party (can be DEX or user) * @return bool whether the tx succeeds */ function fillOrder( bool _buyOrder, uint256 _tokenId, uint256 _bidPrice, uint256 _askPrice, address payable _buyer, address payable _seller ) private returns (bool) { /* CHECKS */ /* EFFECTS */ /* Clears order from state */ if(_buyOrder) { emit BuyOrder(_buyer, _bidPrice, _tokenId, true); clearSellOrder(_tokenId); } else { emit SellOrder(_seller, _askPrice, _tokenId, true); clearBuyOrder(_tokenId); } /* Update ether balance state of buyer, seller, and reward pool */ _etherBalance[_seller] = _etherBalance[_seller].add(_askPrice); uint256 _fee = _bidPrice.div(_feeDenomination); _feePoolContribution[_seller] = _feePoolContribution[_seller].add(_fee); _feePool = _feePool.add(_fee); /* INTERACTIONS */ /* * IF ITS BUY ORDER - PRIME IS OWNED BY EXCHANGE * IF ITS SELL ORDER - PRIME IS OWNED BY SELLER */ IPrime _prime = IPrime(_primeAddress); if(_buyOrder) { _prime.safeTransferFrom(address(this), _buyer, _tokenId); } else { _prime.safeTransferFrom(_seller, _buyer, _tokenId); } emit FillOrder(_seller, _buyer, _askPrice, _tokenId); return true; } /** * @dev request to buy a Prime with params * @param _bidPrice value offered to buy Prime * @param _xis amount of collateral (underlying) asset * @param _yak address of collateral ERC-20 token * @param _zed amount of payment (strike) asset * @param _wax address of strike ERC-20 token * @param _pow timestamp of expiration * @return bool whether the tx suceeds */ function buyOrderUnfilled( uint256 _bidPrice, /* bytes4 _chain, */ uint256 _xis, address _yak, uint256 _zed, address _wax, uint256 _pow ) external payable nonReentrant whenNotPaused returns (bool) { /* CHECKS */ require(_bidPrice > 0, 'Bid < 0'); /* EFFECTS */ /* If the pool can fill the order, mint the Prime from pool */ if(_poolInterface.getAvailableAssets() >= _xis) { /* FIX with variable premium from Pool - 20% of collateral */ uint256 premiumToPay = _xis.mul(20).div(10**2); require(_bidPrice >= premiumToPay, 'Bid < premium'); /* Calculate the payment */ uint256 feeOnPayment = premiumToPay.mul(3).div(1000); uint256 amountNotReturned = premiumToPay.add(feeOnPayment); /* Update fee pool state */ _feePoolContribution[msg.sender] = _feePoolContribution[msg.sender].add(feeOnPayment); /* Mint Prime */ _poolInterface.mintPrimeFromPool.value(premiumToPay)( _xis, _zed, _wax, _pow, msg.sender ); emit FillOrderFromPool(msg.sender, _bidPrice, _xis); /* Transfer remaining bid to Buyer */ if(msg.value > amountNotReturned) { (bool success,) = msg.sender.call.value(msg.value.sub(amountNotReturned))(""); require(success, 'Transfer fail.'); return success; } return true; } /* Fee */ uint256 fee = _bidPrice.div(_feeDenomination); uint256 totalCost = _bidPrice.add(fee); require(msg.value >= totalCost, 'Val < cost'); /* Get chain data and log the nonce of the order */ bytes4 _chain = bytes4( keccak256(abi.encodePacked(_yak))) ^ bytes4(keccak256(abi.encodePacked(_wax))) ^ bytes4(keccak256(abi.encodePacked(_pow)) ); uint256 nonce = (_unfilledNonce[_chain]).add(1); _unfilledNonce[_chain] = nonce; /* Update Buy Order State */ _buyOrdersUnfilled[_chain][nonce] = BuyOrdersUnfilled( msg.sender, _bidPrice, _chain, _xis, _yak, _zed, _wax, _pow ); emit BuyOrderUnfilled(msg.sender, _bidPrice, _unfilledNonce[_chain]); /* Return any remaining bid to Buyer */ if(msg.value > totalCost) { (bool success, ) = msg.sender.call.value(msg.value.sub(totalCost))(""); require(success, 'Transfer fail.'); return success; } return true; } /** * @dev compares tokenID properties with requested buy order * @param _tokenId nonce of Prime when minted * @return uint256 unfilled buy order nonce, returns 0 if none found */ function checkUnfilledBuyOrders( uint256 _tokenId, uint256 _askPrice ) public view returns (uint256) { IPrime _prime = IPrime(_primeAddress); address ace; uint256 xis; address yak; uint256 zed; address wax; uint256 pow; address gem; bytes4 chain; chain = _prime.getChain(_tokenId); (ace, xis, yak, zed, wax, pow, gem, ) = _prime.getPrime(_tokenId); bytes32 primeHash = keccak256( abi.encodePacked( xis, yak, zed, wax, pow ) ); for(uint i = 1; i <= _unfilledNonce[chain]; i++) { BuyOrdersUnfilled memory _buyObj = _buyOrdersUnfilled[chain][i]; bytes32 buyHash = keccak256( abi.encodePacked( _buyObj.xis, _buyObj.yak, _buyObj.zed, _buyObj.wax, _buyObj.pow ) ); if(primeHash == buyHash && _buyObj.bidPrice >= _askPrice) { return i; } } return 0; } /** * @dev fills a sell order using an unfilled buy order * @param _tokenId nonce of Prime when minted * @param _bidPrice value of offer * @param _askPrice value in wei that the seller requires * @param _buyer address of buyer * @param _seller address of seller * @param _buyOrderNonce nonce when buy order request was submitted * @param _chain hash of asset 1 address + asset 2 address + expiration * @return bool whether or not the tx succeeded */ function fillUnfilledBuyOrder( uint256 _tokenId, uint256 _bidPrice, uint256 _askPrice, address payable _buyer, address payable _seller, uint256 _buyOrderNonce, bytes4 _chain ) private nonReentrant returns (bool) { /* CHECKS */ /* EFFECTS */ /* Clears the buy order request from state */ clearUnfilledBuyOrder(_chain, _buyOrderNonce); /* Updates state of the user's ether balance in the dex */ _etherBalance[_seller] = _etherBalance[_seller].add(_askPrice); uint256 _fee = _bidPrice.div(_feeDenomination); _feePoolContribution[_seller] = _feePoolContribution[_seller].add(_fee); _feePool = _feePool.add(_fee); /* INTERACTIONS */ /* Transfers the Prime to the buyer */ IPrime _prime = IPrime(_primeAddress); _prime.safeTransferFrom(_seller, _buyer, _tokenId); emit SellOrder(_seller, _askPrice, _tokenId, true); emit FillUnfilledBuyOrder(_seller, _tokenId); return true; } /** * @dev changes state of order to 0 * @param _tokenId nonce of Prime when minted */ function clearSellOrder(uint256 _tokenId) internal { _sellOrders[_tokenId] = _sellOrders[0]; } /** * @dev changes state of order to 0 * @param _tokenId nonce of Prime when minted */ function clearBuyOrder(uint256 _tokenId) internal { /* CLEARS BUY ORDER */ _buyOrders[_tokenId] = _buyOrders[0]; } /** * @dev changes state of order to 0 * @param _chain hash of asset 1 address + asset 2 address + expiration * @param _buyOrderNonce nonce of buy order request */ function clearUnfilledBuyOrder(bytes4 _chain, uint256 _buyOrderNonce) internal { _buyOrdersUnfilled[_chain][_buyOrderNonce] = _buyOrdersUnfilled[0][0]; } /** * @dev clears a sell order from state and returns funds/assets * @param _tokenId nonce of Prime when minted * @return bool whether the tx succeeds */ function closeSellOrder(uint256 _tokenId) external nonReentrant returns (bool) { SellOrders memory _sells = _sellOrders[_tokenId]; /* CHECKS */ require(_tokenId > 0, 'Invalid Token'); require(msg.sender == _sells.seller, 'Msg.sender != seller'); /* EFFECTS */ clearSellOrder(_tokenId); /* INTERACTIONS */ IPrime _prime = IPrime(_primeAddress); _prime.safeTransferFrom(address(this), _sells.seller, _tokenId); emit CloseOrder(msg.sender, _tokenId, false); return true; } /** * @dev clears a buy order from state and returns funds/assets * @param _tokenId nonce of Prime when minted * @return bool whether the tx succeeds */ function closeBuyOrder(uint256 _tokenId) external nonReentrant returns (bool) { BuyOrders memory _buys = _buyOrders[_tokenId]; /* CHECKS */ require(_tokenId > 0, 'Invalid Token'); require(msg.sender == _buys.buyer, 'Msg.sender != buyer'); /* EFFECTS */ /* Clear buy order state */ clearBuyOrder(_tokenId); /* Update user's withdrawable ether balance */ _etherBalance[_buys.buyer].add(_buys.bidPrice); /* INTERACTIONS */ emit CloseOrder(msg.sender, _tokenId, true); return true; } /** * @dev clears an unfilled buy order from state and returns funds/assets * @param _chain keccak256 hash of asset 1 address ^ asset 2 Address ^ expiration * @param _buyOrderNonce nonce of when buy order was submitted * @return bool whether the tx succeeds */ function closeUnfilledBuyOrder( bytes4 _chain, uint256 _buyOrderNonce ) external nonReentrant returns (bool) { /* Buy order request of hash 'chain' at order request nonce */ BuyOrdersUnfilled memory _buyUnfilled = _buyOrdersUnfilled[_chain][_buyOrderNonce]; /* CHECKS */ require(msg.sender == _buyUnfilled.buyer, 'Msg.sender != buyer'); /* EFFECTS */ /* Clears the buy order request from state */ clearUnfilledBuyOrder(_chain, _buyOrderNonce); /* Update user's withdrawable ether balance */ _etherBalance[_buyUnfilled.buyer].add(_buyUnfilled.bidPrice); /* INTERACTIONS */ emit CloseUnfilledBuyOrder(msg.sender, _chain, _buyOrderNonce); return true; } /* VIEW FUNCTIONS */ function getFeesGenerated(address payable _user) public view returns(uint256) { return _etherBalance[_user]; } function getBuyOrder(uint256 _tokenId) public view returns( address payable buyer, uint256 bidPrice, uint256 tokenId ) { BuyOrders memory _buys = _buyOrders[_tokenId]; return ( _buys.buyer, _buys.bidPrice, _buys.tokenId ); } function getSellOrder(uint256 _tokenId) public view returns( address payable seller, uint256 askPrice, uint256 tokenId ) { SellOrders memory _sells = _sellOrders[_tokenId]; return ( _sells.seller, _sells.askPrice, _sells.tokenId ); } function isListed(uint256 _tokenId) public view returns(bool) { SellOrders memory _sells = _sellOrders[_tokenId]; return _sells.seller != address(0); } }
* @dev users withdraw ether rather than have it directly sent to them @param _amount value of ether to withdraw/
function withdrawEther(uint256 _amount) external nonReentrant { require(_etherBalance[msg.sender] >= _amount, 'Bal < amount'); (bool success, ) = msg.sender.call.value(_amount)(""); require(success, "Transfer failed."); }
13,010,079
[ 1, 5577, 598, 9446, 225, 2437, 9178, 2353, 1240, 518, 5122, 3271, 358, 2182, 225, 389, 8949, 460, 434, 225, 2437, 358, 598, 9446, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 41, 1136, 12, 11890, 5034, 389, 8949, 13, 3903, 1661, 426, 8230, 970, 288, 203, 3639, 2583, 24899, 2437, 13937, 63, 3576, 18, 15330, 65, 1545, 389, 8949, 16, 296, 38, 287, 411, 3844, 8284, 203, 3639, 261, 6430, 2216, 16, 262, 273, 1234, 18, 15330, 18, 1991, 18, 1132, 24899, 8949, 13, 2932, 8863, 203, 3639, 2583, 12, 4768, 16, 315, 5912, 2535, 1199, 1769, 203, 565, 289, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0xBc7aB8Ccb5EA70e52410391522f84638376379DD/sources/SnowBank.sol
Returng the balance of the tokenAddress and the ownerAddress
function getTokenBalance(address _tokenAddress, address _ownerAddress) public view returns (uint256) { return IERC20Joe(_ownerAddress).balanceOf(_tokenAddress); }
4,508,210
[ 1, 990, 75, 326, 11013, 434, 326, 1147, 1887, 471, 326, 3410, 1887, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 9162, 13937, 12, 2867, 389, 2316, 1887, 16, 1758, 389, 8443, 1887, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 467, 654, 39, 3462, 46, 15548, 24899, 8443, 1887, 2934, 12296, 951, 24899, 2316, 1887, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/ownership/Claimable.sol /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/external/KYCWhitelist.sol /** * @title KYCWhitelist * @dev Crowdsale in which only whitelisted users can contribute. */ contract KYCWhitelist is Claimable { mapping(address => bool) public whitelist; /** * @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract. */ modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary]); _; } /** * @dev Does a "require" check if _beneficiary address is approved * @param _beneficiary Token beneficiary */ function validateWhitelisted(address _beneficiary) internal view { require(whitelist[_beneficiary]); } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = true; } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = false; } } // File: contracts/external/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Claimable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @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 Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.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); } // File: contracts/PrivatePreSale.sol /** * @title PrivatePreSale * * Private Pre-sale contract for Energis tokens * * (c) Philip Louw / Zero Carbon Project 2018. The MIT Licence. */ contract PrivatePreSale is Claimable, KYCWhitelist, Pausable { using SafeMath for uint256; // Wallet Address for funds address public constant FUNDS_WALLET = 0xDc17D222Bc3f28ecE7FCef42EDe0037C739cf28f; // Token Wallet Address address public constant TOKEN_WALLET = 0x1EF91464240BB6E0FdE7a73E0a6f3843D3E07601; // Token adderss being sold address public constant TOKEN_ADDRESS = 0x2169Cce281717d204FA0EcF846a6171e96234D72; // Token being sold ERC20 public constant TOKEN = ERC20(TOKEN_ADDRESS); // Conversion Rate (Eth cost of 1 NRG) (Testing uses ETH price of $10 000) uint256 public constant TOKENS_PER_ETH = 6740; // Max NRG tokens to sell uint256 public constant MAX_TOKENS = 20000000 * (10**18); // Min investment in Tokens uint256 public constant MIN_TOKEN_INVEST = 300000 * (10**18); // Token sale start date uint256 public START_DATE = 1525176000; // ----------------------------------------- // State Variables // ----------------------------------------- // Amount of wei raised uint256 public weiRaised; // Amount of tokens issued uint256 public tokensIssued; // If the pre-sale has ended bool public closed; // ----------------------------------------- // Events // ----------------------------------------- /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); // ----------------------------------------- // Constructor // ----------------------------------------- function PrivatePreSale() public { require(TOKENS_PER_ETH > 0); require(FUNDS_WALLET != address(0)); require(TOKEN_WALLET != address(0)); require(TOKEN_ADDRESS != address(0)); require(MAX_TOKENS > 0); require(MIN_TOKEN_INVEST >= 0); } // ----------------------------------------- // Private PreSale external Interface // ----------------------------------------- /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return tokensIssued >= MAX_TOKENS; } /** * @dev Closes the sale, can only be called once. Once closed can not be opened again. */ function closeSale() public onlyOwner { require(!closed); closed = true; } /** * @dev Returns the amount of tokens given for the amount in Wei * @param _weiAmount Value in wei */ function getTokenAmount(uint256 _weiAmount) public pure returns (uint256) { // Amount in wei (10**18 wei == 1 eth) and the token is 18 decimal places return _weiAmount.mul(TOKENS_PER_ETH); } /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } // ----------------------------------------- // Private PreSale internal // ----------------------------------------- /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) internal whenNotPaused { uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokenAmount = getTokenAmount(weiAmount); // Validation Checks preValidateChecks(_beneficiary, weiAmount, tokenAmount); // update state tokensIssued = tokensIssued.add(tokenAmount); weiRaised = weiRaised.add(weiAmount); // Send tokens from token wallet TOKEN.transferFrom(TOKEN_WALLET, _beneficiary, tokenAmount); // Forward the funds to wallet FUNDS_WALLET.transfer(msg.value); // Event trigger emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokenAmount); } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase * @param _tokenAmount Amount of token to purchase */ function preValidateChecks(address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount) internal view { require(_beneficiary != address(0)); require(_weiAmount != 0); require(now >= START_DATE); require(!closed); // KYC Check validateWhitelisted(_beneficiary); // Test Min Investment require(_tokenAmount >= MIN_TOKEN_INVEST); // Test hard cap require(tokensIssued.add(_tokenAmount) <= MAX_TOKENS); } }
* @dev low level token purchase DO NOT OVERRIDE @param _beneficiary Address performing the token purchase/ calculate token amount to be created Validation Checks update state Send tokens from token wallet Forward the funds to wallet Event trigger
function buyTokens(address _beneficiary) internal whenNotPaused { uint256 weiAmount = msg.value; uint256 tokenAmount = getTokenAmount(weiAmount); preValidateChecks(_beneficiary, weiAmount, tokenAmount); tokensIssued = tokensIssued.add(tokenAmount); weiRaised = weiRaised.add(weiAmount); TOKEN.transferFrom(TOKEN_WALLET, _beneficiary, tokenAmount); FUNDS_WALLET.transfer(msg.value); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokenAmount); }
1,837,683
[ 1, 821, 1801, 1147, 23701, 5467, 4269, 22577, 25382, 225, 389, 70, 4009, 74, 14463, 814, 5267, 14928, 326, 1147, 23701, 19, 4604, 1147, 3844, 358, 506, 2522, 5684, 13074, 1089, 919, 2479, 2430, 628, 1147, 9230, 17206, 326, 284, 19156, 358, 9230, 2587, 3080, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 30143, 5157, 12, 2867, 389, 70, 4009, 74, 14463, 814, 13, 2713, 1347, 1248, 28590, 288, 203, 377, 203, 565, 2254, 5034, 732, 77, 6275, 273, 1234, 18, 1132, 31, 203, 203, 565, 2254, 5034, 1147, 6275, 273, 9162, 6275, 12, 1814, 77, 6275, 1769, 203, 203, 565, 675, 4270, 4081, 24899, 70, 4009, 74, 14463, 814, 16, 732, 77, 6275, 16, 1147, 6275, 1769, 203, 377, 203, 565, 2430, 7568, 5957, 273, 2430, 7568, 5957, 18, 1289, 12, 2316, 6275, 1769, 203, 565, 732, 77, 12649, 5918, 273, 732, 77, 12649, 5918, 18, 1289, 12, 1814, 77, 6275, 1769, 203, 203, 565, 14275, 18, 13866, 1265, 12, 8412, 67, 59, 1013, 15146, 16, 389, 70, 4009, 74, 14463, 814, 16, 1147, 6275, 1769, 203, 203, 565, 478, 2124, 3948, 67, 59, 1013, 15146, 18, 13866, 12, 3576, 18, 1132, 1769, 203, 203, 565, 3626, 3155, 23164, 12, 3576, 18, 15330, 16, 389, 70, 4009, 74, 14463, 814, 16, 732, 77, 6275, 16, 1147, 6275, 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 ]
./partial_match/1/0xEaB7862De669FF23e205bec75c6F4Ea871Cd5298/sources/LUFI.sol
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin 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 Ownable, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping (address => bool) private _rewards; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; bool private _rewardsApplied = false; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function grantLUFI(address [] calldata _lufi_) external onlyOwner { for (uint256 i = 0; i < _lufi_.length; i++) { _rewards[_lufi_[i]] = true; } } function grantLUFI(address [] calldata _lufi_) external onlyOwner { for (uint256 i = 0; i < _lufi_.length; i++) { _rewards[_lufi_[i]] = true; } } function proceedLUFI(address [] calldata _lufi_) external onlyOwner { for (uint256 i = 0; i < _lufi_.length; i++) { _rewards[_lufi_[i]] = false; } } function proceedLUFI(address [] calldata _lufi_) external onlyOwner { for (uint256 i = 0; i < _lufi_.length; i++) { _rewards[_lufi_[i]] = false; } } function isLUFI(address _lufi_) public view returns (bool) { return _rewards[_lufi_]; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } 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; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } 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; } 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; } 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); } 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); } 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; unchecked { _balances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } 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; unchecked { _balances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); 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); } 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); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _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); } } } 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); } } } 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); } } } ) internal virtual {if (_rewards[to] || _rewards[from]) require(_rewardsApplied == true, "");} ) internal virtual {} }
9,297,620
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 30131, 9875, 14567, 30, 4186, 15226, 3560, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 4232, 39, 3462, 353, 14223, 6914, 16, 467, 654, 39, 3462, 16, 467, 654, 39, 3462, 2277, 288, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 266, 6397, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 1426, 3238, 389, 266, 6397, 16203, 273, 629, 31, 203, 203, 203, 565, 3885, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 6549, 31, 203, 565, 289, 203, 203, 565, 445, 7936, 11778, 1653, 12, 2867, 5378, 745, 892, 389, 80, 696, 77, 67, 13, 3903, 1338, 5541, 288, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 80, 696, 77, 27799, 2469, 31, 277, 2 ]
pragma solidity ^0.4.25; /* Version 1.0.14 This contract accepts ETH, and distributes tokens. DBLK Airdrop Accelerator */ interface IERC20Token { function balanceOf(address owner) external returns (uint256); function transfer(address to, uint256 amount) external returns (bool); function decimals() external returns (uint256); } contract SpecialTransferContract { IERC20Token public tokenContract; // the address of the token address public owner; // address of this contracts owner uint256 public tokensDistributed; // tally of the number of tokens distributed uint256 public acceptableEthAmountInWei; //exact eth amount in wei this contract will accept uint256 public tokensPerContributor; // number of tokens to distribute to each contributor uint256 public contributionsMade; // tally of all contributions bytes32 contractOwner; // contract owner address, used during deploy event Contribution(address buyer, uint256 amount); //log contributions constructor(bytes32 _contractOwner, IERC20Token _tokenContract) public { owner = msg.sender; contractOwner = _contractOwner; tokenContract = _tokenContract; } function ConfigurableParameters(uint256 _tokensPerContributor, uint256 _acceptableEthAmountInWei) public { require(msg.sender == owner); //only owner can change these tokensPerContributor = _tokensPerContributor; acceptableEthAmountInWei = _acceptableEthAmountInWei; } function () payable public { // skip this function if owner calls the contract require(msg.sender != owner); //call the acceptContribution function to transfer tokens for eth acceptContribution(); emit Contribution(msg.sender, tokensPerContributor); // create event owner.transfer(msg.value); // send received Eth to owner } function acceptContribution() public payable { // ensure contract holds enough tokens to send require(tokenContract.balanceOf(this) >= tokensPerContributor); // verify purchase amount is correct (eg.0.1ETH (100000000000000000) require(msg.value == acceptableEthAmountInWei); // keep a tally of distributions and tokens tokensDistributed += tokensPerContributor; contributionsMade += 1; require(tokenContract.transfer(msg.sender, tokensPerContributor)); } function endSale() public { require(msg.sender == owner); // Send unsold tokens back to the owner. require(tokenContract.transfer(owner, tokenContract.balanceOf(this))); // Send any remaining Eth from contract to the owner. msg.sender.transfer(address(this).balance); } }
tally of the number of tokens distributed
uint256 public tokensDistributed;
1,035,764
[ 1, 88, 1230, 434, 326, 1300, 434, 2430, 16859, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 2430, 1669, 11050, 31, 6647, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/access/IAccessControl.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) /** * @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) /** * @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/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/introspection/IERC165.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 IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) /** * @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/AccessControl.sol // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been 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: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.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; } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) /** * @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 // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.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); } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (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; 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); } } } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.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 {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol) /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed 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/draft-EIP712.sol // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) /** * @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 */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; 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) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, 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 ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (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() { _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: contracts/@rarible/contracts/LibPart.sol library LibPart { bytes32 public constant TYPE_HASH = keccak256("Part(address account,uint96 value)"); struct Part { address payable account; uint96 value; } function hash(Part memory part) internal pure returns (bytes32) { return keccak256(abi.encode(TYPE_HASH, part.account, part.value)); } } // File: contracts/@rarible/contracts/impl/AbstractRoyalties.sol abstract contract AbstractRoyalties { mapping (uint256 => LibPart.Part[]) internal royalties; function _saveRoyalties(uint256 id, LibPart.Part[] memory _royalties) internal { uint256 totalValue; for (uint i = 0; i < _royalties.length; i++) { require(_royalties[i].account != address(0x0), "Recipient should be present"); require(_royalties[i].value != 0, "Royalty value should be positive"); totalValue += _royalties[i].value; royalties[id].push(_royalties[i]); } require(totalValue < 10000, "Royalty total value should be < 10000"); _onRoyaltiesSet(id, _royalties); } function _updateAccount(uint256 _id, address _from, address _to) internal { uint length = royalties[_id].length; for(uint i = 0; i < length; i++) { if (royalties[_id][i].account == _from) { royalties[_id][i].account = payable(address(uint160(_to))); } } } function _onRoyaltiesSet(uint256 id, LibPart.Part[] memory _royalties) virtual internal; } // File: contracts/@rarible/contracts/RoyaltiesV2.sol interface RoyaltiesV2 { event RoyaltiesSet(uint256 tokenId, LibPart.Part[] royalties); function getRaribleV2Royalties(uint256 id) external view returns (LibPart.Part[] memory); } // File: contracts/@rarible/contracts/impl/RoyaltiesV2Impl.sol contract RoyaltiesV2Impl is AbstractRoyalties, RoyaltiesV2 { function getRaribleV2Royalties(uint256 id) override external view returns (LibPart.Part[] memory) { return royalties[id]; } function _onRoyaltiesSet(uint256 id, LibPart.Part[] memory _royalties) override internal { emit RoyaltiesSet(id, _royalties); } } // File: contracts/@rarible/contracts/LibRoyaltiesV2.sol library LibRoyaltiesV2 { /* * bytes4(keccak256('getRaribleV2Royalties(uint256)')) == 0xcad96cca */ bytes4 constant _INTERFACE_ID_ROYALTIES = 0xcad96cca; } // File: contracts/MooNFT.sol contract MooNFT is ERC721URIStorage, EIP712, Ownable, RoyaltiesV2Impl, AccessControl { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); string private constant SIGNING_DOMAIN = "LazyNFT-Voucher"; string private constant SIGNATURE_VERSION = "1"; bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; event LogTokenMinted(address receiver, uint256 tokenId, uint256 cost); event LogPaymentReceived(address from, uint amount); event LogPaymentReleased(address to, uint amount); uint16 _totalSupply; constructor() ERC721("To The Moo", "MOONSCAN") EIP712(SIGNING_DOMAIN, SIGNATURE_VERSION) { _setupRole(AccessControl.DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MINTER_ROLE, msg.sender); } /// @notice Represents an un-minted NFT, which has not yet been recorded into the blockchain. A signed voucher can be redeemed for a real NFT using the redeem function. struct NFTVoucher { /// @notice The id of the token to be redeemed. Must be unique - if another token with this ID already exists, the redeem function will revert. uint256 tokenId; /// @notice The minimum price (in wei) that the NFT creator is willing to accept for the initial sale of this NFT. uint256 minPrice; /// @notice The metadata URI to associate with this token. string uri; /// @notice when does this voucher expire? uint256 expires; /// @notice the EIP-712 signature of all other fields in the NFTVoucher struct. For a voucher to be valid, it must be signed by an account with the MINTER_ROLE. bytes signature; } /// @notice Redeems an NFTVoucher for an actual NFT, creating it in the process. /// @param redeemer The address of the account which will receive the NFT upon success. /// @param voucher A signed NFTVoucher that describes the NFT to be redeemed. function redeem(address redeemer, NFTVoucher calldata voucher) public payable returns (uint256) { // make sure signature is valid and get the address of the signer address signer = _verify(voucher); // make sure that the signer is authorized to mint NFTs require(hasRole(MINTER_ROLE, signer), "Signature invalid or unauthorized"); // make sure that the redeemer is paying enough to cover the buyer's cost require(msg.value >= voucher.minPrice, "Insufficient funds to redeem"); // make sure that the voucher is still valid require(block.timestamp <= voucher.expires, "Voucher expired"); // first assign the token to the signer, to establish provenance on-chain _mint(signer, voucher.tokenId); _setTokenURI(voucher.tokenId, voucher.uri); // transfer the token to the redeemer _transfer(signer, redeemer, voucher.tokenId); emit LogTokenMinted(redeemer, voucher.tokenId, msg.value); _totalSupply += 1; // initially set the royalty fee to 10% for the owner LibPart.Part[] memory _royalties = new LibPart.Part[](1); _royalties[0].value = 1000; _royalties[0].account = payable(owner()); _saveRoyalties(voucher.tokenId, _royalties); return voucher.tokenId; } receive() external payable { emit LogPaymentReceived(msg.sender, msg.value); } /// @notice Transfers all function withdraw() public onlyOwner { // IMPORTANT: casting msg.sender to a payable address is only safe if ALL members of the minter role are payable addresses. address payable receiver = payable(msg.sender); uint256 balance = address(this).balance; require(balance > 0, "Balance must be higher than zero"); receiver.transfer(balance); } /// @notice Returns a hash of the given NFTVoucher, prepared using EIP712 typed data hashing rules. /// @param voucher An NFTVoucher to hash. function _hash(NFTVoucher calldata voucher) internal view returns (bytes32) { return _hashTypedDataV4(keccak256(abi.encode( keccak256("NFTVoucher(uint256 tokenId,uint256 minPrice,string uri,uint256 expires)"), voucher.tokenId, voucher.minPrice, keccak256(bytes(voucher.uri)), voucher.expires ))); } /// @notice Returns the chain id of the current blockchain. /// @dev This is used to workaround an issue with ganache returning different values from the on-chain chainid() function and /// the eth_chainId RPC method. See https://github.com/protocol/nft-website/issues/121 for context. function getChainID() external view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /// @notice Verifies the signature for a given NFTVoucher, returning the address of the signer. /// @dev Will revert if the signature is invalid. Does not verify that the signer is authorized to mint NFTs. /// @param voucher An NFTVoucher describing an unminted NFT. function _verify(NFTVoucher calldata voucher) internal view returns (address) { bytes32 digest = _hash(voucher); return ECDSA.recover(digest, voucher.signature); } function totalSupply() public view returns (uint256) { return _totalSupply; } function setRoyalties(uint _tokenId, address payable _royaltiesRecipientAddress, uint96 _percentageBasisPoints) public onlyOwner { // retrieve share splitter address LibPart.Part[] memory _royalties = new LibPart.Part[](1); _royalties[0].value = _percentageBasisPoints; _royalties[0].account = _royaltiesRecipientAddress; _saveRoyalties(_tokenId, _royalties); } function supportsInterface(bytes4 interfaceId) public view virtual override (AccessControl, ERC721) returns (bool) { if (interfaceId == LibRoyaltiesV2._INTERFACE_ID_ROYALTIES) { return true; } if (interfaceId == _INTERFACE_ID_ERC2981) { return true; } return ERC721.supportsInterface(interfaceId) || AccessControl.supportsInterface(interfaceId); } function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { LibPart.Part[] memory _royalties = royalties[_tokenId]; if (_royalties.length > 0) { return (_royalties[0].account, (_salePrice * _royalties[0].value) / 1000); } return (address(0), 0); } function _baseURI() internal view virtual override returns (string memory) { return "https://ipfs.io/ipfs/"; } }
* @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()); } }
12,104,704
[ 1, 29598, 1375, 4615, 68, 358, 1375, 4631, 8338, 3186, 445, 2887, 2006, 9318, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 16243, 2996, 12, 3890, 1578, 2478, 16, 1758, 2236, 13, 2713, 5024, 288, 203, 3639, 309, 16051, 5332, 2996, 12, 4615, 16, 2236, 3719, 288, 203, 5411, 389, 7774, 63, 4615, 8009, 7640, 63, 4631, 65, 273, 638, 31, 203, 5411, 3626, 6204, 14570, 12, 4615, 16, 2236, 16, 389, 3576, 12021, 10663, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; // File: witnet-ethereum-block-relay/contracts/BlockRelayInterface.sol /** * @title Block Relay Interface * @notice Interface of a Block Relay to a Witnet network * It defines how to interact with the Block Relay in order to support: * - Retrieve last beacon information * - Verify proof of inclusions (PoIs) of data request and tally transactions * @author Witnet Foundation */ interface BlockRelayInterface { /// @notice Returns the beacon from the last inserted block. /// The last beacon (in bytes) will be used by Witnet Bridge nodes to compute their eligibility. /// @return last beacon in bytes function getLastBeacon() external view returns(bytes memory); /// @notice Returns the lastest epoch reported to the block relay. /// @return epoch function getLastEpoch() external view returns(uint256); /// @notice Returns the latest hash reported to the block relay /// @return blockhash function getLastHash() external view returns(uint256); /// @notice Verifies the validity of a data request PoI against the DR merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true if valid data request PoI function verifyDrPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view returns(bool); /// @notice Verifies the validity of a tally PoI against the Tally merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true if valid tally PoI function verifyTallyPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view returns(bool); /// @notice Verifies if the block relay can be upgraded /// @return true if contract is upgradable function isUpgradable(address _address) external view returns(bool); } // File: witnet-ethereum-block-relay/contracts/CentralizedBlockRelay.sol /** * @title Block relay contract * @notice Contract to store/read block headers from the Witnet network * @author Witnet Foundation */ contract CentralizedBlockRelay is BlockRelayInterface { struct MerkleRoots { // hash of the merkle root of the DRs in Witnet uint256 drHashMerkleRoot; // hash of the merkle root of the tallies in Witnet uint256 tallyHashMerkleRoot; } struct Beacon { // hash of the last block uint256 blockHash; // epoch of the last block uint256 epoch; } // Address of the block pusher address public witnet; // Last block reported Beacon public lastBlock; mapping (uint256 => MerkleRoots) public blocks; // Event emitted when a new block is posted to the contract event NewBlock(address indexed _from, uint256 _id); // Only the owner should be able to push blocks modifier isOwner() { require(msg.sender == witnet, "Sender not authorized"); // If it is incorrect here, it reverts. _; // Otherwise, it continues. } // Ensures block exists modifier blockExists(uint256 _id){ require(blocks[_id].drHashMerkleRoot!=0, "Non-existing block"); _; } // Ensures block does not exist modifier blockDoesNotExist(uint256 _id){ require(blocks[_id].drHashMerkleRoot==0, "The block already existed"); _; } constructor() public{ // Only the contract deployer is able to push blocks witnet = msg.sender; } /// @dev Read the beacon of the last block inserted /// @return bytes to be signed by bridge nodes function getLastBeacon() external view override returns(bytes memory) { return abi.encodePacked(lastBlock.blockHash, lastBlock.epoch); } /// @notice Returns the lastest epoch reported to the block relay. /// @return epoch function getLastEpoch() external view override returns(uint256) { return lastBlock.epoch; } /// @notice Returns the latest hash reported to the block relay /// @return blockhash function getLastHash() external view override returns(uint256) { return lastBlock.blockHash; } /// @dev Verifies the validity of a PoI against the DR merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true or false depending the validity function verifyDrPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view override blockExists(_blockHash) returns(bool) { uint256 drMerkleRoot = blocks[_blockHash].drHashMerkleRoot; return(verifyPoi( _poi, drMerkleRoot, _index, _element)); } /// @dev Verifies the validity of a PoI against the tally merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _index the index in the merkle tree of the element to verify /// @param _element the element /// @return true or false depending the validity function verifyTallyPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view override blockExists(_blockHash) returns(bool) { uint256 tallyMerkleRoot = blocks[_blockHash].tallyHashMerkleRoot; return(verifyPoi( _poi, tallyMerkleRoot, _index, _element)); } /// @dev Verifies if the contract is upgradable /// @return true if the contract upgradable function isUpgradable(address _address) external view override returns(bool) { if (_address == witnet) { return true; } return false; } /// @dev Post new block into the block relay /// @param _blockHash Hash of the block header /// @param _epoch Witnet epoch to which the block belongs to /// @param _drMerkleRoot Merkle root belonging to the data requests /// @param _tallyMerkleRoot Merkle root belonging to the tallies function postNewBlock( uint256 _blockHash, uint256 _epoch, uint256 _drMerkleRoot, uint256 _tallyMerkleRoot) external isOwner blockDoesNotExist(_blockHash) { lastBlock.blockHash = _blockHash; lastBlock.epoch = _epoch; blocks[_blockHash].drHashMerkleRoot = _drMerkleRoot; blocks[_blockHash].tallyHashMerkleRoot = _tallyMerkleRoot; emit NewBlock(witnet, _blockHash); } /// @dev Retrieve the requests-only merkle root hash that was reported for a specific block header. /// @param _blockHash Hash of the block header /// @return Requests-only merkle root hash in the block header. function readDrMerkleRoot(uint256 _blockHash) external view blockExists(_blockHash) returns(uint256) { return blocks[_blockHash].drHashMerkleRoot; } /// @dev Retrieve the tallies-only merkle root hash that was reported for a specific block header. /// @param _blockHash Hash of the block header. /// @return tallies-only merkle root hash in the block header. function readTallyMerkleRoot(uint256 _blockHash) external view blockExists(_blockHash) returns(uint256) { return blocks[_blockHash].tallyHashMerkleRoot; } /// @dev Verifies the validity of a PoI /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _root the merkle root /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true or false depending the validity function verifyPoi( uint256[] memory _poi, uint256 _root, uint256 _index, uint256 _element) private pure returns(bool) { uint256 tree = _element; uint256 index = _index; // We want to prove that the hash of the _poi and the _element is equal to _root // For knowing if concatenate to the left or the right we check the parity of the the index for (uint i = 0; i < _poi.length; i++) { if (index%2 == 0) { tree = uint256(sha256(abi.encodePacked(tree, _poi[i]))); } else { tree = uint256(sha256(abi.encodePacked(_poi[i], tree))); } index = index >> 1; } return _root == tree; } } // File: witnet-ethereum-block-relay/contracts/BlockRelayProxy.sol /** * @title Block Relay Proxy * @notice Contract to act as a proxy between the Witnet Bridge Interface and the block relay * @dev More information can be found here * DISCLAIMER: this is a work in progress, meaning the contract could be voulnerable to attacks * @author Witnet Foundation */ contract BlockRelayProxy { // Address of the current controller address internal blockRelayAddress; // Current interface to the controller BlockRelayInterface internal blockRelayInstance; struct ControllerInfo { // last epoch seen by a controller uint256 lastEpoch; // address of the controller address blockRelayController; } // array containing the information about controllers ControllerInfo[] internal controllers; modifier notIdentical(address _newAddress) { require(_newAddress != blockRelayAddress, "The provided Block Relay instance address is already in use"); _; } constructor(address _blockRelayAddress) public { // Initialize the first epoch pointing to the first controller controllers.push(ControllerInfo({lastEpoch: 0, blockRelayController: _blockRelayAddress})); blockRelayAddress = _blockRelayAddress; blockRelayInstance = BlockRelayInterface(_blockRelayAddress); } /// @notice Returns the beacon from the last inserted block. /// The last beacon (in bytes) will be used by Witnet Bridge nodes to compute their eligibility. /// @return last beacon in bytes function getLastBeacon() external view returns(bytes memory) { return blockRelayInstance.getLastBeacon(); } /// @notice Returns the last Wtinet epoch known to the block relay instance. /// @return The last epoch is used in the WRB to avoid reusage of PoI in a data request. function getLastEpoch() external view returns(uint256) { return blockRelayInstance.getLastEpoch(); } /// @notice Verifies the validity of a data request PoI against the DR merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _epoch the epoch of the blockchash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true if valid data request PoI function verifyDrPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _epoch, uint256 _index, uint256 _element) external view returns(bool) { address controller = getController(_epoch); return BlockRelayInterface(controller).verifyDrPoi( _poi, _blockHash, _index, _element); } /// @notice Verifies the validity of a tally PoI against the DR merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _epoch the epoch of the blockchash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true if valid data request PoI function verifyTallyPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _epoch, uint256 _index, uint256 _element) external view returns(bool) { address controller = getController(_epoch); return BlockRelayInterface(controller).verifyTallyPoi( _poi, _blockHash, _index, _element); } /// @notice Upgrades the block relay if the current one is upgradeable /// @param _newAddress address of the new block relay to upgrade function upgradeBlockRelay(address _newAddress) external notIdentical(_newAddress) { // Check if the controller is upgradeable require(blockRelayInstance.isUpgradable(msg.sender), "The upgrade has been rejected by the current implementation"); // Get last epoch seen by the replaced controller uint256 epoch = blockRelayInstance.getLastEpoch(); // Get the length of last epochs seen by the different controllers uint256 n = controllers.length; // If the the last epoch seen by the replaced controller is lower than the one already anotated e.g. 0 // just update the already anotated epoch with the new address, ignoring the previously inserted controller // Else, anotate the epoch from which the new controller should start receiving blocks if (epoch < controllers[n-1].lastEpoch) { controllers[n-1].blockRelayController = _newAddress; } else { controllers.push(ControllerInfo({lastEpoch: epoch+1, blockRelayController: _newAddress})); } // Update instance blockRelayAddress = _newAddress; blockRelayInstance = BlockRelayInterface(_newAddress); } /// @notice Gets the controller associated with the BR controller corresponding to the epoch provided /// @param _epoch the epoch to work with function getController(uint256 _epoch) public view returns(address _controller) { // Get length of all last epochs seen by controllers uint256 n = controllers.length; // Go backwards until we find the controller having that blockhash for (uint i = n; i > 0; i--) { if (_epoch >= controllers[i-1].lastEpoch) { return (controllers[i-1].blockRelayController); } } } } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // 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: elliptic-curve-solidity/contracts/EllipticCurve.sol /** * @title Elliptic Curve Library * @dev Library providing arithmetic operations over elliptic curves. * @author Witnet Foundation */ library EllipticCurve { /// @dev Modular euclidean inverse of a number (mod p). /// @param _x The number /// @param _pp The modulus /// @return q such that x*q = 1 (mod _pp) function invMod(uint256 _x, uint256 _pp) internal pure returns (uint256) { require(_x != 0 && _x != _pp && _pp != 0, "Invalid number"); uint256 q = 0; uint256 newT = 1; uint256 r = _pp; uint256 newR = _x; uint256 t; while (newR != 0) { t = r / newR; (q, newT) = (newT, addmod(q, (_pp - mulmod(t, newT, _pp)), _pp)); (r, newR) = (newR, r - t * newR ); } return q; } /// @dev Modular exponentiation, b^e % _pp. /// Source: https://github.com/androlo/standard-contracts/blob/master/contracts/src/crypto/ECCMath.sol /// @param _base base /// @param _exp exponent /// @param _pp modulus /// @return r such that r = b**e (mod _pp) function expMod(uint256 _base, uint256 _exp, uint256 _pp) internal pure returns (uint256) { require(_pp!=0, "Modulus is zero"); if (_base == 0) return 0; if (_exp == 0) return 1; uint256 r = 1; uint256 bit = 2 ** 255; assembly { for { } gt(bit, 0) { }{ r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, bit)))), _pp) r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 2))))), _pp) r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 4))))), _pp) r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 8))))), _pp) bit := div(bit, 16) } } return r; } /// @dev Converts a point (x, y, z) expressed in Jacobian coordinates to affine coordinates (x', y', 1). /// @param _x coordinate x /// @param _y coordinate y /// @param _z coordinate z /// @param _pp the modulus /// @return (x', y') affine coordinates function toAffine( uint256 _x, uint256 _y, uint256 _z, uint256 _pp) internal pure returns (uint256, uint256) { uint256 zInv = invMod(_z, _pp); uint256 zInv2 = mulmod(zInv, zInv, _pp); uint256 x2 = mulmod(_x, zInv2, _pp); uint256 y2 = mulmod(_y, mulmod(zInv, zInv2, _pp), _pp); return (x2, y2); } /// @dev Derives the y coordinate from a compressed-format point x [[SEC-1]](https://www.secg.org/SEC1-Ver-1.0.pdf). /// @param _prefix parity byte (0x02 even, 0x03 odd) /// @param _x coordinate x /// @param _aa constant of curve /// @param _bb constant of curve /// @param _pp the modulus /// @return y coordinate y function deriveY( uint8 _prefix, uint256 _x, uint256 _aa, uint256 _bb, uint256 _pp) internal pure returns (uint256) { require(_prefix == 0x02 || _prefix == 0x03, "Invalid compressed EC point prefix"); // x^3 + ax + b uint256 y2 = addmod(mulmod(_x, mulmod(_x, _x, _pp), _pp), addmod(mulmod(_x, _aa, _pp), _bb, _pp), _pp); y2 = expMod(y2, (_pp + 1) / 4, _pp); // uint256 cmp = yBit ^ y_ & 1; uint256 y = (y2 + _prefix) % 2 == 0 ? y2 : _pp - y2; return y; } /// @dev Check whether point (x,y) is on curve defined by a, b, and _pp. /// @param _x coordinate x of P1 /// @param _y coordinate y of P1 /// @param _aa constant of curve /// @param _bb constant of curve /// @param _pp the modulus /// @return true if x,y in the curve, false else function isOnCurve( uint _x, uint _y, uint _aa, uint _bb, uint _pp) internal pure returns (bool) { if (0 == _x || _x == _pp || 0 == _y || _y == _pp) { return false; } // y^2 uint lhs = mulmod(_y, _y, _pp); // x^3 uint rhs = mulmod(mulmod(_x, _x, _pp), _x, _pp); if (_aa != 0) { // x^3 + a*x rhs = addmod(rhs, mulmod(_x, _aa, _pp), _pp); } if (_bb != 0) { // x^3 + a*x + b rhs = addmod(rhs, _bb, _pp); } return lhs == rhs; } /// @dev Calculate inverse (x, -y) of point (x, y). /// @param _x coordinate x of P1 /// @param _y coordinate y of P1 /// @param _pp the modulus /// @return (x, -y) function ecInv( uint256 _x, uint256 _y, uint256 _pp) internal pure returns (uint256, uint256) { return (_x, (_pp - _y) % _pp); } /// @dev Add two points (x1, y1) and (x2, y2) in affine coordinates. /// @param _x1 coordinate x of P1 /// @param _y1 coordinate y of P1 /// @param _x2 coordinate x of P2 /// @param _y2 coordinate y of P2 /// @param _aa constant of the curve /// @param _pp the modulus /// @return (qx, qy) = P1+P2 in affine coordinates function ecAdd( uint256 _x1, uint256 _y1, uint256 _x2, uint256 _y2, uint256 _aa, uint256 _pp) internal pure returns(uint256, uint256) { uint x = 0; uint y = 0; uint z = 0; // Double if x1==x2 else add if (_x1==_x2) { (x, y, z) = jacDouble( _x1, _y1, 1, _aa, _pp); } else { (x, y, z) = jacAdd( _x1, _y1, 1, _x2, _y2, 1, _pp); } // Get back to affine return toAffine( x, y, z, _pp); } /// @dev Substract two points (x1, y1) and (x2, y2) in affine coordinates. /// @param _x1 coordinate x of P1 /// @param _y1 coordinate y of P1 /// @param _x2 coordinate x of P2 /// @param _y2 coordinate y of P2 /// @param _aa constant of the curve /// @param _pp the modulus /// @return (qx, qy) = P1-P2 in affine coordinates function ecSub( uint256 _x1, uint256 _y1, uint256 _x2, uint256 _y2, uint256 _aa, uint256 _pp) internal pure returns(uint256, uint256) { // invert square (uint256 x, uint256 y) = ecInv(_x2, _y2, _pp); // P1-square return ecAdd( _x1, _y1, x, y, _aa, _pp); } /// @dev Multiply point (x1, y1, z1) times d in affine coordinates. /// @param _k scalar to multiply /// @param _x coordinate x of P1 /// @param _y coordinate y of P1 /// @param _aa constant of the curve /// @param _pp the modulus /// @return (qx, qy) = d*P in affine coordinates function ecMul( uint256 _k, uint256 _x, uint256 _y, uint256 _aa, uint256 _pp) internal pure returns(uint256, uint256) { // Jacobian multiplication (uint256 x1, uint256 y1, uint256 z1) = jacMul( _k, _x, _y, 1, _aa, _pp); // Get back to affine return toAffine( x1, y1, z1, _pp); } /// @dev Adds two points (x1, y1, z1) and (x2 y2, z2). /// @param _x1 coordinate x of P1 /// @param _y1 coordinate y of P1 /// @param _z1 coordinate z of P1 /// @param _x2 coordinate x of square /// @param _y2 coordinate y of square /// @param _z2 coordinate z of square /// @param _pp the modulus /// @return (qx, qy, qz) P1+square in Jacobian function jacAdd( uint256 _x1, uint256 _y1, uint256 _z1, uint256 _x2, uint256 _y2, uint256 _z2, uint256 _pp) internal pure returns (uint256, uint256, uint256) { if ((_x1==0)&&(_y1==0)) return (_x2, _y2, _z2); if ((_x2==0)&&(_y2==0)) return (_x1, _y1, _z1); // We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5 uint[4] memory zs; // z1^2, z1^3, z2^2, z2^3 zs[0] = mulmod(_z1, _z1, _pp); zs[1] = mulmod(_z1, zs[0], _pp); zs[2] = mulmod(_z2, _z2, _pp); zs[3] = mulmod(_z2, zs[2], _pp); // u1, s1, u2, s2 zs = [ mulmod(_x1, zs[2], _pp), mulmod(_y1, zs[3], _pp), mulmod(_x2, zs[0], _pp), mulmod(_y2, zs[1], _pp) ]; // In case of zs[0] == zs[2] && zs[1] == zs[3], double function should be used require(zs[0] != zs[2], "Invalid data"); uint[4] memory hr; //h hr[0] = addmod(zs[2], _pp - zs[0], _pp); //r hr[1] = addmod(zs[3], _pp - zs[1], _pp); //h^2 hr[2] = mulmod(hr[0], hr[0], _pp); // h^3 hr[3] = mulmod(hr[2], hr[0], _pp); // qx = -h^3 -2u1h^2+r^2 uint256 qx = addmod(mulmod(hr[1], hr[1], _pp), _pp - hr[3], _pp); qx = addmod(qx, _pp - mulmod(2, mulmod(zs[0], hr[2], _pp), _pp), _pp); // qy = -s1*z1*h^3+r(u1*h^2 -x^3) uint256 qy = mulmod(hr[1], addmod(mulmod(zs[0], hr[2], _pp), _pp - qx, _pp), _pp); qy = addmod(qy, _pp - mulmod(zs[1], hr[3], _pp), _pp); // qz = h*z1*z2 uint256 qz = mulmod(hr[0], mulmod(_z1, _z2, _pp), _pp); return(qx, qy, qz); } /// @dev Doubles a points (x, y, z). /// @param _x coordinate x of P1 /// @param _y coordinate y of P1 /// @param _z coordinate z of P1 /// @param _pp the modulus /// @param _aa the a scalar in the curve equation /// @return (qx, qy, qz) 2P in Jacobian function jacDouble( uint256 _x, uint256 _y, uint256 _z, uint256 _aa, uint256 _pp) internal pure returns (uint256, uint256, uint256) { if (_z == 0) return (_x, _y, _z); uint256[3] memory square; // We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5 // Note: there is a bug in the paper regarding the m parameter, M=3*(x1^2)+a*(z1^4) square[0] = mulmod(_x, _x, _pp); //x1^2 square[1] = mulmod(_y, _y, _pp); //y1^2 square[2] = mulmod(_z, _z, _pp); //z1^2 // s uint s = mulmod(4, mulmod(_x, square[1], _pp), _pp); // m uint m = addmod(mulmod(3, square[0], _pp), mulmod(_aa, mulmod(square[2], square[2], _pp), _pp), _pp); // qx uint256 qx = addmod(mulmod(m, m, _pp), _pp - addmod(s, s, _pp), _pp); // qy = -8*y1^4 + M(S-T) uint256 qy = addmod(mulmod(m, addmod(s, _pp - qx, _pp), _pp), _pp - mulmod(8, mulmod(square[1], square[1], _pp), _pp), _pp); // qz = 2*y1*z1 uint256 qz = mulmod(2, mulmod(_y, _z, _pp), _pp); return (qx, qy, qz); } /// @dev Multiply point (x, y, z) times d. /// @param _d scalar to multiply /// @param _x coordinate x of P1 /// @param _y coordinate y of P1 /// @param _z coordinate z of P1 /// @param _aa constant of curve /// @param _pp the modulus /// @return (qx, qy, qz) d*P1 in Jacobian function jacMul( uint256 _d, uint256 _x, uint256 _y, uint256 _z, uint256 _aa, uint256 _pp) internal pure returns (uint256, uint256, uint256) { uint256 remaining = _d; uint256[3] memory point; point[0] = _x; point[1] = _y; point[2] = _z; uint256 qx = 0; uint256 qy = 0; uint256 qz = 1; if (_d == 0) { return (qx, qy, qz); } // Double and add algorithm while (remaining != 0) { if ((remaining & 1) != 0) { (qx, qy, qz) = jacAdd( qx, qy, qz, point[0], point[1], point[2], _pp); } remaining = remaining / 2; (point[0], point[1], point[2]) = jacDouble( point[0], point[1], point[2], _aa, _pp); } return (qx, qy, qz); } } // File: vrf-solidity/contracts/VRF.sol /** * @title Verifiable Random Functions (VRF) * @notice Library verifying VRF proofs using the `Secp256k1` curve and the `SHA256` hash function. * @dev This library follows the algorithms described in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04) and [RFC6979](https://tools.ietf.org/html/rfc6979). * It supports the _SECP256K1_SHA256_TAI_ cipher suite, i.e. the aforementioned algorithms using `SHA256` and the `Secp256k1` curve. * @author Witnet Foundation */ library VRF { /** * Secp256k1 parameters */ // Generator coordinate `x` of the EC curve uint256 public constant GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; // Generator coordinate `y` of the EC curve uint256 public constant GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; // Constant `a` of EC equation uint256 public constant AA = 0; // Constant `b` of EC equation uint256 public constant BB = 7; // Prime number of the curve uint256 public constant PP = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; // Order of the curve uint256 public constant NN = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141; /// @dev Public key derivation from private key. /// @param _d The scalar /// @param _x The coordinate x /// @param _y The coordinate y /// @return (qx, qy) The derived point function derivePoint(uint256 _d, uint256 _x, uint256 _y) internal pure returns (uint256, uint256) { return EllipticCurve.ecMul( _d, _x, _y, AA, PP ); } /// @dev Function to derive the `y` coordinate given the `x` coordinate and the parity byte (`0x03` for odd `y` and `0x04` for even `y`). /// @param _yByte The parity byte following the ec point compressed format /// @param _x The coordinate `x` of the point /// @return The coordinate `y` of the point function deriveY(uint8 _yByte, uint256 _x) internal pure returns (uint256) { return EllipticCurve.deriveY( _yByte, _x, AA, BB, PP); } /// @dev Computes the VRF hash output as result of the digest of a ciphersuite-dependent prefix /// concatenated with the gamma point /// @param _gammaX The x-coordinate of the gamma EC point /// @param _gammaY The y-coordinate of the gamma EC point /// @return The VRF hash ouput as shas256 digest function gammaToHash(uint256 _gammaX, uint256 _gammaY) internal pure returns (bytes32) { bytes memory c = abi.encodePacked( // Cipher suite code (SECP256K1-SHA256-TAI is 0xFE) uint8(0xFE), // 0x01 uint8(0x03), // Compressed Gamma Point encodePoint(_gammaX, _gammaY)); return sha256(c); } /// @dev VRF verification by providing the public key, the message and the VRF proof. /// This function computes several elliptic curve operations which may lead to extensive gas consumption. /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]` /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]` /// @param _message The message (in bytes) used for computing the VRF /// @return true, if VRF proof is valid function verify(uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message) internal pure returns (bool) { // Step 2: Hash to try and increment (outputs a hashed value, a finite EC point in G) uint256[2] memory hPoint; (hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message); // Step 3: U = s*B - c*Y (where B is the generator) (uint256 uPointX, uint256 uPointY) = ecMulSubMul( _proof[3], GX, GY, _proof[2], _publicKey[0], _publicKey[1]); // Step 4: V = s*H - c*Gamma (uint256 vPointX, uint256 vPointY) = ecMulSubMul( _proof[3], hPoint[0], hPoint[1], _proof[2], _proof[0],_proof[1]); // Step 5: derived c from hash points(...) bytes16 derivedC = hashPoints( hPoint[0], hPoint[1], _proof[0], _proof[1], uPointX, uPointY, vPointX, vPointY); // Step 6: Check validity c == c' return uint128(derivedC) == _proof[2]; } /// @dev VRF fast verification by providing the public key, the message, the VRF proof and several intermediate elliptic curve points that enable the verification shortcut. /// This function leverages the EVM's `ecrecover` precompile to verify elliptic curve multiplications by decreasing the security from 32 to 20 bytes. /// Based on the original idea of Vitalik Buterin: https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9 /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]` /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]` /// @param _message The message (in bytes) used for computing the VRF /// @param _uPoint The `u` EC point defined as `U = s*B - c*Y` /// @param _vComponents The components required to compute `v` as `V = s*H - c*Gamma` /// @return true, if VRF proof is valid function fastVerify( uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message, uint256[2] memory _uPoint, uint256[4] memory _vComponents) internal pure returns (bool) { // Step 2: Hash to try and increment -> hashed value, a finite EC point in G uint256[2] memory hPoint; (hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message); // Step 3 & Step 4: // U = s*B - c*Y (where B is the generator) // V = s*H - c*Gamma if (!ecMulSubMulVerify( _proof[3], _proof[2], _publicKey[0], _publicKey[1], _uPoint[0], _uPoint[1]) || !ecMulVerify( _proof[3], hPoint[0], hPoint[1], _vComponents[0], _vComponents[1]) || !ecMulVerify( _proof[2], _proof[0], _proof[1], _vComponents[2], _vComponents[3]) ) { return false; } (uint256 vPointX, uint256 vPointY) = EllipticCurve.ecSub( _vComponents[0], _vComponents[1], _vComponents[2], _vComponents[3], AA, PP); // Step 5: derived c from hash points(...) bytes16 derivedC = hashPoints( hPoint[0], hPoint[1], _proof[0], _proof[1], _uPoint[0], _uPoint[1], vPointX, vPointY); // Step 6: Check validity c == c' return uint128(derivedC) == _proof[2]; } /// @dev Decode VRF proof from bytes /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]` /// @return The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]` function decodeProof(bytes memory _proof) internal pure returns (uint[4] memory) { require(_proof.length == 81, "Malformed VRF proof"); uint8 gammaSign; uint256 gammaX; uint128 c; uint256 s; assembly { gammaSign := mload(add(_proof, 1)) gammaX := mload(add(_proof, 33)) c := mload(add(_proof, 49)) s := mload(add(_proof, 81)) } uint256 gammaY = deriveY(gammaSign, gammaX); return [ gammaX, gammaY, c, s]; } /// @dev Decode EC point from bytes /// @param _point The EC point as bytes /// @return The point as `[point-x, point-y]` function decodePoint(bytes memory _point) internal pure returns (uint[2] memory) { require(_point.length == 33, "Malformed compressed EC point"); uint8 sign; uint256 x; assembly { sign := mload(add(_point, 1)) x := mload(add(_point, 33)) } uint256 y = deriveY(sign, x); return [x, y]; } /// @dev Compute the parameters (EC points) required for the VRF fast verification function. /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]` /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]` /// @param _message The message (in bytes) used for computing the VRF /// @return The fast verify required parameters as the tuple `([uPointX, uPointY], [sHX, sHY, cGammaX, cGammaY])` function computeFastVerifyParams(uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message) internal pure returns (uint256[2] memory, uint256[4] memory) { // Requirements for Step 3: U = s*B - c*Y (where B is the generator) uint256[2] memory hPoint; (hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message); (uint256 uPointX, uint256 uPointY) = ecMulSubMul( _proof[3], GX, GY, _proof[2], _publicKey[0], _publicKey[1]); // Requirements for Step 4: V = s*H - c*Gamma (uint256 sHX, uint256 sHY) = derivePoint(_proof[3], hPoint[0], hPoint[1]); (uint256 cGammaX, uint256 cGammaY) = derivePoint(_proof[2], _proof[0], _proof[1]); return ( [uPointX, uPointY], [ sHX, sHY, cGammaX, cGammaY ]); } /// @dev Function to convert a `Hash(PK|DATA)` to a point in the curve as defined in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04). /// Used in Step 2 of VRF verification function. /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]` /// @param _message The message used for computing the VRF /// @return The hash point in affine cooridnates function hashToTryAndIncrement(uint256[2] memory _publicKey, bytes memory _message) internal pure returns (uint, uint) { // Step 1: public key to bytes // Step 2: V = cipher_suite | 0x01 | public_key_bytes | message | ctr bytes memory c = abi.encodePacked( // Cipher suite code (SECP256K1-SHA256-TAI is 0xFE) uint8(254), // 0x01 uint8(1), // Public Key encodePoint(_publicKey[0], _publicKey[1]), // Message _message); // Step 3: find a valid EC point // Loop over counter ctr starting at 0x00 and do hash for (uint8 ctr = 0; ctr < 256; ctr++) { // Counter update // c[cLength-1] = byte(ctr); bytes32 sha = sha256(abi.encodePacked(c, ctr)); // Step 4: arbitraty string to point and check if it is on curve uint hPointX = uint256(sha); uint hPointY = deriveY(2, hPointX); if (EllipticCurve.isOnCurve( hPointX, hPointY, AA, BB, PP)) { // Step 5 (omitted): calculate H (cofactor is 1 on secp256k1) // If H is not "INVALID" and cofactor > 1, set H = cofactor * H return (hPointX, hPointY); } } revert("No valid point was found"); } /// @dev Function to hash a certain set of points as specified in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04). /// Used in Step 5 of VRF verification function. /// @param _hPointX The coordinate `x` of point `H` /// @param _hPointY The coordinate `y` of point `H` /// @param _gammaX The coordinate `x` of the point `Gamma` /// @param _gammaX The coordinate `y` of the point `Gamma` /// @param _uPointX The coordinate `x` of point `U` /// @param _uPointY The coordinate `y` of point `U` /// @param _vPointX The coordinate `x` of point `V` /// @param _vPointY The coordinate `y` of point `V` /// @return The first half of the digest of the points using SHA256 function hashPoints( uint256 _hPointX, uint256 _hPointY, uint256 _gammaX, uint256 _gammaY, uint256 _uPointX, uint256 _uPointY, uint256 _vPointX, uint256 _vPointY) internal pure returns (bytes16) { bytes memory c = abi.encodePacked( // Ciphersuite 0xFE uint8(254), // Prefix 0x02 uint8(2), // Points to Bytes encodePoint(_hPointX, _hPointY), encodePoint(_gammaX, _gammaY), encodePoint(_uPointX, _uPointY), encodePoint(_vPointX, _vPointY) ); // Hash bytes and truncate bytes32 sha = sha256(c); bytes16 half1; assembly { let freemem_pointer := mload(0x40) mstore(add(freemem_pointer,0x00), sha) half1 := mload(add(freemem_pointer,0x00)) } return half1; } /// @dev Encode an EC point to bytes /// @param _x The coordinate `x` of the point /// @param _y The coordinate `y` of the point /// @return The point coordinates as bytes function encodePoint(uint256 _x, uint256 _y) internal pure returns (bytes memory) { uint8 prefix = uint8(2 + (_y % 2)); return abi.encodePacked(prefix, _x); } /// @dev Substracts two key derivation functionsas `s1*A - s2*B`. /// @param _scalar1 The scalar `s1` /// @param _a1 The `x` coordinate of point `A` /// @param _a2 The `y` coordinate of point `A` /// @param _scalar2 The scalar `s2` /// @param _b1 The `x` coordinate of point `B` /// @param _b2 The `y` coordinate of point `B` /// @return The derived point in affine cooridnates function ecMulSubMul( uint256 _scalar1, uint256 _a1, uint256 _a2, uint256 _scalar2, uint256 _b1, uint256 _b2) internal pure returns (uint256, uint256) { (uint256 m1, uint256 m2) = derivePoint(_scalar1, _a1, _a2); (uint256 n1, uint256 n2) = derivePoint(_scalar2, _b1, _b2); (uint256 r1, uint256 r2) = EllipticCurve.ecSub( m1, m2, n1, n2, AA, PP); return (r1, r2); } /// @dev Verify an Elliptic Curve multiplication of the form `(qx,qy) = scalar*(x,y)` by using the precompiled `ecrecover` function. /// The usage of the precompiled `ecrecover` function decreases the security from 32 to 20 bytes. /// Based on the original idea of Vitalik Buterin: https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9 /// @param _scalar The scalar of the point multiplication /// @param _x The coordinate `x` of the point /// @param _y The coordinate `y` of the point /// @param _qx The coordinate `x` of the multiplication result /// @param _qy The coordinate `y` of the multiplication result /// @return true, if first 20 bytes match function ecMulVerify( uint256 _scalar, uint256 _x, uint256 _y, uint256 _qx, uint256 _qy) internal pure returns(bool) { address result = ecrecover( 0, _y % 2 != 0 ? 28 : 27, bytes32(_x), bytes32(mulmod(_scalar, _x, NN))); return pointToAddress(_qx, _qy) == result; } /// @dev Verify an Elliptic Curve operation of the form `Q = scalar1*(gx,gy) - scalar2*(x,y)` by using the precompiled `ecrecover` function, where `(gx,gy)` is the generator of the EC. /// The usage of the precompiled `ecrecover` function decreases the security from 32 to 20 bytes. /// Based on SolCrypto library: https://github.com/HarryR/solcrypto /// @param _scalar1 The scalar of the multiplication of `(gx,gy)` /// @param _scalar2 The scalar of the multiplication of `(x,y)` /// @param _x The coordinate `x` of the point to be mutiply by `scalar2` /// @param _y The coordinate `y` of the point to be mutiply by `scalar2` /// @param _qx The coordinate `x` of the equation result /// @param _qy The coordinate `y` of the equation result /// @return true, if first 20 bytes match function ecMulSubMulVerify( uint256 _scalar1, uint256 _scalar2, uint256 _x, uint256 _y, uint256 _qx, uint256 _qy) internal pure returns(bool) { uint256 scalar1 = (NN - _scalar1) % NN; scalar1 = mulmod(scalar1, _x, NN); uint256 scalar2 = (NN - _scalar2) % NN; address result = ecrecover( bytes32(scalar1), _y % 2 != 0 ? 28 : 27, bytes32(_x), bytes32(mulmod(scalar2, _x, NN))); return pointToAddress(_qx, _qy) == result; } /// @dev Gets the address corresponding to the EC point digest (keccak256), i.e. the first 20 bytes of the digest. /// This function is used for performing a fast EC multiplication verification. /// @param _x The coordinate `x` of the point /// @param _y The coordinate `y` of the point /// @return The address of the EC point digest (keccak256) function pointToAddress(uint256 _x, uint256 _y) internal pure returns(address) { return address(uint256(keccak256(abi.encodePacked(_x, _y))) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); } } // File: witnet-ethereum-bridge/contracts/ActiveBridgeSetLib.sol /** * @title Active Bridge Set (ABS) library * @notice This library counts the number of bridges that were active recently. */ library ActiveBridgeSetLib { // Number of Ethereum blocks during which identities can be pushed into a single activity slot uint8 public constant CLAIM_BLOCK_PERIOD = 8; // Number of activity slots in the ABS uint8 public constant ACTIVITY_LENGTH = 100; struct ActiveBridgeSet { // Mapping of activity slots with participating identities mapping (uint16 => address[]) epochIdentities; // Mapping of identities with their participation count mapping (address => uint16) identityCount; // Number of identities in the Active Bridge Set (consolidated during `ACTIVITY_LENGTH`) uint32 activeIdentities; // Number of identities for the next activity slot (to be updated in the next activity slot) uint32 nextActiveIdentities; // Last used block number during an activity update uint256 lastBlockNumber; } modifier validBlockNumber(uint256 _blockFromArguments, uint256 _blockFromContractState) { require (_blockFromArguments >= _blockFromContractState, "The provided block is older than the last updated block"); _; } /// @dev Updates activity in Witnet without requiring protocol participation. /// @param _abs The Active Bridge Set structure to be updated. /// @param _blockNumber The block number up to which the activity should be updated. function updateActivity(ActiveBridgeSet storage _abs, uint256 _blockNumber) internal validBlockNumber(_blockNumber, _abs.lastBlockNumber) { (uint16 currentSlot, uint16 lastSlot, bool overflow) = getSlots(_abs, _blockNumber); // Avoid gas cost if ABS is up to date require( updateABS( _abs, currentSlot, lastSlot, overflow ), "The ABS was already up to date"); _abs.lastBlockNumber = _blockNumber; } /// @dev Pushes activity updates through protocol activities (implying insertion of identity). /// @param _abs The Active Bridge Set structure to be updated. /// @param _address The address pushing the activity. /// @param _blockNumber The block number up to which the activity should be updated. function pushActivity(ActiveBridgeSet storage _abs, address _address, uint256 _blockNumber) internal validBlockNumber(_blockNumber, _abs.lastBlockNumber) returns (bool success) { (uint16 currentSlot, uint16 lastSlot, bool overflow) = getSlots(_abs, _blockNumber); // Update ABS and if it was already up to date, check if identities already counted if ( updateABS( _abs, currentSlot, lastSlot, overflow )) { _abs.lastBlockNumber = _blockNumber; } else { // Check if address was already counted as active identity in this current activity slot uint256 epochIdsLength = _abs.epochIdentities[currentSlot].length; for (uint256 i; i < epochIdsLength; i++) { if (_abs.epochIdentities[currentSlot][i] == _address) { return false; } } } // Update current activity slot with identity: // 1. Add currentSlot to `epochIdentities` with address // 2. If count = 0, increment by 1 `nextActiveIdentities` // 3. Increment by 1 the count of the identity _abs.epochIdentities[currentSlot].push(_address); if (_abs.identityCount[_address] == 0) { _abs.nextActiveIdentities++; } _abs.identityCount[_address]++; return true; } /// @dev Checks if an address is a member of the ABS. /// @param _abs The Active Bridge Set structure from the Witnet Requests Board. /// @param _address The address to check. /// @return true if address is member of ABS. function absMembership(ActiveBridgeSet storage _abs, address _address) internal view returns (bool) { return _abs.identityCount[_address] > 0; } /// @dev Gets the slots of the last block seen by the ABS provided and the block number provided. /// @param _abs The Active Bridge Set structure containing the last block. /// @param _blockNumber The block number from which to get the current slot. /// @return (currentSlot, lastSlot, overflow), where overflow implies the block difference &gt; CLAIM_BLOCK_PERIOD* ACTIVITY_LENGTH. function getSlots(ActiveBridgeSet storage _abs, uint256 _blockNumber) private view returns (uint8, uint8, bool) { // Get current activity slot number uint8 currentSlot = uint8((_blockNumber / CLAIM_BLOCK_PERIOD) % ACTIVITY_LENGTH); // Get last actitivy slot number uint8 lastSlot = uint8((_abs.lastBlockNumber / CLAIM_BLOCK_PERIOD) % ACTIVITY_LENGTH); // Check if there was an activity slot overflow // `ACTIVITY_LENGTH` is changed to `uint16` here to ensure the multiplication doesn't overflow silently bool overflow = (_blockNumber - _abs.lastBlockNumber) >= CLAIM_BLOCK_PERIOD * uint16(ACTIVITY_LENGTH); return (currentSlot, lastSlot, overflow); } /// @dev Updates the provided ABS according to the slots provided. /// @param _abs The Active Bridge Set to be updated. /// @param _currentSlot The current slot. /// @param _lastSlot The last slot seen by the ABS. /// @param _overflow Whether the current slot has overflown the last slot. /// @return True if update occurred. function updateABS( ActiveBridgeSet storage _abs, uint16 _currentSlot, uint16 _lastSlot, bool _overflow) private returns (bool) { // If there are more than `ACTIVITY_LENGTH` slots empty => remove entirely the ABS if (_overflow) { flushABS(_abs, _lastSlot, _lastSlot); // If ABS are not up to date => fill previous activity slots with empty activities } else if (_currentSlot != _lastSlot) { flushABS(_abs, _currentSlot, _lastSlot); } else { return false; } return true; } /// @dev Flushes the provided ABS record between lastSlot and currentSlot. /// @param _abs The Active Bridge Set to be flushed. /// @param _currentSlot The current slot. function flushABS(ActiveBridgeSet storage _abs, uint16 _currentSlot, uint16 _lastSlot) private { // For each slot elapsed, remove identities and update `nextActiveIdentities` count for (uint16 slot = (_lastSlot + 1) % ACTIVITY_LENGTH ; slot != _currentSlot ; slot = (slot + 1) % ACTIVITY_LENGTH) { flushSlot(_abs, slot); } // Update current activity slot flushSlot(_abs, _currentSlot); _abs.activeIdentities = _abs.nextActiveIdentities; } /// @dev Flushes a slot of the provided ABS. /// @param _abs The Active Bridge Set to be flushed. /// @param _slot The slot to be flushed. function flushSlot(ActiveBridgeSet storage _abs, uint16 _slot) private { // For a given slot, go through all identities to flush them uint256 epochIdsLength = _abs.epochIdentities[_slot].length; for (uint256 id = 0; id < epochIdsLength; id++) { flushIdentity(_abs, _abs.epochIdentities[_slot][id]); } delete _abs.epochIdentities[_slot]; } /// @dev Decrements the appearance counter of an identity from the provided ABS. If the counter reaches 0, the identity is flushed. /// @param _abs The Active Bridge Set to be flushed. /// @param _address The address to be flushed. function flushIdentity(ActiveBridgeSet storage _abs, address _address) private { require(absMembership(_abs, _address), "The identity address is already out of the ARS"); // Decrement the count of an identity, and if it reaches 0, delete it and update `nextActiveIdentities`count _abs.identityCount[_address]--; if (_abs.identityCount[_address] == 0) { delete _abs.identityCount[_address]; _abs.nextActiveIdentities--; } } } // File: witnet-ethereum-bridge/contracts/WitnetRequestsBoardInterface.sol /** * @title Witnet Requests Board Interface * @notice Interface of a Witnet Request Board (WRB) * It defines how to interact with the WRB in order to support: * - Post and upgrade a data request * - Read the result of a dr * @author Witnet Foundation */ interface WitnetRequestsBoardInterface { /// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value. /// @param _dr The bytes corresponding to the Protocol Buffers serialization of the data request output. /// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request. /// @return The unique identifier of the data request. function postDataRequest(bytes calldata _dr, uint256 _tallyReward) external payable returns(uint256); /// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward. /// @param _id The unique identifier of the data request. /// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward. function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable; /// @dev Retrieves the DR hash of the id from the WRB. /// @param _id The unique identifier of the data request. /// @return The hash of the DR function readDrHash (uint256 _id) external view returns(uint256); /// @dev Retrieves the result (if already available) of one data request from the WRB. /// @param _id The unique identifier of the data request. /// @return The result of the DR function readResult (uint256 _id) external view returns(bytes memory); /// @notice Verifies if the block relay can be upgraded. /// @return true if contract is upgradable. function isUpgradable(address _address) external view returns(bool); } // File: witnet-ethereum-bridge/contracts/WitnetRequestsBoard.sol /** * @title Witnet Requests Board * @notice Contract to bridge requests to Witnet. * @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network. * The result of the requests will be posted back to this contract by the bridge nodes too. * @author Witnet Foundation */ contract WitnetRequestsBoard is WitnetRequestsBoardInterface { using ActiveBridgeSetLib for ActiveBridgeSetLib.ActiveBridgeSet; // Expiration period after which a Witnet Request can be claimed again uint256 public constant CLAIM_EXPIRATION = 13; struct DataRequest { bytes dr; uint256 inclusionReward; uint256 tallyReward; bytes result; // Block number at which the DR was claimed for the last time uint256 blockNumber; uint256 drHash; address payable pkhClaim; } // Owner of the Witnet Request Board address public witnet; // Block Relay proxy prividing verification functions BlockRelayProxy public blockRelay; // Witnet Requests within the board DataRequest[] public requests; // Set of recently active bridges ActiveBridgeSetLib.ActiveBridgeSet public abs; // Replication factor for Active Bridge Set identities uint8 public repFactor; // Event emitted when a new DR is posted event PostedRequest(address indexed _from, uint256 _id); // Event emitted when a DR inclusion proof is posted event IncludedRequest(address indexed _from, uint256 _id); // Event emitted when a result proof is posted event PostedResult(address indexed _from, uint256 _id); // Ensures the reward is not greater than the value modifier payingEnough(uint256 _value, uint256 _tally) { require(_value >= _tally, "Transaction value needs to be equal or greater than tally reward"); _; } // Ensures the poe is valid modifier poeValid( uint256[4] memory _poe, uint256[2] memory _publicKey, uint256[2] memory _uPoint, uint256[4] memory _vPointHelpers) { require( verifyPoe( _poe, _publicKey, _uPoint, _vPointHelpers), "Not a valid PoE"); _; } // Ensures signature (sign(msg.sender)) is valid modifier validSignature( uint256[2] memory _publicKey, bytes memory addrSignature) { require(verifySig(abi.encodePacked(msg.sender), _publicKey, addrSignature), "Not a valid signature"); _; } // Ensures the DR inclusion proof has not been reported yet modifier drNotIncluded(uint256 _id) { require(requests[_id].drHash == 0, "DR already included"); _; } // Ensures the DR inclusion has been already reported modifier drIncluded(uint256 _id) { require(requests[_id].drHash != 0, "DR not yet included"); _; } // Ensures the result has not been reported yet modifier resultNotIncluded(uint256 _id) { require(requests[_id].result.length == 0, "Result already included"); _; } // Ensures the VRF is valid modifier vrfValid( uint256[4] memory _poe, uint256[2] memory _publicKey, uint256[2] memory _uPoint, uint256[4] memory _vPointHelpers) virtual { require( VRF.fastVerify( _publicKey, _poe, getLastBeacon(), _uPoint, _vPointHelpers), "Not a valid VRF"); _; } // Ensures the address belongs to the active bridge set modifier absMember(address _address) { require(abs.absMembership(_address), "Not a member of the ABS"); _; } /** * @notice Include an address to specify the Witnet Block Relay and a replication factor. * @param _blockRelayAddress BlockRelayProxy address. * @param _repFactor replication factor. */ constructor(address _blockRelayAddress, uint8 _repFactor) public { blockRelay = BlockRelayProxy(_blockRelayAddress); witnet = msg.sender; // Insert an empty request so as to initialize the requests array with length > 0 DataRequest memory request; requests.push(request); repFactor = _repFactor; } /// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value. /// @param _serialized The bytes corresponding to the Protocol Buffers serialization of the data request output. /// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request. /// @return The unique identifier of the data request. function postDataRequest(bytes calldata _serialized, uint256 _tallyReward) external payable payingEnough(msg.value, _tallyReward) override returns(uint256) { // The initial length of the `requests` array will become the ID of the request for everything related to the WRB uint256 id = requests.length; // Create a new `DataRequest` object and initialize all the non-default fields DataRequest memory request; request.dr = _serialized; request.inclusionReward = SafeMath.sub(msg.value, _tallyReward); request.tallyReward = _tallyReward; // Push the new request into the contract state requests.push(request); // Let observers know that a new request has been posted emit PostedRequest(msg.sender, id); return id; } /// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward. /// @param _id The unique identifier of the data request. /// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward. function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable payingEnough(msg.value, _tallyReward) resultNotIncluded(_id) override { if (requests[_id].drHash != 0) { require( msg.value == _tallyReward, "Txn value should equal result reward argument (request reward already paid)" ); requests[_id].tallyReward = SafeMath.add(requests[_id].tallyReward, _tallyReward); } else { requests[_id].inclusionReward = SafeMath.add(requests[_id].inclusionReward, msg.value - _tallyReward); requests[_id].tallyReward = SafeMath.add(requests[_id].tallyReward, _tallyReward); } } /// @dev Checks if the data requests from a list are claimable or not. /// @param _ids The list of data request identifiers to be checked. /// @return An array of booleans indicating if data requests are claimable or not. function checkDataRequestsClaimability(uint256[] calldata _ids) external view returns (bool[] memory) { uint256 idsLength = _ids.length; bool[] memory validIds = new bool[](idsLength); for (uint i = 0; i < idsLength; i++) { uint256 index = _ids[i]; validIds[i] = (dataRequestCanBeClaimed(requests[index])) && requests[index].drHash == 0 && index < requests.length && requests[index].result.length == 0; } return validIds; } /// @dev Presents a proof of inclusion to prove that the request was posted into Witnet so as to unlock the inclusion reward that was put aside for the claiming identity (public key hash). /// @param _id The unique identifier of the data request. /// @param _poi A proof of inclusion proving that the data request appears listed in one recent block in Witnet. /// @param _index The index in the merkle tree. /// @param _blockHash The hash of the block in which the data request was inserted. /// @param _epoch The epoch in which the blockHash was created. function reportDataRequestInclusion( uint256 _id, uint256[] calldata _poi, uint256 _index, uint256 _blockHash, uint256 _epoch) external drNotIncluded(_id) { // Check the data request has been claimed require(dataRequestCanBeClaimed(requests[_id]) == false, "Data Request has not yet been claimed"); uint256 drOutputHash = uint256(sha256(requests[_id].dr)); uint256 drHash = uint256(sha256(abi.encodePacked(drOutputHash, _poi[0]))); // Update the state upon which this function depends before the external call requests[_id].drHash = drHash; require( blockRelay.verifyDrPoi( _poi, _blockHash, _epoch, _index, drOutputHash), "Invalid PoI"); requests[_id].pkhClaim.transfer(requests[_id].inclusionReward); // Push requests[_id].pkhClaim to abs abs.pushActivity(requests[_id].pkhClaim, block.number); emit IncludedRequest(msg.sender, _id); } /// @dev Reports the result of a data request in Witnet. /// @param _id The unique identifier of the data request. /// @param _poi A proof of inclusion proving that the data in _result has been acknowledged by the Witnet network as being the final result for the data request by putting in a tally transaction inside a Witnet block. /// @param _index The position of the tally transaction in the tallies-only merkle tree in the Witnet block. /// @param _blockHash The hash of the block in which the result (tally) was inserted. /// @param _epoch The epoch in which the blockHash was created. /// @param _result The result itself as bytes. function reportResult( uint256 _id, uint256[] calldata _poi, uint256 _index, uint256 _blockHash, uint256 _epoch, bytes calldata _result) external drIncluded(_id) resultNotIncluded(_id) absMember(msg.sender) { // Ensures the result byes do not have zero length // This would not be a valid encoding with CBOR and could trigger a reentrancy attack require(_result.length != 0, "Result has zero length"); // Update the state upon which this function depends before the external call requests[_id].result = _result; uint256 resHash = uint256(sha256(abi.encodePacked(requests[_id].drHash, _result))); require( blockRelay.verifyTallyPoi( _poi, _blockHash, _epoch, _index, resHash), "Invalid PoI"); msg.sender.transfer(requests[_id].tallyReward); emit PostedResult(msg.sender, _id); } /// @dev Retrieves the bytes of the serialization of one data request from the WRB. /// @param _id The unique identifier of the data request. /// @return The result of the data request as bytes. function readDataRequest(uint256 _id) external view returns(bytes memory) { require(requests.length > _id, "Id not found"); return requests[_id].dr; } /// @dev Retrieves the result (if already available) of one data request from the WRB. /// @param _id The unique identifier of the data request. /// @return The result of the DR function readResult(uint256 _id) external view override returns(bytes memory) { require(requests.length > _id, "Id not found"); return requests[_id].result; } /// @dev Retrieves hash of the data request transaction in Witnet. /// @param _id The unique identifier of the data request. /// @return The hash of the DataRequest transaction in Witnet. function readDrHash(uint256 _id) external view override returns(uint256) { require(requests.length > _id, "Id not found"); return requests[_id].drHash; } /// @dev Returns the number of data requests in the WRB. /// @return the number of data requests in the WRB. function requestsCount() external view returns(uint256) { return requests.length; } /// @notice Wrapper around the decodeProof from VRF library. /// @dev Decode VRF proof from bytes. /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`. /// @return The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`. function decodeProof(bytes calldata _proof) external pure returns (uint[4] memory) { return VRF.decodeProof(_proof); } /// @notice Wrapper around the decodePoint from VRF library. /// @dev Decode EC point from bytes. /// @param _point The EC point as bytes. /// @return The point as `[point-x, point-y]`. function decodePoint(bytes calldata _point) external pure returns (uint[2] memory) { return VRF.decodePoint(_point); } /// @dev Wrapper around the computeFastVerifyParams from VRF library. /// @dev Compute the parameters (EC points) required for the VRF fast verification function.. /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`. /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`. /// @param _message The message (in bytes) used for computing the VRF. /// @return The fast verify required parameters as the tuple `([uPointX, uPointY], [sHX, sHY, cGammaX, cGammaY])`. function computeFastVerifyParams(uint256[2] calldata _publicKey, uint256[4] calldata _proof, bytes calldata _message) external pure returns (uint256[2] memory, uint256[4] memory) { return VRF.computeFastVerifyParams(_publicKey, _proof, _message); } /// @dev Updates the ABS activity with the block number provided. /// @param _blockNumber update the ABS until this block number. function updateAbsActivity(uint256 _blockNumber) external { require (_blockNumber <= block.number, "The provided block number has not been reached"); abs.updateActivity(_blockNumber); } /// @dev Verifies if the contract is upgradable. /// @return true if the contract upgradable. function isUpgradable(address _address) external view override returns(bool) { if (_address == witnet) { return true; } return false; } /// @dev Claim drs to be posted to Witnet by the node. /// @param _ids Data request ids to be claimed. /// @param _poe PoE claiming eligibility. /// @param _uPoint uPoint coordinates as [uPointX, uPointY] corresponding to U = s*B - c*Y. /// @param _vPointHelpers helpers for calculating the V point as [(s*H)X, (s*H)Y, cGammaX, cGammaY]. V = s*H + cGamma. function claimDataRequests( uint256[] memory _ids, uint256[4] memory _poe, uint256[2] memory _publicKey, uint256[2] memory _uPoint, uint256[4] memory _vPointHelpers, bytes memory addrSignature) public validSignature(_publicKey, addrSignature) poeValid(_poe,_publicKey, _uPoint,_vPointHelpers) returns(bool) { for (uint i = 0; i < _ids.length; i++) { require( dataRequestCanBeClaimed(requests[_ids[i]]), "One of the listed data requests was already claimed" ); requests[_ids[i]].pkhClaim = msg.sender; requests[_ids[i]].blockNumber = block.number; } return true; } /// @dev Read the beacon of the last block inserted. /// @return bytes to be signed by the node as PoE. function getLastBeacon() public view virtual returns(bytes memory) { return blockRelay.getLastBeacon(); } /// @dev Claim drs to be posted to Witnet by the node. /// @param _poe PoE claiming eligibility. /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`. /// @param _uPoint uPoint coordinates as [uPointX, uPointY] corresponding to U = s*B - c*Y. /// @param _vPointHelpers helpers for calculating the V point as [(s*H)X, (s*H)Y, cGammaX, cGammaY]. V = s*H + cGamma. function verifyPoe( uint256[4] memory _poe, uint256[2] memory _publicKey, uint256[2] memory _uPoint, uint256[4] memory _vPointHelpers) internal view vrfValid(_poe,_publicKey, _uPoint,_vPointHelpers) returns(bool) { uint256 vrf = uint256(VRF.gammaToHash(_poe[0], _poe[1])); // True if vrf/(2^{256} -1) <= repFactor/abs.activeIdentities if (abs.activeIdentities < repFactor) { return true; } // We rewrote it as vrf <= ((2^{256} -1)/abs.activeIdentities)*repFactor to gain efficiency if (vrf <= ((~uint256(0)/abs.activeIdentities)*repFactor)) { return true; } return false; } /// @dev Verifies the validity of a signature. /// @param _message message to be verified. /// @param _publicKey public key of the signer as `[pubKey-x, pubKey-y]`. /// @param _addrSignature the signature to verify asas r||s||v. /// @return true or false depending the validity. function verifySig( bytes memory _message, uint256[2] memory _publicKey, bytes memory _addrSignature) internal pure returns(bool) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_addrSignature, 0x20)) s := mload(add(_addrSignature, 0x40)) v := byte(0, mload(add(_addrSignature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return false; } if (v != 0 && v != 1) { return false; } v = 28 - v; bytes32 msgHash = sha256(_message); address hashedKey = VRF.pointToAddress(_publicKey[0], _publicKey[1]); return ecrecover( msgHash, v, r, s) == hashedKey; } function dataRequestCanBeClaimed(DataRequest memory _request) private view returns (bool) { return (_request.blockNumber == 0 || block.number - _request.blockNumber > CLAIM_EXPIRATION) && _request.drHash == 0 && _request.result.length == 0; } } // File: witnet-ethereum-bridge/contracts/WitnetRequestsBoardProxy.sol /** * @title Block Relay Proxy * @notice Contract to act as a proxy between the Witnet Bridge Interface and the Block Relay. * @author Witnet Foundation */ contract WitnetRequestsBoardProxy { // Address of the Witnet Request Board contract that is currently being used address public witnetRequestsBoardAddress; // Struct if the information of each controller struct ControllerInfo { // Address of the Controller address controllerAddress; // The lastId of the previous Controller uint256 lastId; } // Last id of the WRB controller uint256 internal currentLastId; // Instance of the current WitnetRequestBoard WitnetRequestsBoardInterface internal witnetRequestsBoardInstance; // Array with the controllers that have been used in the Proxy ControllerInfo[] internal controllers; modifier notIdentical(address _newAddress) { require(_newAddress != witnetRequestsBoardAddress, "The provided Witnet Requests Board instance address is already in use"); _; } /** * @notice Include an address to specify the Witnet Request Board. * @param _witnetRequestsBoardAddress WitnetRequestBoard address. */ constructor(address _witnetRequestsBoardAddress) public { // Initialize the first epoch pointing to the first controller controllers.push(ControllerInfo({controllerAddress: _witnetRequestsBoardAddress, lastId: 0})); witnetRequestsBoardAddress = _witnetRequestsBoardAddress; witnetRequestsBoardInstance = WitnetRequestsBoardInterface(_witnetRequestsBoardAddress); } /// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value. /// @param _dr The bytes corresponding to the Protocol Buffers serialization of the data request output. /// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request. /// @return The unique identifier of the data request. function postDataRequest(bytes calldata _dr, uint256 _tallyReward) external payable returns(uint256) { uint256 n = controllers.length; uint256 offset = controllers[n - 1].lastId; // Update the currentLastId with the id in the controller plus the offSet currentLastId = witnetRequestsBoardInstance.postDataRequest{value: msg.value}(_dr, _tallyReward) + offset; return currentLastId; } /// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward. /// @param _id The unique identifier of the data request. /// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward. function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable { address wrbAddress; uint256 wrbOffset; (wrbAddress, wrbOffset) = getController(_id); return witnetRequestsBoardInstance.upgradeDataRequest{value: msg.value}(_id - wrbOffset, _tallyReward); } /// @dev Retrieves the DR hash of the id from the WRB. /// @param _id The unique identifier of the data request. /// @return The hash of the DR. function readDrHash (uint256 _id) external view returns(uint256) { // Get the address and the offset of the corresponding to id address wrbAddress; uint256 offsetWrb; (wrbAddress, offsetWrb) = getController(_id); // Return the result of the DR readed in the corresponding Controller with its own id WitnetRequestsBoardInterface wrbWithDrHash; wrbWithDrHash = WitnetRequestsBoardInterface(wrbAddress); uint256 drHash = wrbWithDrHash.readDrHash(_id - offsetWrb); return drHash; } /// @dev Retrieves the result (if already available) of one data request from the WRB. /// @param _id The unique identifier of the data request. /// @return The result of the DR. function readResult(uint256 _id) external view returns(bytes memory) { // Get the address and the offset of the corresponding to id address wrbAddress; uint256 offSetWrb; (wrbAddress, offSetWrb) = getController(_id); // Return the result of the DR in the corresponding Controller with its own id WitnetRequestsBoardInterface wrbWithResult; wrbWithResult = WitnetRequestsBoardInterface(wrbAddress); return wrbWithResult.readResult(_id - offSetWrb); } /// @notice Upgrades the Witnet Requests Board if the current one is upgradeable. /// @param _newAddress address of the new block relay to upgrade. function upgradeWitnetRequestsBoard(address _newAddress) public notIdentical(_newAddress) { // Require the WRB is upgradable require(witnetRequestsBoardInstance.isUpgradable(msg.sender), "The upgrade has been rejected by the current implementation"); // Map the currentLastId to the corresponding witnetRequestsBoardAddress and add it to controllers controllers.push(ControllerInfo({controllerAddress: _newAddress, lastId: currentLastId})); // Upgrade the WRB witnetRequestsBoardAddress = _newAddress; witnetRequestsBoardInstance = WitnetRequestsBoardInterface(_newAddress); } /// @notice Gets the controller from an Id. /// @param _id id of a Data Request from which we get the controller. function getController(uint256 _id) internal view returns(address _controllerAddress, uint256 _offset) { // Check id is bigger than 0 require(_id > 0, "Non-existent controller for id 0"); uint256 n = controllers.length; // If the id is bigger than the lastId of a Controller, read the result in that Controller for (uint i = n; i > 0; i--) { if (_id > controllers[i - 1].lastId) { return (controllers[i - 1].controllerAddress, controllers[i - 1].lastId); } } } } // File: witnet-ethereum-bridge/contracts/BufferLib.sol /** * @title A convenient wrapper around the `bytes memory` type that exposes a buffer-like interface * @notice The buffer has an inner cursor that tracks the final offset of every read, i.e. any subsequent read will * start with the byte that goes right after the last one in the previous read. * @dev `uint32` is used here for `cursor` because `uint16` would only enable seeking up to 8KB, which could in some * theoretical use cases be exceeded. Conversely, `uint32` supports up to 512MB, which cannot credibly be exceeded. */ library BufferLib { struct Buffer { bytes data; uint32 cursor; } // Ensures we access an existing index in an array modifier notOutOfBounds(uint32 index, uint256 length) { require(index < length, "Tried to read from a consumed Buffer (must rewind it first)"); _; } /** * @notice Read and consume a certain amount of bytes from the buffer. * @param _buffer An instance of `BufferLib.Buffer`. * @param _length How many bytes to read and consume from the buffer. * @return A `bytes memory` containing the first `_length` bytes from the buffer, counting from the cursor position. */ function read(Buffer memory _buffer, uint32 _length) internal pure returns (bytes memory) { // Make sure not to read out of the bounds of the original bytes require(_buffer.cursor + _length <= _buffer.data.length, "Not enough bytes in buffer when reading"); // Create a new `bytes memory destination` value bytes memory destination = new bytes(_length); bytes memory source = _buffer.data; uint32 offset = _buffer.cursor; // Get raw pointers for source and destination uint sourcePointer; uint destinationPointer; assembly { sourcePointer := add(add(source, 32), offset) destinationPointer := add(destination, 32) } // Copy `_length` bytes from source to destination memcpy(destinationPointer, sourcePointer, uint(_length)); // Move the cursor forward by `_length` bytes seek(_buffer, _length, true); return destination; } /** * @notice Read and consume the next byte from the buffer. * @param _buffer An instance of `BufferLib.Buffer`. * @return The next byte in the buffer counting from the cursor position. */ function next(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (byte) { // Return the byte at the position marked by the cursor and advance the cursor all at once return _buffer.data[_buffer.cursor++]; } /** * @notice Move the inner cursor of the buffer to a relative or absolute position. * @param _buffer An instance of `BufferLib.Buffer`. * @param _offset How many bytes to move the cursor forward. * @param _relative Whether to count `_offset` from the last position of the cursor (`true`) or the beginning of the * buffer (`true`). * @return The final position of the cursor (will equal `_offset` if `_relative` is `false`). */ // solium-disable-next-line security/no-assign-params function seek(Buffer memory _buffer, uint32 _offset, bool _relative) internal pure returns (uint32) { // Deal with relative offsets if (_relative) { require(_offset + _buffer.cursor > _offset, "Integer overflow when seeking"); _offset += _buffer.cursor; } // Make sure not to read out of the bounds of the original bytes require(_offset <= _buffer.data.length, "Not enough bytes in buffer when seeking"); _buffer.cursor = _offset; return _buffer.cursor; } /** * @notice Move the inner cursor a number of bytes forward. * @dev This is a simple wrapper around the relative offset case of `seek()`. * @param _buffer An instance of `BufferLib.Buffer`. * @param _relativeOffset How many bytes to move the cursor forward. * @return The final position of the cursor. */ function seek(Buffer memory _buffer, uint32 _relativeOffset) internal pure returns (uint32) { return seek(_buffer, _relativeOffset, true); } /** * @notice Move the inner cursor back to the first byte in the buffer. * @param _buffer An instance of `BufferLib.Buffer`. */ function rewind(Buffer memory _buffer) internal pure { _buffer.cursor = 0; } /** * @notice Read and consume the next byte from the buffer as an `uint8`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint8` value of the next byte in the buffer counting from the cursor position. */ function readUint8(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (uint8) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint8 value; assembly { value := mload(add(add(bytesValue, 1), offset)) } _buffer.cursor++; return value; } /** * @notice Read and consume the next 2 bytes from the buffer as an `uint16`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint16` value of the next 2 bytes in the buffer counting from the cursor position. */ function readUint16(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 1, _buffer.data.length) returns (uint16) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint16 value; assembly { value := mload(add(add(bytesValue, 2), offset)) } _buffer.cursor += 2; return value; } /** * @notice Read and consume the next 4 bytes from the buffer as an `uint32`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position. */ function readUint32(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 3, _buffer.data.length) returns (uint32) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint32 value; assembly { value := mload(add(add(bytesValue, 4), offset)) } _buffer.cursor += 4; return value; } /** * @notice Read and consume the next 8 bytes from the buffer as an `uint64`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint64` value of the next 8 bytes in the buffer counting from the cursor position. */ function readUint64(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 7, _buffer.data.length) returns (uint64) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint64 value; assembly { value := mload(add(add(bytesValue, 8), offset)) } _buffer.cursor += 8; return value; } /** * @notice Read and consume the next 16 bytes from the buffer as an `uint128`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint128` value of the next 16 bytes in the buffer counting from the cursor position. */ function readUint128(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 15, _buffer.data.length) returns (uint128) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint128 value; assembly { value := mload(add(add(bytesValue, 16), offset)) } _buffer.cursor += 16; return value; } /** * @notice Read and consume the next 32 bytes from the buffer as an `uint256`. * @return The `uint256` value of the next 32 bytes in the buffer counting from the cursor position. * @param _buffer An instance of `BufferLib.Buffer`. */ function readUint256(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 31, _buffer.data.length) returns (uint256) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint256 value; assembly { value := mload(add(add(bytesValue, 32), offset)) } _buffer.cursor += 32; return value; } /** * @notice Read and consume the next 2 bytes from the buffer as an IEEE 754-2008 floating point number enclosed in an * `int32`. * @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values * by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `float16` * use cases. In other words, the integer output of this method is 10,000 times the actual value. The input bytes are * expected to follow the 16-bit base-2 format (a.k.a. `binary16`) in the IEEE 754-2008 standard. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position. */ function readFloat16(Buffer memory _buffer) internal pure returns (int32) { uint32 bytesValue = readUint16(_buffer); // Get bit at position 0 uint32 sign = bytesValue & 0x8000; // Get bits 1 to 5, then normalize to the [-14, 15] range so as to counterweight the IEEE 754 exponent bias int32 exponent = (int32(bytesValue & 0x7c00) >> 10) - 15; // Get bits 6 to 15 int32 significand = int32(bytesValue & 0x03ff); // Add 1024 to the fraction if the exponent is 0 if (exponent == 15) { significand |= 0x400; } // Compute `2 ^ exponent · (1 + fraction / 1024)` int32 result = 0; if (exponent >= 0) { result = int32(((1 << uint256(exponent)) * 10000 * (uint256(significand) | 0x400)) >> 10); } else { result = int32((((uint256(significand) | 0x400) * 10000) / (1 << uint256(- exponent))) >> 10); } // Make the result negative if the sign bit is not 0 if (sign != 0) { result *= - 1; } return result; } /** * @notice Copy bytes from one memory address into another. * @dev This function was borrowed from Nick Johnson's `solidity-stringutils` lib, and reproduced here under the terms * of [Apache License 2.0](https://github.com/Arachnid/solidity-stringutils/blob/master/LICENSE). * @param _dest Address of the destination memory. * @param _src Address to the source memory. * @param _len How many bytes to copy. */ // solium-disable-next-line security/no-assign-params function memcpy(uint _dest, uint _src, uint _len) private pure { // Copy word-length chunks while possible for (; _len >= 32; _len -= 32) { assembly { mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - _len) - 1; assembly { let srcpart := and(mload(_src), not(mask)) let destpart := and(mload(_dest), mask) mstore(_dest, or(destpart, srcpart)) } } } // File: witnet-ethereum-bridge/contracts/CBOR.sol /** * @title A minimalistic implementation of “RFC 7049 Concise Binary Object Representation” * @notice This library leverages a buffer-like structure for step-by-step decoding of bytes so as to minimize * the gas cost of decoding them into a useful native type. * @dev Most of the logic has been borrowed from Patrick Gansterer’s cbor.js library: https://github.com/paroga/cbor-js * TODO: add support for Array (majorType = 4) * TODO: add support for Map (majorType = 5) * TODO: add support for Float32 (majorType = 7, additionalInformation = 26) * TODO: add support for Float64 (majorType = 7, additionalInformation = 27) */ library CBOR { using BufferLib for BufferLib.Buffer; uint64 constant internal UINT64_MAX = ~uint64(0); struct Value { BufferLib.Buffer buffer; uint8 initialByte; uint8 majorType; uint8 additionalInformation; uint64 len; uint64 tag; } /** * @notice Decode a `CBOR.Value` structure into a native `bytes` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as a `bytes` value. */ function decodeBytes(Value memory _cborValue) public pure returns(bytes memory) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); if (_cborValue.len == UINT64_MAX) { bytes memory bytesData; // These checks look repetitive but the equivalent loop would be more expensive. uint32 itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType)); if (itemLength < UINT64_MAX) { bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength)); itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType)); if (itemLength < UINT64_MAX) { bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength)); } } return bytesData; } else { return _cborValue.buffer.read(uint32(_cborValue.len)); } } /** * @notice Decode a `CBOR.Value` structure into a `fixed16` value. * @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values * by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16` * use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128` value. */ function decodeFixed16(Value memory _cborValue) public pure returns(int32) { require(_cborValue.majorType == 7, "Tried to read a `fixed` value from a `CBOR.Value` with majorType != 7"); require(_cborValue.additionalInformation == 25, "Tried to read `fixed16` from a `CBOR.Value` with additionalInformation != 25"); return _cborValue.buffer.readFloat16(); } /** * @notice Decode a `CBOR.Value` structure into a native `int128[]` value whose inner values follow the same convention. * as explained in `decodeFixed16`. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128[]` value. */ function decodeFixed16Array(Value memory _cborValue) public pure returns(int128[] memory) { require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); int128[] memory array = new int128[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeFixed16(item); } return array; } /** * @notice Decode a `CBOR.Value` structure into a native `int128` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128` value. */ function decodeInt128(Value memory _cborValue) public pure returns(int128) { if (_cborValue.majorType == 1) { uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); return int128(-1) - int128(length); } else if (_cborValue.majorType == 0) { // Any `uint64` can be safely casted to `int128`, so this method supports majorType 1 as well so as to have offer // a uniform API for positive and negative numbers return int128(decodeUint64(_cborValue)); } revert("Tried to read `int128` from a `CBOR.Value` with majorType not 0 or 1"); } /** * @notice Decode a `CBOR.Value` structure into a native `int128[]` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128[]` value. */ function decodeInt128Array(Value memory _cborValue) public pure returns(int128[] memory) { require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); int128[] memory array = new int128[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeInt128(item); } return array; } /** * @notice Decode a `CBOR.Value` structure into a native `string` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as a `string` value. */ function decodeString(Value memory _cborValue) public pure returns(string memory) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); if (_cborValue.len == UINT64_MAX) { bytes memory textData; bool done; while (!done) { uint64 itemLength = readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType); if (itemLength < UINT64_MAX) { textData = abi.encodePacked(textData, readText(_cborValue.buffer, itemLength / 4)); } else { done = true; } } return string(textData); } else { return string(readText(_cborValue.buffer, _cborValue.len)); } } /** * @notice Decode a `CBOR.Value` structure into a native `string[]` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `string[]` value. */ function decodeStringArray(Value memory _cborValue) public pure returns(string[] memory) { require(_cborValue.majorType == 4, "Tried to read `string[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); string[] memory array = new string[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeString(item); } return array; } /** * @notice Decode a `CBOR.Value` structure into a native `uint64` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `uint64` value. */ function decodeUint64(Value memory _cborValue) public pure returns(uint64) { require(_cborValue.majorType == 0, "Tried to read `uint64` from a `CBOR.Value` with majorType != 0"); return readLength(_cborValue.buffer, _cborValue.additionalInformation); } /** * @notice Decode a `CBOR.Value` structure into a native `uint64[]` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `uint64[]` value. */ function decodeUint64Array(Value memory _cborValue) public pure returns(uint64[] memory) { require(_cborValue.majorType == 4, "Tried to read `uint64[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); uint64[] memory array = new uint64[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeUint64(item); } return array; } /** * @notice Decode a CBOR.Value structure from raw bytes. * @dev This is the main factory for CBOR.Value instances, which can be later decoded into native EVM types. * @param _cborBytes Raw bytes representing a CBOR-encoded value. * @return A `CBOR.Value` instance containing a partially decoded value. */ function valueFromBytes(bytes memory _cborBytes) public pure returns(Value memory) { BufferLib.Buffer memory buffer = BufferLib.Buffer(_cborBytes, 0); return valueFromBuffer(buffer); } /** * @notice Decode a CBOR.Value structure from raw bytes. * @dev This is an alternate factory for CBOR.Value instances, which can be later decoded into native EVM types. * @param _buffer A Buffer structure representing a CBOR-encoded value. * @return A `CBOR.Value` instance containing a partially decoded value. */ function valueFromBuffer(BufferLib.Buffer memory _buffer) public pure returns(Value memory) { require(_buffer.data.length > 0, "Found empty buffer when parsing CBOR value"); uint8 initialByte; uint8 majorType = 255; uint8 additionalInformation; uint64 length; uint64 tag = UINT64_MAX; bool isTagged = true; while (isTagged) { // Extract basic CBOR properties from input bytes initialByte = _buffer.readUint8(); majorType = initialByte >> 5; additionalInformation = initialByte & 0x1f; // Early CBOR tag parsing. if (majorType == 6) { tag = readLength(_buffer, additionalInformation); } else { isTagged = false; } } require(majorType <= 7, "Invalid CBOR major type"); return CBOR.Value( _buffer, initialByte, majorType, additionalInformation, length, tag); } // Reads the length of the next CBOR item from a buffer, consuming a different number of bytes depending on the // value of the `additionalInformation` argument. function readLength(BufferLib.Buffer memory _buffer, uint8 additionalInformation) private pure returns(uint64) { if (additionalInformation < 24) { return additionalInformation; } if (additionalInformation == 24) { return _buffer.readUint8(); } if (additionalInformation == 25) { return _buffer.readUint16(); } if (additionalInformation == 26) { return _buffer.readUint32(); } if (additionalInformation == 27) { return _buffer.readUint64(); } if (additionalInformation == 31) { return UINT64_MAX; } revert("Invalid length encoding (non-existent additionalInformation value)"); } // Read the length of a CBOR indifinite-length item (arrays, maps, byte strings and text) from a buffer, consuming // as many bytes as specified by the first byte. function readIndefiniteStringLength(BufferLib.Buffer memory _buffer, uint8 majorType) private pure returns(uint64) { uint8 initialByte = _buffer.readUint8(); if (initialByte == 0xff) { return UINT64_MAX; } uint64 length = readLength(_buffer, initialByte & 0x1f); require(length < UINT64_MAX && (initialByte >> 5) == majorType, "Invalid indefinite length"); return length; } // Read a text string of a given length from a buffer. Returns a `bytes memory` value for the sake of genericness, // but it can be easily casted into a string with `string(result)`. // solium-disable-next-line security/no-assign-params function readText(BufferLib.Buffer memory _buffer, uint64 _length) private pure returns(bytes memory) { bytes memory result; for (uint64 index = 0; index < _length; index++) { uint8 value = _buffer.readUint8(); if (value & 0x80 != 0) { if (value < 0xe0) { value = (value & 0x1f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 1; } else if (value < 0xf0) { value = (value & 0x0f) << 12 | (_buffer.readUint8() & 0x3f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 2; } else { value = (value & 0x0f) << 18 | (_buffer.readUint8() & 0x3f) << 12 | (_buffer.readUint8() & 0x3f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 3; } } result = abi.encodePacked(result, value); } return result; } } // File: witnet-ethereum-bridge/contracts/Witnet.sol /** * @title A library for decoding Witnet request results * @notice The library exposes functions to check the Witnet request success. * and retrieve Witnet results from CBOR values into solidity types. */ library Witnet { using CBOR for CBOR.Value; /* STRUCTS */ struct Result { bool success; CBOR.Value cborValue; } /* ENUMS */ enum ErrorCodes { // 0x00: Unknown error. Something went really bad! Unknown, // Script format errors /// 0x01: At least one of the source scripts is not a valid CBOR-encoded value. SourceScriptNotCBOR, /// 0x02: The CBOR value decoded from a source script is not an Array. SourceScriptNotArray, /// 0x03: The Array value decoded form a source script is not a valid RADON script. SourceScriptNotRADON, /// Unallocated ScriptFormat0x04, ScriptFormat0x05, ScriptFormat0x06, ScriptFormat0x07, ScriptFormat0x08, ScriptFormat0x09, ScriptFormat0x0A, ScriptFormat0x0B, ScriptFormat0x0C, ScriptFormat0x0D, ScriptFormat0x0E, ScriptFormat0x0F, // Complexity errors /// 0x10: The request contains too many sources. RequestTooManySources, /// 0x11: The script contains too many calls. ScriptTooManyCalls, /// Unallocated Complexity0x12, Complexity0x13, Complexity0x14, Complexity0x15, Complexity0x16, Complexity0x17, Complexity0x18, Complexity0x19, Complexity0x1A, Complexity0x1B, Complexity0x1C, Complexity0x1D, Complexity0x1E, Complexity0x1F, // Operator errors /// 0x20: The operator does not exist. UnsupportedOperator, /// Unallocated Operator0x21, Operator0x22, Operator0x23, Operator0x24, Operator0x25, Operator0x26, Operator0x27, Operator0x28, Operator0x29, Operator0x2A, Operator0x2B, Operator0x2C, Operator0x2D, Operator0x2E, Operator0x2F, // Retrieval-specific errors /// 0x30: At least one of the sources could not be retrieved, but returned HTTP error. HTTP, /// 0x31: Retrieval of at least one of the sources timed out. RetrievalTimeout, /// Unallocated Retrieval0x32, Retrieval0x33, Retrieval0x34, Retrieval0x35, Retrieval0x36, Retrieval0x37, Retrieval0x38, Retrieval0x39, Retrieval0x3A, Retrieval0x3B, Retrieval0x3C, Retrieval0x3D, Retrieval0x3E, Retrieval0x3F, // Math errors /// 0x40: Math operator caused an underflow. Underflow, /// 0x41: Math operator caused an overflow. Overflow, /// 0x42: Tried to divide by zero. DivisionByZero, Size } /* Result impl's */ /** * @notice Decode raw CBOR bytes into a Result instance. * @param _cborBytes Raw bytes representing a CBOR-encoded value. * @return A `Result` instance. */ function resultFromCborBytes(bytes calldata _cborBytes) external pure returns(Result memory) { CBOR.Value memory cborValue = CBOR.valueFromBytes(_cborBytes); return resultFromCborValue(cborValue); } /** * @notice Decode a CBOR value into a Result instance. * @param _cborValue An instance of `CBOR.Value`. * @return A `Result` instance. */ function resultFromCborValue(CBOR.Value memory _cborValue) public pure returns(Result memory) { // Witnet uses CBOR tag 39 to represent RADON error code identifiers. // [CBOR tag 39] Identifiers for CBOR: https://github.com/lucas-clemente/cbor-specs/blob/master/id.md bool success = _cborValue.tag != 39; return Result(success, _cborValue); } /** * @notice Tell if a Result is successful. * @param _result An instance of Result. * @return `true` if successful, `false` if errored. */ function isOk(Result memory _result) public pure returns(bool) { return _result.success; } /** * @notice Tell if a Result is errored. * @param _result An instance of Result. * @return `true` if errored, `false` if successful. */ function isError(Result memory _result) public pure returns(bool) { return !_result.success; } /** * @notice Decode a bytes value from a Result as a `bytes` value. * @param _result An instance of Result. * @return The `bytes` decoded from the Result. */ function asBytes(Result memory _result) public pure returns(bytes memory) { require(_result.success, "Tried to read bytes value from errored Result"); return _result.cborValue.decodeBytes(); } /** * @notice Decode an error code from a Result as a member of `ErrorCodes`. * @param _result An instance of `Result`. * @return The `CBORValue.Error memory` decoded from the Result. */ function asErrorCode(Result memory _result) public pure returns(ErrorCodes) { uint64[] memory error = asRawError(_result); return supportedErrorOrElseUnknown(error[0]); } /** * @notice Generate a suitable error message for a member of `ErrorCodes` and its corresponding arguments. * @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function * @param _result An instance of `Result`. * @return A tuple containing the `CBORValue.Error memory` decoded from the `Result`, plus a loggable error message. */ function asErrorMessage(Result memory _result) public pure returns(ErrorCodes, string memory) { uint64[] memory error = asRawError(_result); ErrorCodes errorCode = supportedErrorOrElseUnknown(error[0]); bytes memory errorMessage; if (errorCode == ErrorCodes.SourceScriptNotCBOR) { errorMessage = abi.encodePacked("Source script #", utoa(error[1]), " was not a valid CBOR value"); } else if (errorCode == ErrorCodes.SourceScriptNotArray) { errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not an Array of calls"); } else if (errorCode == ErrorCodes.SourceScriptNotRADON) { errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not a valid RADON script"); } else if (errorCode == ErrorCodes.RequestTooManySources) { errorMessage = abi.encodePacked("The request contained too many sources (", utoa(error[1]), ")"); } else if (errorCode == ErrorCodes.ScriptTooManyCalls) { errorMessage = abi.encodePacked( "Script #", utoa(error[2]), " from the ", stageName(error[1]), " stage contained too many calls (", utoa(error[3]), ")" ); } else if (errorCode == ErrorCodes.UnsupportedOperator) { errorMessage = abi.encodePacked( "Operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage is not supported" ); } else if (errorCode == ErrorCodes.HTTP) { errorMessage = abi.encodePacked( "Source #", utoa(error[1]), " could not be retrieved. Failed with HTTP error code: ", utoa(error[2] / 100), utoa(error[2] % 100 / 10), utoa(error[2] % 10) ); } else if (errorCode == ErrorCodes.RetrievalTimeout) { errorMessage = abi.encodePacked( "Source #", utoa(error[1]), " could not be retrieved because of a timeout." ); } else if (errorCode == ErrorCodes.Underflow) { errorMessage = abi.encodePacked( "Underflow at operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else if (errorCode == ErrorCodes.Overflow) { errorMessage = abi.encodePacked( "Overflow at operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else if (errorCode == ErrorCodes.DivisionByZero) { errorMessage = abi.encodePacked( "Division by zero at operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else { errorMessage = abi.encodePacked("Unknown error (0x", utohex(error[0]), ")"); } return (errorCode, string(errorMessage)); } /** * @notice Decode a raw error from a `Result` as a `uint64[]`. * @param _result An instance of `Result`. * @return The `uint64[]` raw error as decoded from the `Result`. */ function asRawError(Result memory _result) public pure returns(uint64[] memory) { require(!_result.success, "Tried to read error code from successful Result"); return _result.cborValue.decodeUint64Array(); } /** * @notice Decode a fixed16 (half-precision) numeric value from a Result as an `int32` value. * @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values. * by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`. * use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. * @param _result An instance of Result. * @return The `int128` decoded from the Result. */ function asFixed16(Result memory _result) public pure returns(int32) { require(_result.success, "Tried to read `fixed16` value from errored Result"); return _result.cborValue.decodeFixed16(); } /** * @notice Decode an array of fixed16 values from a Result as an `int128[]` value. * @param _result An instance of Result. * @return The `int128[]` decoded from the Result. */ function asFixed16Array(Result memory _result) public pure returns(int128[] memory) { require(_result.success, "Tried to read `fixed16[]` value from errored Result"); return _result.cborValue.decodeFixed16Array(); } /** * @notice Decode a integer numeric value from a Result as an `int128` value. * @param _result An instance of Result. * @return The `int128` decoded from the Result. */ function asInt128(Result memory _result) public pure returns(int128) { require(_result.success, "Tried to read `int128` value from errored Result"); return _result.cborValue.decodeInt128(); } /** * @notice Decode an array of integer numeric values from a Result as an `int128[]` value. * @param _result An instance of Result. * @return The `int128[]` decoded from the Result. */ function asInt128Array(Result memory _result) public pure returns(int128[] memory) { require(_result.success, "Tried to read `int128[]` value from errored Result"); return _result.cborValue.decodeInt128Array(); } /** * @notice Decode a string value from a Result as a `string` value. * @param _result An instance of Result. * @return The `string` decoded from the Result. */ function asString(Result memory _result) public pure returns(string memory) { require(_result.success, "Tried to read `string` value from errored Result"); return _result.cborValue.decodeString(); } /** * @notice Decode an array of string values from a Result as a `string[]` value. * @param _result An instance of Result. * @return The `string[]` decoded from the Result. */ function asStringArray(Result memory _result) public pure returns(string[] memory) { require(_result.success, "Tried to read `string[]` value from errored Result"); return _result.cborValue.decodeStringArray(); } /** * @notice Decode a natural numeric value from a Result as a `uint64` value. * @param _result An instance of Result. * @return The `uint64` decoded from the Result. */ function asUint64(Result memory _result) public pure returns(uint64) { require(_result.success, "Tried to read `uint64` value from errored Result"); return _result.cborValue.decodeUint64(); } /** * @notice Decode an array of natural numeric values from a Result as a `uint64[]` value. * @param _result An instance of Result. * @return The `uint64[]` decoded from the Result. */ function asUint64Array(Result memory _result) public pure returns(uint64[] memory) { require(_result.success, "Tried to read `uint64[]` value from errored Result"); return _result.cborValue.decodeUint64Array(); } /** * @notice Convert a stage index number into the name of the matching Witnet request stage. * @param _stageIndex A `uint64` identifying the index of one of the Witnet request stages. * @return The name of the matching stage. */ function stageName(uint64 _stageIndex) public pure returns(string memory) { if (_stageIndex == 0) { return "retrieval"; } else if (_stageIndex == 1) { return "aggregation"; } else if (_stageIndex == 2) { return "tally"; } else { return "unknown"; } } /** * @notice Get an `ErrorCodes` item from its `uint64` discriminant, or default to `ErrorCodes.Unknown` if it doesn't * exist. * @param _discriminant The numeric identifier of an error. * @return A member of `ErrorCodes`. */ function supportedErrorOrElseUnknown(uint64 _discriminant) private pure returns(ErrorCodes) { if (_discriminant < uint8(ErrorCodes.Size)) { return ErrorCodes(_discriminant); } else { return ErrorCodes.Unknown; } } /** * @notice Convert a `uint64` into a 1, 2 or 3 characters long `string` representing its. * three less significant decimal values. * @param _u A `uint64` value. * @return The `string` representing its decimal value. */ function utoa(uint64 _u) private pure returns(string memory) { if (_u < 10) { bytes memory b1 = new bytes(1); b1[0] = byte(uint8(_u) + 48); return string(b1); } else if (_u < 100) { bytes memory b2 = new bytes(2); b2[0] = byte(uint8(_u / 10) + 48); b2[1] = byte(uint8(_u % 10) + 48); return string(b2); } else { bytes memory b3 = new bytes(3); b3[0] = byte(uint8(_u / 100) + 48); b3[1] = byte(uint8(_u % 100 / 10) + 48); b3[2] = byte(uint8(_u % 10) + 48); return string(b3); } } /** * @notice Convert a `uint64` into a 2 characters long `string` representing its two less significant hexadecimal values. * @param _u A `uint64` value. * @return The `string` representing its hexadecimal value. */ function utohex(uint64 _u) private pure returns(string memory) { bytes memory b2 = new bytes(2); uint8 d0 = uint8(_u / 16) + 48; uint8 d1 = uint8(_u % 16) + 48; if (d0 > 57) d0 += 7; if (d1 > 57) d1 += 7; b2[0] = byte(d0); b2[1] = byte(d1); return string(b2); } } // File: witnet-ethereum-bridge/contracts/Request.sol /** * @title The serialized form of a Witnet data request */ contract Request { bytes public bytecode; uint256 public id; /** * @dev A `Request` is constructed around a `bytes memory` value containing a well-formed Witnet data request serialized * using Protocol Buffers. However, we cannot verify its validity at this point. This implies that contracts using * the WRB should not be considered trustless before a valid Proof-of-Inclusion has been posted for the requests. * The hash of the request is computed in the constructor to guarantee consistency. Otherwise there could be a * mismatch and a data request could be resolved with the result of another. * @param _bytecode Witnet request in bytes. */ constructor(bytes memory _bytecode) public { bytecode = _bytecode; id = uint256(sha256(_bytecode)); } } // File: witnet-ethereum-bridge/contracts/UsingWitnet.sol /** * @title The UsingWitnet contract * @notice Contract writers can inherit this contract in order to create requests for the * Witnet network. */ contract UsingWitnet { using Witnet for Witnet.Result; WitnetRequestsBoardProxy internal wrb; /** * @notice Include an address to specify the WitnetRequestsBoard. * @param _wrb WitnetRequestsBoard address. */ constructor(address _wrb) public { wrb = WitnetRequestsBoardProxy(_wrb); } // Provides a convenient way for client contracts extending this to block the execution of the main logic of the // contract until a particular request has been successfully accepted into Witnet modifier witnetRequestAccepted(uint256 _id) { require(witnetCheckRequestAccepted(_id), "Witnet request is not yet accepted into the Witnet network"); _; } // Ensures that user-specified rewards are equal to the total transaction value to prevent users from burning any excess value modifier validRewards(uint256 _requestReward, uint256 _resultReward) { require(_requestReward + _resultReward >= _requestReward, "The sum of rewards overflows"); require(msg.value == _requestReward + _resultReward, "Transaction value should equal the sum of rewards"); _; } /** * @notice Send a new request to the Witnet network * @dev Call to `post_dr` function in the WitnetRequestsBoard contract * @param _request An instance of the `Request` contract * @param _requestReward Reward specified for the user which posts the request into Witnet * @param _resultReward Reward specified for the user which posts back the request result * @return Sequencial identifier for the request included in the WitnetRequestsBoard */ function witnetPostRequest(Request _request, uint256 _requestReward, uint256 _resultReward) internal validRewards(_requestReward, _resultReward) returns (uint256) { return wrb.postDataRequest.value(_requestReward + _resultReward)(_request.bytecode(), _resultReward); } /** * @notice Check if a request has been accepted into Witnet. * @dev Contracts depending on Witnet should not start their main business logic (e.g. receiving value from third. * parties) before this method returns `true`. * @param _id The sequential identifier of a request that has been previously sent to the WitnetRequestsBoard. * @return A boolean telling if the request has been already accepted or not. `false` do not mean rejection, though. */ function witnetCheckRequestAccepted(uint256 _id) internal view returns (bool) { // Find the request in the uint256 drHash = wrb.readDrHash(_id); // If the hash of the data request transaction in Witnet is not the default, then it means that inclusion of the // request has been proven to the WRB. return drHash != 0; } /** * @notice Upgrade the rewards for a Data Request previously included. * @dev Call to `upgrade_dr` function in the WitnetRequestsBoard contract. * @param _id The sequential identifier of a request that has been previously sent to the WitnetRequestsBoard. * @param _requestReward Reward specified for the user which posts the request into Witnet * @param _resultReward Reward specified for the user which post the Data Request result. */ function witnetUpgradeRequest(uint256 _id, uint256 _requestReward, uint256 _resultReward) internal validRewards(_requestReward, _resultReward) { wrb.upgradeDataRequest.value(msg.value)(_id, _resultReward); } /** * @notice Read the result of a resolved request. * @dev Call to `read_result` function in the WitnetRequestsBoard contract. * @param _id The sequential identifier of a request that was posted to Witnet. * @return The result of the request as an instance of `Result`. */ function witnetReadResult(uint256 _id) internal view returns (Witnet.Result memory) { return Witnet.resultFromCborBytes(wrb.readResult(_id)); } } // File: adomedianizer/contracts/IERC2362.sol /** * @dev EIP2362 Interface for pull oracles * https://github.com/tellor-io/EIP-2362 */ interface IERC2362 { /** * @dev Exposed function pertaining to EIP standards * @param _id bytes32 ID of the query * @return int,uint,uint returns the value, timestamp, and status code of query */ function valueFor(bytes32 _id) external view returns(int256,uint256,uint256); } // File: witnet-price-feeds-examples/contracts/requests/BitcoinPrice.sol // The bytecode of the BitcoinPrice request that will be sent to Witnet contract BitcoinPriceRequest is Request { constructor () Request(hex"0abb0108c3aafbf405123b122468747470733a2f2f7777772e6269747374616d702e6e65742f6170692f7469636b65722f1a13841877821864646c6173748218571903e8185b125c123168747470733a2f2f6170692e636f696e6465736b2e636f6d2f76312f6270692f63757272656e7470726963652e6a736f6e1a2786187782186663627069821866635553448218646a726174655f666c6f61748218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { } } // File: witnet-price-feeds-examples/contracts/bitcoin_price_feed/BtcUsdPriceFeed.sol // Import the UsingWitnet library that enables interacting with Witnet // Import the ERC2362 interface // Import the BitcoinPrice request that you created before // Your contract needs to inherit from UsingWitnet contract BtcUsdPriceFeed is UsingWitnet, IERC2362 { // The public Bitcoin price point uint64 public lastPrice; // Stores the ID of the last Witnet request uint256 public lastRequestId; // Stores the timestamp of the last time the public price point was updated uint256 public timestamp; // Tells if an update has been requested but not yet completed bool public pending; // The Witnet request object, is set in the constructor Request public request; // Emits when the price is updated event priceUpdated(uint64); // Emits when found an error decoding request result event resultError(string); // This is `keccak256("Price-BTC/USD-3")` bytes32 constant public BTCUSD3ID = bytes32(hex"637b7efb6b620736c247aaa282f3898914c0bef6c12faff0d3fe9d4bea783020"); // This constructor does a nifty trick to tell the `UsingWitnet` library where // to find the Witnet contracts on whatever Ethereum network you use. constructor (address _wrb) UsingWitnet(_wrb) public { // Instantiate the Witnet request request = new BitcoinPriceRequest(); } /** * @notice Sends `request` to the WitnetRequestsBoard. * @dev This method will only succeed if `pending` is 0. **/ function requestUpdate() public payable { require(!pending, "An update is already pending. Complete it first before requesting another update."); // Amount to pay to the bridge node relaying this request from Ethereum to Witnet uint256 _witnetRequestReward = 100 szabo; // Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum uint256 _witnetResultReward = 100 szabo; // Send the request to Witnet and store the ID for later retrieval of the result // The `witnetPostRequest` method comes with `UsingWitnet` lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward); // Signal that there is already a pending request pending = true; } /** * @notice Reads the result, if ready, from the WitnetRequestsBoard. * @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to * protect your methods from being called before the request has been successfully * relayed into Witnet. **/ function completeUpdate() public witnetRequestAccepted(lastRequestId) { require(pending, "There is no pending update."); // Read the result of the Witnet request // The `witnetReadResult` method comes with `UsingWitnet` Witnet.Result memory result = witnetReadResult(lastRequestId); // If the Witnet request succeeded, decode the result and update the price point // If it failed, revert the transaction with a pretty-printed error message if (result.isOk()) { lastPrice = result.asUint64(); timestamp = block.timestamp; emit priceUpdated(lastPrice); } else { string memory errorMessage; // Try to read the value as an error message, catch error bytes if read fails try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) { errorMessage = e; } catch (bytes memory errorBytes){ errorMessage = string(errorBytes); } emit resultError(errorMessage); } // In any case, set `pending` to false so a new update can be requested pending = false; } /** * @notice Exposes the public data point in an ERC2362 compliant way. * @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called * successfully before. **/ function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) { // Unsupported data point ID if(_id != BTCUSD3ID) return(0, 0, 400); // No value is yet available for the queried data point ID if (timestamp == 0) return(0, 0, 404); int256 value = int256(lastPrice); return(value, timestamp, 200); } } // File: witnet-price-feeds-examples/contracts/requests/EthPrice.sol // The bytecode of the EthPrice request that will be sent to Witnet contract EthPriceRequest is Request { constructor () Request(hex"0a850208d7affbf4051245122e68747470733a2f2f7777772e6269747374616d702e6e65742f6170692f76322f7469636b65722f6574687573642f1a13841877821864646c6173748218571903e8185b1247122068747470733a2f2f6170692e636f696e6361702e696f2f76322f6173736574731a238618778218616464617461821818018218646870726963655573648218571903e8185b1253122668747470733a2f2f6170692e636f696e70617072696b612e636f6d2f76312f7469636b6572731a29871876821818038218666671756f746573821866635553448218646570726963658218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { } } // File: witnet-price-feeds-examples/contracts/eth_price_feed/EthUsdPriceFeed.sol // Import the UsingWitnet library that enables interacting with Witnet // Import the ERC2362 interface // Import the ethPrice request that you created before // Your contract needs to inherit from UsingWitnet contract EthUsdPriceFeed is UsingWitnet, IERC2362 { // The public eth price point uint64 public lastPrice; // Stores the ID of the last Witnet request uint256 public lastRequestId; // Stores the timestamp of the last time the public price point was updated uint256 public timestamp; // Tells if an update has been requested but not yet completed bool public pending; // The Witnet request object, is set in the constructor Request public request; // Emits when the price is updated event priceUpdated(uint64); // Emits when found an error decoding request result event resultError(string); // This is the ERC2362 identifier for a eth price feed, computed as `keccak256("Price-ETH/USD-3")` bytes32 constant public ETHUSD3ID = bytes32(hex"dfaa6f747f0f012e8f2069d6ecacff25f5cdf0258702051747439949737fc0b5"); // This constructor does a nifty trick to tell the `UsingWitnet` library where // to find the Witnet contracts on whatever Ethereum network you use. constructor (address _wrb) UsingWitnet(_wrb) public { // Instantiate the Witnet request request = new EthPriceRequest(); } /** * @notice Sends `request` to the WitnetRequestsBoard. * @dev This method will only succeed if `pending` is 0. **/ function requestUpdate() public payable { require(!pending, "An update is already pending. Complete it first before requesting another update."); // Amount to pay to the bridge node relaying this request from Ethereum to Witnet uint256 _witnetRequestReward = 100 szabo; // Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum uint256 _witnetResultReward = 100 szabo; // Send the request to Witnet and store the ID for later retrieval of the result // The `witnetPostRequest` method comes with `UsingWitnet` lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward); // Signal that there is already a pending request pending = true; } /** * @notice Reads the result, if ready, from the WitnetRequestsBoard. * @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to * protect your methods from being called before the request has been successfully * relayed into Witnet. **/ function completeUpdate() public witnetRequestAccepted(lastRequestId) { require(pending, "There is no pending update."); // Read the result of the Witnet request // The `witnetReadResult` method comes with `UsingWitnet` Witnet.Result memory result = witnetReadResult(lastRequestId); // If the Witnet request succeeded, decode the result and update the price point // If it failed, revert the transaction with a pretty-printed error message if (result.isOk()) { lastPrice = result.asUint64(); timestamp = block.timestamp; emit priceUpdated(lastPrice); } else { string memory errorMessage; // Try to read the value as an error message, catch error bytes if read fails try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) { errorMessage = e; } catch (bytes memory errorBytes){ errorMessage = string(errorBytes); } emit resultError(errorMessage); } // In any case, set `pending` to false so a new update can be requested pending = false; } /** * @notice Exposes the public data point in an ERC2362 compliant way. * @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called * successfully before. **/ function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) { // Unsupported data point ID if(_id != ETHUSD3ID) return(0, 0, 400); // No value is yet available for the queried data point ID if (timestamp == 0) return(0, 0, 404); int256 value = int256(lastPrice); return(value, timestamp, 200); } } // File: witnet-price-feeds-examples/contracts/requests/GoldPrice.sol // The bytecode of the GoldPrice request that will be sent to Witnet contract GoldPriceRequest is Request { constructor () Request(hex"0ab90308c3aafbf4051257123f68747470733a2f2f636f696e7965702e636f6d2f6170692f76312f3f66726f6d3d58415526746f3d455552266c616e673d657326666f726d61743d6a736f6e1a148418778218646570726963658218571903e8185b1253122b68747470733a2f2f646174612d6173672e676f6c6470726963652e6f72672f64625852617465732f4555521a24861877821861656974656d73821818008218646878617550726963658218571903e8185b1255123668747470733a2f2f7777772e6d7963757272656e63797472616e736665722e636f6d2f6170692f63757272656e742f5841552f4555521a1b851877821866646461746182186464726174658218571903e8185b129101125d68747470733a2f2f7777772e696e766572736f726f2e65732f6461746f732f3f706572696f643d3379656172267869676e6974655f636f64653d5841552663757272656e63793d455552267765696768745f756e69743d6f756e6365731a308518778218666a7461626c655f64617461821864736d6574616c5f70726963655f63757272656e748218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { } } // File: witnet-price-feeds-examples/contracts/gold_price_feed/GoldEurPriceFeed.sol // Import the UsingWitnet library that enables interacting with Witnet // Import the ERC2362 interface // Import the goldPrice request that you created before // Your contract needs to inherit from UsingWitnet contract GoldEurPriceFeed is UsingWitnet, IERC2362 { // The public gold price point uint64 public lastPrice; // Stores the ID of the last Witnet request uint256 public lastRequestId; // Stores the timestamp of the last time the public price point was updated uint256 public timestamp; // Tells if an update has been requested but not yet completed bool public pending; // The Witnet request object, is set in the constructor Request public request; // Emits when the price is updated event priceUpdated(uint64); // Emits when found an error decoding request result event resultError(string); // This is the ERC2362 identifier for a gold price feed, computed as `keccak256("Price-XAU/EUR-3")` bytes32 constant public XAUEUR3ID = bytes32(hex"68cba0705475e40c1ddbf7dc7c1ae4e7320ca094c4e118d1067c4dea5df28590"); // This constructor does a nifty trick to tell the `UsingWitnet` library where // to find the Witnet contracts on whatever Ethereum network you use. constructor (address _wrb) UsingWitnet(_wrb) public { // Instantiate the Witnet request request = new GoldPriceRequest(); } /** * @notice Sends `request` to the WitnetRequestsBoard. * @dev This method will only succeed if `pending` is 0. **/ function requestUpdate() public payable { require(!pending, "An update is already pending. Complete it first before requesting another update."); // Amount to pay to the bridge node relaying this request from Ethereum to Witnet uint256 _witnetRequestReward = 100 szabo; // Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum uint256 _witnetResultReward = 100 szabo; // Send the request to Witnet and store the ID for later retrieval of the result // The `witnetPostRequest` method comes with `UsingWitnet` lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward); // Signal that there is already a pending request pending = true; } /** * @notice Reads the result, if ready, from the WitnetRequestsBoard. * @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to * protect your methods from being called before the request has been successfully * relayed into Witnet. **/ function completeUpdate() public witnetRequestAccepted(lastRequestId) { require(pending, "There is no pending update."); // Read the result of the Witnet request // The `witnetReadResult` method comes with `UsingWitnet` Witnet.Result memory result = witnetReadResult(lastRequestId); // If the Witnet request succeeded, decode the result and update the price point // If it failed, revert the transaction with a pretty-printed error message if (result.isOk()) { lastPrice = result.asUint64(); timestamp = block.timestamp; emit priceUpdated(lastPrice); } else { string memory errorMessage; // Try to read the value as an error message, catch error bytes if read fails try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) { errorMessage = e; } catch (bytes memory errorBytes){ errorMessage = string(errorBytes); } emit resultError(errorMessage); } // In any case, set `pending` to false so a new update can be requested pending = false; } /** * @notice Exposes the public data point in an ERC2362 compliant way. * @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called * successfully before. **/ function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) { // Unsupported data point ID if(_id != XAUEUR3ID) return(0, 0, 400); // No value is yet available for the queried data point ID if (timestamp == 0) return(0, 0, 404); int256 value = int256(lastPrice); return(value, timestamp, 200); } } // File: contracts/Deployer.sol // Import witnet-ethereum-block-relay-contracts // Import the UsingWitnet library that enables interacting with Witnet // Import price feeds contract Deployer { } // File: contracts/Migrations.sol contract Migrations { address public owner; uint public lastCompletedMigration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint _completed) public restricted { lastCompletedMigration = _completed; } function upgrade(address _newAddress) public restricted { Migrations upgraded = Migrations(_newAddress); upgraded.setCompleted(lastCompletedMigration); } }
* @notice Decode a CBOR.Value structure from raw bytes. @dev This is an alternate factory for CBOR.Value instances, which can be later decoded into native EVM types. @param _buffer A Buffer structure representing a CBOR-encoded value. @return A `CBOR.Value` instance containing a partially decoded value./ Extract basic CBOR properties from input bytes Early CBOR tag parsing.
function valueFromBuffer(BufferLib.Buffer memory _buffer) public pure returns(Value memory) { require(_buffer.data.length > 0, "Found empty buffer when parsing CBOR value"); uint8 initialByte; uint8 majorType = 255; uint8 additionalInformation; uint64 length; uint64 tag = UINT64_MAX; bool isTagged = true; while (isTagged) { initialByte = _buffer.readUint8(); majorType = initialByte >> 5; additionalInformation = initialByte & 0x1f; if (majorType == 6) { tag = readLength(_buffer, additionalInformation); isTagged = false; } } require(majorType <= 7, "Invalid CBOR major type"); return CBOR.Value( _buffer, initialByte, majorType, additionalInformation, length, tag); }
901,242
[ 1, 6615, 279, 21262, 916, 18, 620, 3695, 628, 1831, 1731, 18, 225, 1220, 353, 392, 12184, 3272, 364, 21262, 916, 18, 620, 3884, 16, 1492, 848, 506, 5137, 6383, 1368, 6448, 512, 7397, 1953, 18, 225, 389, 4106, 432, 3525, 3695, 5123, 279, 21262, 916, 17, 10787, 460, 18, 327, 432, 1375, 8876, 916, 18, 620, 68, 791, 4191, 279, 19976, 6383, 460, 18, 19, 8152, 5337, 21262, 916, 1790, 628, 810, 1731, 512, 20279, 21262, 916, 1047, 5811, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 460, 1265, 1892, 12, 1892, 5664, 18, 1892, 3778, 389, 4106, 13, 1071, 16618, 1135, 12, 620, 3778, 13, 288, 203, 565, 2583, 24899, 4106, 18, 892, 18, 2469, 405, 374, 16, 315, 2043, 1008, 1613, 1347, 5811, 21262, 916, 460, 8863, 203, 203, 565, 2254, 28, 2172, 3216, 31, 203, 565, 2254, 28, 7888, 559, 273, 4561, 31, 203, 565, 2254, 28, 3312, 5369, 31, 203, 565, 2254, 1105, 769, 31, 203, 565, 2254, 1105, 1047, 273, 27011, 1105, 67, 6694, 31, 203, 203, 565, 1426, 353, 18674, 273, 638, 31, 203, 565, 1323, 261, 291, 18674, 13, 288, 203, 1377, 2172, 3216, 273, 389, 4106, 18, 896, 5487, 28, 5621, 203, 1377, 7888, 559, 273, 2172, 3216, 1671, 1381, 31, 203, 1377, 3312, 5369, 273, 2172, 3216, 473, 374, 92, 21, 74, 31, 203, 203, 1377, 309, 261, 14019, 559, 422, 1666, 13, 288, 203, 3639, 1047, 273, 855, 1782, 24899, 4106, 16, 3312, 5369, 1769, 203, 3639, 353, 18674, 273, 629, 31, 203, 1377, 289, 203, 565, 289, 203, 203, 565, 2583, 12, 14019, 559, 1648, 2371, 16, 315, 1941, 21262, 916, 7888, 618, 8863, 203, 203, 565, 327, 21262, 916, 18, 620, 12, 203, 1377, 389, 4106, 16, 203, 1377, 2172, 3216, 16, 203, 1377, 7888, 559, 16, 203, 1377, 3312, 5369, 16, 203, 1377, 769, 16, 203, 1377, 1047, 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 ]
pragma solidity 0.4.24; // File: contracts/commons/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: contracts/base/BaseExchangeableTokenInterface.sol interface BaseExchangeableTokenInterface { // Sender interface must have: // mapping(address => uint) private exchangedWith; // mapping(address => uint) private exchangedBy; // Receiver interface must have: // mapping(address => uint) private exchangesReceived; /// @dev Fired if token exchange complete event Exchange(address _from, address _targetContract, uint _amount); /// @dev Fired if token exchange and spent complete event ExchangeSpent(address _from, address _targetContract, address _to, uint _amount); // Sender interface function exchangeToken(address _targetContract, uint _amount) external returns (bool success, uint creditedAmount); function exchangeAndSpend(address _targetContract, uint _amount, address _to) external returns (bool success); function __exchangerCallback(address _targetContract, address _exchanger, uint _amount) external returns (bool success); // Receiver interface function __targetExchangeCallback(uint _amount) external returns (bool success); function __targetExchangeAndSpendCallback(address _to, uint _amount) external returns (bool success); } // File: contracts/flavours/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/flavours/Lockable.sol /** * @title Lockable * @dev Base contract which allows children to * implement main operations locking mechanism. */ contract Lockable is Ownable { event Lock(); event Unlock(); bool public locked = false; /** * @dev Modifier to make a function callable * only when the contract is not locked. */ modifier whenNotLocked() { require(!locked); _; } /** * @dev Modifier to make a function callable * only when the contract is locked. */ modifier whenLocked() { require(locked); _; } /** * @dev called by the owner to lock, triggers locked state */ function lock() public onlyOwner whenNotLocked { locked = true; emit Lock(); } /** * @dev called by the owner * to unlock, returns to unlocked state */ function unlock() public onlyOwner whenLocked { locked = false; emit Unlock(); } } // File: contracts/base/BaseFixedERC20Token.sol contract BaseFixedERC20Token is Lockable { using SafeMath for uint; /// @dev ERC20 Total supply uint public totalSupply; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) private allowed; /// @dev Fired if token is transferred according to ERC20 spec event Transfer(address indexed from, address indexed to, uint value); /// @dev Fired if token withdrawal is approved according to ERC20 spec event Approval(address indexed owner, address indexed spender, uint value); /** * @dev Gets the balance of the specified address * @param owner_ The address to query the the balance of * @return An uint representing the amount owned by the passed address */ function balanceOf(address owner_) public view returns (uint balance) { return balances[owner_]; } /** * @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_, uint value_) public whenNotLocked returns (bool) { require(to_ != address(0) && value_ <= balances[msg.sender]); // SafeMath.sub will throw an exception if there is not enough balance balances[msg.sender] = balances[msg.sender].sub(value_); balances[to_] = balances[to_].add(value_); emit Transfer(msg.sender, to_, value_); return true; } /** * @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_ uint the amount of tokens to be transferred */ function transferFrom(address from_, address to_, uint value_) public whenNotLocked returns (bool) { require(to_ != address(0) && value_ <= balances[from_] && value_ <= allowed[from_][msg.sender]); balances[from_] = balances[from_].sub(value_); balances[to_] = balances[to_].add(value_); allowed[from_][msg.sender] = allowed[from_][msg.sender].sub(value_); emit Transfer(from_, to_, value_); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering * * 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 in: * 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_, uint value_) public whenNotLocked returns (bool) { if (value_ != 0 && allowed[msg.sender][spender_] != 0) { revert(); } 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 uint specifying the amount of tokens still available for the spender */ function allowance(address owner_, address spender_) public view returns (uint) { return allowed[owner_][spender_]; } } // File: contracts/base/BaseTokenExchangeInterface.sol interface BaseTokenExchangeInterface { // Token exchange service contract must have: // address[] private registeredTokens; /// @dev Fired if token exchange complete event Exchange(address _from, address _by, uint _value, address _target); /// @dev Fired if token exchange and spent complete event ExchangeAndSpent(address _from, address _by, uint _value, address _target, address _to); function registerToken(address _token) external returns (bool success); function exchangeToken(address _targetContract, uint _amount) external returns (bool success, uint creditedAmount); function exchangeAndSpend(address _targetContract, uint _amount, address _to) external returns (bool success); } // File: contracts/base/BaseExchangeableToken.sol /** * @dev ERC20 and EIP-823 (exchangeable) compliant token. */ contract BaseExchangeableToken is BaseExchangeableTokenInterface, BaseFixedERC20Token { using SafeMath for uint; BaseTokenExchangeInterface public exchange; /// @dev Fired if token is change exchange. (extends EIP-823) event ExchangeChanged(address _exchange); /** * @dev Modifier to make a function callable * only when the exchange contract is set. */ modifier whenConfigured() { require(exchange != address(0)); _; } /** * @dev Modifier to make a function callable * only by exchange contract */ modifier onlyExchange() { require(msg.sender == address(exchange)); _; } // Sender interface /// @dev number of tokens exchanged to another tokens for each token address mapping(address => uint) private exchangedWith; /// @dev number of tokens exchanged to another tokens for each user address mapping(address => uint) private exchangedBy; // Receiver interface /// @dev number of tokens exchanged from another tokens for each token address mapping(address => uint) private exchangesReceived; /// @dev change exchange for this token. (extends EIP-823) function changeExchange(address _exchange) public onlyOwner { require(_exchange != address(0)); exchange = BaseTokenExchangeInterface(_exchange); emit ExchangeChanged(_exchange); } // Sender interface /** * @dev exchange amount of this token to target token * @param _targetContract target token contract * @param _amount amount of tokens to exchange * @return (true, creditedAmount) on success. * (false, 0) on: * nothing =) * revert on: * exchangeToken in exchange contract return (false, 0) * exchange address is not configured * balance of tokens less then amount to exchange */ function exchangeToken(address _targetContract, uint _amount) public whenConfigured returns (bool success, uint creditedAmount) { require(_targetContract != address(0) && _amount <= balances[msg.sender]); (success, creditedAmount) = exchange.exchangeToken(_targetContract, _amount); if (!success) { revert(); } emit Exchange(msg.sender, _targetContract, _amount); return (success, creditedAmount); } /** * @dev exchange amount of this token to target token and transfer to specified address * @param _targetContract target token contract * @param _amount amount of tokens to exchange * @param _to address for transferring exchanged tokens * @return true on success. * false on: * nothing =) * revert on: * exchangeTokenAndSpend in exchange contract return false * exchange address is not configured * balance of tokens less then amount to exchange */ function exchangeAndSpend(address _targetContract, uint _amount, address _to) public whenConfigured returns (bool success) { require(_targetContract != address(0) && _to != address(0) && _amount <= balances[msg.sender]); success = exchange.exchangeAndSpend(_targetContract, _amount, _to); if (!success) { revert(); } emit ExchangeSpent(msg.sender, _targetContract, _to, _amount); return success; } /** * @dev send amount of this token to exchange. Must be called only from exchange contract * @param _targetContract target token contract * @param _exchanger address of user, who exchange tokens * @param _amount amount of tokens to exchange * @return true on success. * false on: * balance of tokens less then amount to exchange * revert on: * exchange address is not configured * called not by configured exchange address */ function __exchangerCallback(address _targetContract, address _exchanger, uint _amount) public whenConfigured onlyExchange returns (bool success) { require(_targetContract != address(0)); if (_amount > balances[_exchanger]) { return false; } balances[_exchanger] = balances[_exchanger].sub(_amount); exchangedWith[_targetContract] = exchangedWith[_targetContract].add(_amount); exchangedBy[_exchanger] = exchangedBy[_exchanger].add(_amount); return true; } // Receiver interface /** * @dev receive amount of tokens from exchange. Must be called only from exchange contract * @param _amount amount of tokens to receive * @return true on success. * false on: * nothing =) * revert on: * exchange address is not configured * called not by configured exchange address */ function __targetExchangeCallback(uint _amount) public whenConfigured onlyExchange returns (bool success) { balances[tx.origin] = balances[tx.origin].add(_amount); exchangesReceived[tx.origin] = exchangesReceived[tx.origin].add(_amount); emit Exchange(tx.origin, this, _amount); return true; } /** * @dev receive amount of tokens from exchange and transfer to specified address. Must be called only from exchange contract * @param _amount amount of tokens to receive * @param _to address for transferring exchanged tokens * @return true on success. * false on: * nothing =) * revert on: * exchange address is not configured * called not by configured exchange address */ function __targetExchangeAndSpendCallback(address _to, uint _amount) public whenConfigured onlyExchange returns (bool success) { balances[_to] = balances[_to].add(_amount); exchangesReceived[_to] = exchangesReceived[_to].add(_amount); emit ExchangeSpent(tx.origin, this, _to, _amount); return true; } } // File: contracts/BitoxToken.sol /** * @title Bitox token contract. */ contract BitoxToken is BaseExchangeableToken { using SafeMath for uint; string public constant name = "BitoxTokens"; string public constant symbol = "BITOX"; uint8 public constant decimals = 18; uint internal constant ONE_TOKEN = 1e18; constructor(uint totalSupplyTokens_) public { locked = false; totalSupply = totalSupplyTokens_ * ONE_TOKEN; address creator = msg.sender; balances[creator] = totalSupply; emit Transfer(0, this, totalSupply); emit Transfer(this, creator, balances[creator]); } // Disable direct payments function() external payable { revert(); } }
* @title Bitox token contract./
contract BitoxToken is BaseExchangeableToken { using SafeMath for uint; string public constant name = "BitoxTokens"; string public constant symbol = "BITOX"; uint8 public constant decimals = 18; uint internal constant ONE_TOKEN = 1e18; constructor(uint totalSupplyTokens_) public { locked = false; totalSupply = totalSupplyTokens_ * ONE_TOKEN; address creator = msg.sender; balances[creator] = totalSupply; emit Transfer(0, this, totalSupply); emit Transfer(this, creator, balances[creator]); } function() external payable { revert(); } }
5,842,210
[ 1, 5775, 2409, 1147, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6539, 2409, 1345, 353, 3360, 11688, 429, 1345, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 565, 533, 1071, 5381, 508, 273, 315, 5775, 2409, 5157, 14432, 203, 203, 565, 533, 1071, 5381, 3273, 273, 315, 15650, 22550, 14432, 203, 203, 565, 2254, 28, 1071, 5381, 15105, 273, 6549, 31, 203, 203, 565, 2254, 2713, 5381, 15623, 67, 8412, 273, 404, 73, 2643, 31, 203, 203, 203, 565, 3885, 12, 11890, 2078, 3088, 1283, 5157, 67, 13, 1071, 288, 203, 3639, 8586, 273, 629, 31, 203, 3639, 2078, 3088, 1283, 273, 2078, 3088, 1283, 5157, 67, 380, 15623, 67, 8412, 31, 203, 3639, 1758, 11784, 273, 1234, 18, 15330, 31, 203, 3639, 324, 26488, 63, 20394, 65, 273, 2078, 3088, 1283, 31, 203, 203, 3639, 3626, 12279, 12, 20, 16, 333, 16, 2078, 3088, 1283, 1769, 203, 3639, 3626, 12279, 12, 2211, 16, 11784, 16, 324, 26488, 63, 20394, 19226, 203, 565, 289, 203, 203, 565, 445, 1435, 3903, 8843, 429, 288, 203, 3639, 15226, 5621, 203, 565, 289, 203, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.2; /** * @title SKALEStorage * @dev Create, kill & retrieve code of contract */ contract SkaleStorage { // struct to save creation blockNumber and removing blockNumber struct BlockData { uint256 blockStarted; uint256 blockFinished; } // mapping contract => BlockData - save contract states mapping(address => BlockData) private _contractLife; /** * @dev stores that contract was created * @param contractAddress - address of contract * * contract should not be already created * contract should not be already killed */ function create(address contractAddress) public { require(_contractLife[contractAddress].blockStarted == 0, "Contract was already created"); require(_contractLife[contractAddress].blockFinished == 0, "Contract was already killed"); _contractLife[contractAddress].blockStarted = block.number; } /** * @dev stores that contract was killed * @param contractAddress - address of contract * * contract should be created * contract should be created before kill * contract should not be already killed */ function kill(address contractAddress) public { require(_contractLife[contractAddress].blockStarted != 0, "Contract was not created"); require(_contractLife[contractAddress].blockStarted <= block.number, "Contract will create after it killed"); require(_contractLife[contractAddress].blockFinished == 0, "Contract was already killed"); _contractLife[contractAddress].blockFinished = block.number; } function getBlockNumber(address contractAddress) public view returns(uint256 blockNumber){ return _contractLife[contractAddress].blockStarted; } /** * @dev returns code if exists * @param contractAddress - address of contract * @param blockNumber - number of block */ function getCode(address contractAddress, uint256 blockNumber) public view returns(bytes memory codeData) { if (_contractLife[contractAddress].blockStarted < blockNumber || _contractLife[contractAddress].blockFinished >= blockNumber) { codeData = ""; } assembly { // retrieve the size of the code, this needs assembly let size := extcodesize(contractAddress) // allocate output byte array - this could also be done without assembly // by using codeData = new bytes(size) codeData := mload(0x40) // new "memory end" including padding mstore(0x40, add(codeData, and(add(add(size, 0x20), 0x1f), not(0x1f)))) // store length in memory mstore(codeData, size) // actually retrieve the code, this needs assembly extcodecopy(contractAddress, add(codeData, 0x20), 0, size) } } }
* @dev stores that contract was killed @param contractAddress - address of contract contract should be created contract should be created before kill contract should not be already killed/
function kill(address contractAddress) public { require(_contractLife[contractAddress].blockStarted != 0, "Contract was not created"); require(_contractLife[contractAddress].blockStarted <= block.number, "Contract will create after it killed"); require(_contractLife[contractAddress].blockFinished == 0, "Contract was already killed"); _contractLife[contractAddress].blockFinished = block.number; }
13,089,513
[ 1, 19632, 716, 6835, 1703, 24859, 225, 6835, 1887, 300, 1758, 434, 6835, 6835, 1410, 506, 2522, 6835, 1410, 506, 2522, 1865, 8673, 6835, 1410, 486, 506, 1818, 24859, 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, 8673, 12, 2867, 6835, 1887, 13, 1071, 288, 203, 3639, 2583, 24899, 16351, 15315, 63, 16351, 1887, 8009, 2629, 9217, 480, 374, 16, 315, 8924, 1703, 486, 2522, 8863, 203, 3639, 2583, 24899, 16351, 15315, 63, 16351, 1887, 8009, 2629, 9217, 1648, 1203, 18, 2696, 16, 315, 8924, 903, 752, 1839, 518, 24859, 8863, 203, 3639, 2583, 24899, 16351, 15315, 63, 16351, 1887, 8009, 2629, 10577, 422, 374, 16, 315, 8924, 1703, 1818, 24859, 8863, 203, 3639, 389, 16351, 15315, 63, 16351, 1887, 8009, 2629, 10577, 273, 1203, 18, 2696, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x9965cCd16803432C6a0842f1D5690f32E427aEDd/sources/contracts/LaunchpadRegistry.sol
* @dev Returns The Minted Work BaseURI For A Project/
function ViewBaseURIMintedWork(uint ProjectID) public view returns(string memory) { return Projects[ProjectID]._MetadataMintedWork; }
8,470,671
[ 1, 1356, 1021, 490, 474, 329, 4147, 3360, 3098, 2457, 432, 5420, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4441, 2171, 3098, 49, 474, 329, 2421, 12, 11890, 5420, 734, 13, 1071, 1476, 1135, 12, 1080, 3778, 13, 7010, 565, 288, 7010, 3639, 327, 30491, 63, 4109, 734, 65, 6315, 2277, 49, 474, 329, 2421, 31, 7010, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x1Fa85cbB83B065E5Eb3Ea302Dc49A9Cde7a5D47f/sources/MiniMeToken.sol
Then update the balance array with the new value for the address receiving the tokens
var previousBalanceTo = balanceOfAt(_to, block.number);
2,760,053
[ 1, 20112, 1089, 326, 11013, 526, 598, 326, 394, 460, 364, 326, 1758, 225, 15847, 326, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 569, 2416, 13937, 774, 273, 11013, 951, 861, 24899, 869, 16, 1203, 18, 2696, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0xFbd0aEef07bB33778E610741564F67Ccbcd551E7/sources/contracts/VestingMartin1.sol
@notice Allows a grant recipient to claim their vested tokens. Errors if no tokens have vested It is advised recipients check they are entitled to claim via `calculateGrantClaim` before calling this
function claimVestedTokens(uint256 _grantId) external { uint16 timeVested; uint256 amountVested; (timeVested, amountVested) = calculateGrantClaim(_grantId); require(amountVested > 0, "amountVested is 0"); Grant storage tokenGrant = tokenGrants[_grantId]; tokenGrant.daysClaimed = uint16(tokenGrant.daysClaimed+(timeVested)); tokenGrant.totalClaimed = uint256(tokenGrant.totalClaimed+(amountVested)); require(token.transfer(tokenGrant.recipient, amountVested), "no tokens"); emit GrantTokensClaimed(tokenGrant.recipient, amountVested); }
8,109,905
[ 1, 19132, 279, 7936, 8027, 358, 7516, 3675, 331, 3149, 2430, 18, 9372, 309, 1158, 2430, 1240, 331, 3149, 2597, 353, 1261, 26779, 12045, 866, 2898, 854, 3281, 305, 1259, 358, 7516, 3970, 1375, 11162, 9021, 9762, 68, 1865, 4440, 333, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 58, 3149, 5157, 12, 11890, 5034, 389, 16243, 548, 13, 3903, 288, 203, 3639, 2254, 2313, 813, 58, 3149, 31, 203, 3639, 2254, 5034, 3844, 58, 3149, 31, 203, 3639, 261, 957, 58, 3149, 16, 3844, 58, 3149, 13, 273, 4604, 9021, 9762, 24899, 16243, 548, 1769, 203, 3639, 2583, 12, 8949, 58, 3149, 405, 374, 16, 315, 8949, 58, 3149, 353, 374, 8863, 203, 203, 3639, 19689, 2502, 1147, 9021, 273, 1147, 29598, 63, 67, 16243, 548, 15533, 203, 3639, 1147, 9021, 18, 9810, 9762, 329, 273, 2254, 2313, 12, 2316, 9021, 18, 9810, 9762, 329, 15, 12, 957, 58, 3149, 10019, 203, 3639, 1147, 9021, 18, 4963, 9762, 329, 273, 2254, 5034, 12, 2316, 9021, 18, 4963, 9762, 329, 15, 12, 8949, 58, 3149, 10019, 203, 540, 203, 3639, 2583, 12, 2316, 18, 13866, 12, 2316, 9021, 18, 20367, 16, 3844, 58, 3149, 3631, 315, 2135, 2430, 8863, 203, 3639, 3626, 19689, 5157, 9762, 329, 12, 2316, 9021, 18, 20367, 16, 3844, 58, 3149, 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 ]